fix: unify stream cleanup and async request ownership

This commit is contained in:
手瓜一十雪 committed 2026-10-18 13:20:22 +08:00
1 parent 9b165a8971
commit fb39af6c28
13 files changed
+667 -461

No files matched your search

+4
View File
@@ -42,6 +42,10 @@ request headers. The backend still accepts `Authorization: Bearer <token>` for
existing clients when the dedicated header is absent. Both layers still require
their own valid credentials.
Late authentication failures from an old session do not sign out a newer session.
Live streams release subscriptions on disconnect and pause with the page.
Malformed stream data is reported; a debug stream invocation fails instead of silently succeeding.
## Process account detection
Process cards use QQ's local account data before injection and the hook's confirmed
+135 -250
View File
@@ -44,6 +44,7 @@ import {
type TotpStatus,
} from './types';
import { localStorageTokenStore } from './token-store';
import { readSseJson } from './sse';
import { WEBUI_SESSION_HEADER, webuiSessionHeaders } from './session-headers';
const DEFAULT_TOKEN_KEY = 'snowluma_token';
@@ -263,22 +264,13 @@ class HttpApiClient implements ApiClient {
return data.appearance;
},
uploadBackground: async (file) => {
// FormData must set its own multipart boundary, so this bypasses
// request() (which would force application/json) and attaches the
// bearer header directly — mirroring login()'s deliberate bypass.
const form = new FormData();
form.append('file', file);
const res = await fetch('/api/ui/background', {
const res = await this.request('/api/ui/background', {
method: 'POST',
headers: webuiSessionHeaders(this.currentToken),
body: form,
});
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
}
if (!res.ok) {
const payload = await readJson<ErrorPayload>(res);
throw new ApiError(
@@ -480,7 +472,8 @@ class HttpApiClient implements ApiClient {
// ---------- HTTP helpers ----------
async request(url: string, init: RequestInit = {}): Promise<Response> {
const headers = webuiSessionHeaders(this.currentToken, init.headers);
const token = this.currentToken;
const headers = webuiSessionHeaders(token, init.headers);
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
@@ -489,8 +482,7 @@ class HttpApiClient implements ApiClient {
const res = await this.fetchWithDeadline(url, { ...init, headers });
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
this.expireSession(token);
}
return res;
@@ -552,6 +544,15 @@ class HttpApiClient implements ApiClient {
// ---------- token management ----------
private expireSession(token: string | null): void {
if (!token || token !== this.currentToken) {
return;
}
this.setToken(null);
this.onUnauthorized?.();
}
private setToken(token: string | null): void {
const changed = this.currentToken !== token;
this.currentToken = token;
@@ -700,7 +701,7 @@ class HttpApiClient implements ApiClient {
// ---------- SSE ----------
/** Fetch-based SSE keeps the session token in a header and reconnects after transport loss. */
/** One active request per subscription, paused with the page and retried on disconnect. */
private openSseChannel<T>(
path: string,
onMessage: (data: T) => void,
@@ -713,24 +714,45 @@ class HttpApiClient implements ApiClient {
}
let disposed = false;
let suspended = false;
let active: AbortController | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
const page = typeof window !== 'undefined' && typeof document !== 'undefined';
const clearReconnect = () => {
const cancelReconnect = () => {
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
};
const disconnect = () => {
clearReconnect();
active?.abort();
const stopRequest = () => {
const request = active;
active = null;
request?.abort();
};
const dispose = () => {
if (disposed) {
return;
}
disposed = true;
cancelReconnect();
stopRequest();
if (page) {
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('pageshow', onPageShow);
document.removeEventListener('visibilitychange', onVisible);
document.removeEventListener('freeze', onPageHide);
}
onStatus?.('closed');
};
const scheduleReconnect = () => {
if (disposed || reconnectTimer !== null) {
if (disposed || suspended || reconnectTimer !== null) {
return;
}
@@ -742,7 +764,7 @@ class HttpApiClient implements ApiClient {
};
const connect = async () => {
if (disposed || active) {
if (disposed || suspended || active) {
return;
}
@@ -755,8 +777,6 @@ class HttpApiClient implements ApiClient {
const controller = new AbortController();
active = controller;
const isCurrent = () =>
!disposed && active === controller && !controller.signal.aborted;
try {
const response = await fetch(path, {
@@ -768,15 +788,14 @@ class HttpApiClient implements ApiClient {
signal: controller.signal,
});
if (!isCurrent()) {
if (active !== controller || token !== this.currentToken) {
await response.body?.cancel();
return;
}
if (response.status === 401) {
dispose();
this.setToken(null);
this.onUnauthorized?.();
this.expireSession(token);
return;
}
@@ -785,108 +804,54 @@ class HttpApiClient implements ApiClient {
}
onStatus?.('open');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
try {
while (isCurrent()) {
const { done, value } = await reader.read();
if (!isCurrent()) {
break;
}
if (done) {
buffer += decoder.decode();
break;
}
buffer += decoder.decode(value, { stream: true });
if (buffer.length > 1024 * 1024) {
throw new Error('SSE frame buffer exceeded 1 MiB');
}
while (isCurrent()) {
const lf = buffer.indexOf('\n\n');
const crlf = buffer.indexOf('\r\n\r\n');
let separator = -1;
let separatorLength = 0;
if (lf >= 0 && (crlf < 0 || lf < crlf)) {
separator = lf;
separatorLength = 2;
} else if (crlf >= 0) {
separator = crlf;
separatorLength = 4;
}
if (separator < 0) {
break;
}
const block = buffer.slice(0, separator);
buffer = buffer.slice(separator + separatorLength);
const data = block
.split(/\r?\n/u)
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).replace(/^ /u, ''))
.join('\n');
if (!data) {
continue;
}
try {
onMessage(JSON.parse(data) as T);
} catch {
/* malformed frame — skip */
}
}
for await (const frame of readSseJson<T>(response.body, controller.signal)) {
if (active !== controller || token !== this.currentToken) {
break;
}
} finally {
try {
await reader.cancel();
} catch {
/* already closed */
onMessage(frame);
} catch (error) {
console.error('实时消息处理失败', error);
}
reader.releaseLock();
}
if (isCurrent()) {
scheduleReconnect();
}
} catch {
if (isCurrent()) {
scheduleReconnect();
} catch (error) {
if (!controller.signal.aborted) {
console.warn('实时连接中断', error);
}
} finally {
if (active === controller) {
active = null;
scheduleReconnect();
}
}
};
const onPageHide = disconnect;
const onPageHide = () => {
suspended = true;
cancelReconnect();
stopRequest();
};
const resume = () => {
suspended = false;
cancelReconnect();
void connect();
};
const onPageShow = (event: PageTransitionEvent) => {
if (event.persisted && !disposed) {
clearReconnect();
void connect();
if (event.persisted) {
resume();
}
};
const onVisible = () => {
if (document.visibilityState === 'visible' && !disposed && !active) {
clearReconnect();
void connect();
if (document.visibilityState === 'visible') {
resume();
}
};
const page = typeof window !== 'undefined' && typeof document !== 'undefined';
if (page) {
window.addEventListener('pagehide', onPageHide);
window.addEventListener('pageshow', onPageShow);
@@ -894,41 +859,22 @@ class HttpApiClient implements ApiClient {
document.addEventListener('freeze', onPageHide);
}
const dispose = () => {
if (disposed) {
return;
}
disposed = true;
if (page) {
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('pageshow', onPageShow);
document.removeEventListener('visibilitychange', onVisible);
document.removeEventListener('freeze', onPageHide);
}
disconnect();
onStatus?.('closed');
};
void connect();
return dispose;
}
private openLogStream(options: LogsStreamOptions): () => void {
this.logSubscribers.add(options);
const subscription = { ...options };
this.logSubscribers.add(subscription);
if (this.logStreamDispose) {
// A late subscriber joins the already-live shared connection — replay the
// current transport status so its badge isn't stuck at the default.
options.onStatus?.(this.lastLogStatus);
subscription.onStatus?.(this.lastLogStatus);
} else {
this.openSharedLogStream();
}
return () => {
this.logSubscribers.delete(options);
this.logSubscribers.delete(subscription);
if (this.logSubscribers.size === 0 && this.logStreamDispose) {
this.logStreamDispose();
@@ -938,7 +884,7 @@ class HttpApiClient implements ApiClient {
};
}
/** Isolate subscribers and leave unauthenticated attempts free to reconnect after login. */
/** Share one connection, isolating subscriber failures and skipping removed listeners. */
private openSharedLogStream(): void {
if (!this.currentToken) {
this.lastLogStatus = 'closed';
@@ -990,7 +936,7 @@ class HttpApiClient implements ApiClient {
);
}
/** A new request must pick up the changed session token. */
/** Replace the connection when its session token changes. */
private reopenSharedLogStream(): void {
if (this.logStreamDispose) {
this.logStreamDispose();
@@ -1004,9 +950,6 @@ class HttpApiClient implements ApiClient {
}
}
// Invoke a (stream) action and relay each `data: <json>\n\n` SSE frame. Uses
// fetch + a body reader (not EventSource) so the bearer token rides in the
// header and the request can be a POST. Resolves when the stream ends.
private async openDebugInvokeStream(
uin: string,
action: string,
@@ -1014,7 +957,8 @@ class HttpApiClient implements ApiClient {
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
signal?: AbortSignal,
): Promise<void> {
const headers = webuiSessionHeaders(this.currentToken, {
const token = this.currentToken;
const headers = webuiSessionHeaders(token, {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
'Cache-Control': 'no-cache',
@@ -1029,8 +973,7 @@ class HttpApiClient implements ApiClient {
});
if (res.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
this.expireSession(token);
throw new ApiError(401, '未授权');
}
@@ -1043,137 +986,79 @@ class HttpApiClient implements ApiClient {
);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = '';
const takeFrames = (raw: string) => {
for (;;) {
const lf = raw.indexOf('\n\n');
const crlf = raw.indexOf('\r\n\r\n');
let separator = -1;
let separatorLength = 0;
if (lf >= 0 && (crlf < 0 || lf < crlf)) {
separator = lf;
separatorLength = 2;
} else if (crlf >= 0) {
separator = crlf;
separatorLength = 4;
}
if (separator < 0) {
return raw;
}
const block = raw.slice(0, separator);
raw = raw.slice(separator + separatorLength);
const data = block
.split(/\r?\n/u)
.filter((line) => line.startsWith('data:'))
.map((line) => line.slice(5).replace(/^ /u, ''))
.join('\n');
if (!data) {
continue;
}
try {
onFrame(JSON.parse(data) as import('@/types').DebugStreamFrame);
} catch {
/* skip malformed */
}
}
};
try {
for (;;) {
const { done, value } = await reader.read();
if (done) {
buf += decoder.decode();
takeFrames(buf);
break;
}
buf += decoder.decode(value, { stream: true });
if (buf.length > 1024 * 1024) {
throw new Error('SSE frame buffer exceeded 1 MiB');
}
buf = takeFrames(buf);
}
} finally {
try {
await reader.cancel();
} catch {
/* already closed */
}
try {
reader.releaseLock();
} catch {
/* already released */
}
for await (const frame of readSseJson<import('@/types').DebugStreamFrame>(
res.body,
signal,
)) {
onFrame(frame);
}
}
// Upload a browser file to a server temp path. Uses XHR (not fetch) so the
// upload progress callback can fire — fetch can't observe request-body
// progress. Returns the parsed { path, size }.
private uploadDebugFile(
/** XHR exposes upload progress; every settlement releases its abort listener. */
private async uploadDebugFile(
file: File,
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
): Promise<import('@/types').DebugUploadResult> {
return new Promise((resolve, reject) => {
const name = opts?.filename ?? file.name;
const xhr = new XMLHttpRequest();
xhr.open('POST', `/api/debug/upload?filename=${encodeURIComponent(name)}`);
const signal = opts?.signal;
if (this.currentToken) {
xhr.setRequestHeader(WEBUI_SESSION_HEADER, this.currentToken);
}
if (signal?.aborted) {
throw new ApiError(0, '上传已取消');
}
xhr.responseType = 'json';
const token = this.currentToken;
const xhr = new XMLHttpRequest();
const onAbort = () => xhr.abort();
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
opts?.onProgress?.(e.loaded / e.total);
}
};
try {
return await new Promise<import('@/types').DebugUploadResult>((resolve, reject) => {
const name = opts?.filename ?? file.name;
xhr.open('POST', '/api/debug/upload?filename=' + encodeURIComponent(name));
xhr.onload = () => {
if (xhr.status === 401) {
this.setToken(null);
this.onUnauthorized?.();
reject(new ApiError(401, '未授权'));
return;
if (token) {
xhr.setRequestHeader(WEBUI_SESSION_HEADER, token);
}
const body = (xhr.response ?? {}) as import('@/types').DebugUploadResult;
xhr.responseType = 'json';
if (xhr.status >= 200 && xhr.status < 300 && body.path) {
resolve(body);
} else {
reject(new ApiError(xhr.status, body.message || '上传失败'));
}
};
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
opts?.onProgress?.(event.loaded / event.total);
}
};
xhr.onerror = () => reject(new ApiError(0, '上传网络错误'));
xhr.onabort = () => reject(new ApiError(0, '上传已取消'));
xhr.onload = () => {
if (xhr.status === 401) {
this.expireSession(token);
reject(new ApiError(401, '未授权'));
return;
}
if (opts?.signal) {
if (opts.signal.aborted) {
xhr.abort();
return;
}
const body = xhr.response as import('@/types').DebugUploadResult | null;
opts.signal.addEventListener('abort', () => xhr.abort(), { once: true });
}
if (
xhr.status >= 200 &&
xhr.status < 300 &&
typeof body?.path === 'string' &&
body.path
) {
resolve(body);
} else {
reject(new ApiError(xhr.status, body?.message || '上传失败'));
}
};
xhr.send(file);
});
xhr.onerror = () => reject(new ApiError(0, '上传网络错误'));
xhr.onabort = () => reject(new ApiError(0, '上传已取消'));
signal?.addEventListener('abort', onAbort, { once: true });
xhr.send(file);
});
} finally {
signal?.removeEventListener('abort', onAbort);
xhr.onload = null;
xhr.onerror = null;
xhr.onabort = null;
xhr.upload.onprogress = null;
}
}
private openDebugStream(
+101
View File
@@ -0,0 +1,101 @@
import { ApiError } from './types';
const MAX_FRAME_CHARS = 1024 * 1024;
function createFrameDecoder() {
let line = '';
let data: string[] = [];
let frameChars = 0;
let skipLf = false;
return function* (chunk: string): Generator<string> {
for (const char of chunk) {
if (skipLf) {
skipLf = false;
if (char === '\n') {
continue;
}
}
frameChars += char.length;
if (frameChars > MAX_FRAME_CHARS) {
throw new ApiError(502, '实时数据帧过大', 'INVALID_RESPONSE');
}
if (char !== '\r' && char !== '\n') {
line += char;
continue;
}
skipLf = char === '\r';
if (line === '') {
const frame = data.join('\n');
data = [];
frameChars = 0;
if (frame) {
yield frame;
}
} else if (line.startsWith('data:')) {
const value = line.slice(5);
data.push(value.startsWith(' ') ? value.slice(1) : value);
} else if (line === 'data') {
data.push('');
}
line = '';
}
};
}
/** Read JSON data frames; incomplete events at EOF are discarded per SSE. */
export async function* readSseJson<T>(
body: ReadableStream<Uint8Array>,
signal?: AbortSignal,
): AsyncGenerator<T> {
const reader = body.getReader();
const decoder = new TextDecoder();
const decodeFrames = createFrameDecoder();
let cancellation: Promise<void> | undefined;
const cancel = () => {
// A failed body read also rejects cancel; preserve the original read error.
cancellation ??= reader.cancel().catch(() => {});
};
signal?.addEventListener('abort', cancel, { once: true });
try {
signal?.throwIfAborted();
for (;;) {
const { done, value } = await reader.read();
signal?.throwIfAborted();
for (const data of decodeFrames(decoder.decode(value, { stream: !done }))) {
signal?.throwIfAborted();
let parsed: T;
try {
parsed = JSON.parse(data) as T;
} catch {
throw new ApiError(502, '实时数据格式无效', 'INVALID_RESPONSE');
}
yield parsed;
}
if (done) {
return;
}
}
} finally {
signal?.removeEventListener('abort', cancel);
cancel();
await cancellation;
reader.releaseLock();
}
}
+1 -1
View File
@@ -322,6 +322,6 @@ export interface TokenStore {
export interface CreateApiClientOptions {
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
tokenStore?: TokenStore;
/** Fires whenever a request returns 401, after the token has been cleared. */
/** Fires when the current session expires, after its token has been cleared. */
onUnauthorized?: () => void;
}
@@ -12,6 +12,29 @@ afterEach(() => {
});
describe('WebUI authentication behind a Basic-auth proxy', () => {
it('does not clear a new session when an old request returns 401', async () => {
const old = Promise.withResolvers<Response>();
vi.stubGlobal(
'fetch',
vi.fn((url: string) =>
url === '/api/login'
? Promise.resolve(Response.json({ token: 'new-token' }))
: old.promise,
),
);
const save = vi.fn();
const onUnauthorized = vi.fn();
const client = createApiClient({
tokenStore: { load: () => sessionToken, save },
onUnauthorized,
});
const request = client.request('/api/old');
await client.login('password');
old.resolve(new Response(null, { status: 401 }));
await request;
expect(save.mock.calls).toEqual([['new-token']]);
expect(onUnauthorized).not.toHaveBeenCalled();
});
it.each([
{ kind: 'object', headers: { Authorization: proxyAuthorization } },
{ kind: 'Headers', headers: new Headers({ Authorization: proxyAuthorization }) },
@@ -10,6 +10,75 @@ describe('API client SSE lifecycle', () => {
vi.unstubAllGlobals();
});
it('keeps repeated log subscriptions independent even when they reuse options', async () => {
let stream!: ReadableStreamDefaultController<Uint8Array>;
const body = new ReadableStream<Uint8Array>({
start(controller) {
stream = controller;
},
});
const fetchMock = vi.fn().mockResolvedValue(new Response(body));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const options = { onLine: vi.fn() };
const first = client.logs.stream(options);
const second = client.logs.stream(options);
first();
first();
try {
stream.enqueue(encoder.encode('data: {"message":"still subscribed"}\n\n'));
await vi.waitFor(() => expect(options.onLine).toHaveBeenCalledOnce());
expect(fetchMock).toHaveBeenCalledOnce();
} finally {
second();
}
});
it('fails a debug invocation on malformed stream data', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('data: broken\n\n')));
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
await expect(
client.debug.invokeStream('12345', 'test_action', {}, vi.fn()),
).rejects.toMatchObject({ code: 'INVALID_RESPONSE' });
});
it('propagates a debug callback failure and cancels the remaining body', async () => {
const cancel = vi.fn();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoder.encode('data: {"type":"done"}\n\n'));
},
cancel,
});
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(body)));
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const error = new Error('callback failed');
await expect(
client.debug.invokeStream('12345', 'test_action', {}, () => {
throw error;
}),
).rejects.toBe(error);
expect(cancel).toHaveBeenCalledOnce();
expect(body.locked).toBe(false);
});
it('keeps only one connection when a restored page is also made visible', async () => {
const page = new EventTarget();
const document = Object.assign(new EventTarget(), { visibilityState: 'visible' });
vi.stubGlobal('window', page);
vi.stubGlobal('document', document);
const fetchMock = vi.fn(() => new Promise<Response>(() => {}));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const dispose = client.stateStream({ onEvent: vi.fn() });
page.dispatchEvent(new Event('pagehide'));
document.dispatchEvent(new Event('visibilitychange'));
page.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
expect(fetchMock).toHaveBeenCalledTimes(2);
dispose();
});
it('keeps Authorization available for the proxy while authenticating and parsing frames', async () => {
let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
const stream = new ReadableStream<Uint8Array>({
@@ -0,0 +1,85 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
class FakeUpload {
static instances: FakeUpload[] = [];
status = 200;
response: unknown = { status: 'ok', path: '/tmp/file', size: 3 };
responseType = '';
upload = { onprogress: null as ((event: ProgressEvent) => void) | null };
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
onabort: (() => void) | null = null;
sent = false;
constructor() {
FakeUpload.instances.push(this);
}
open() {}
setRequestHeader() {}
send() {
this.sent = true;
}
abort() {
if (this.sent) {
this.onabort?.();
}
}
}
beforeEach(() => {
FakeUpload.instances = [];
vi.stubGlobal('XMLHttpRequest', FakeUpload);
});
afterEach(() => vi.unstubAllGlobals());
describe('debug upload lifecycle', () => {
it('does not clear a new session when an old upload returns 401', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ token: 'new-token' })));
const save = vi.fn();
const onUnauthorized = vi.fn();
const client = createApiClient({
tokenStore: { load: () => 'old-token', save },
onUnauthorized,
});
const result = client.debug.upload(new File(['abc'], 'a.txt'));
const rejected = expect(result).rejects.toMatchObject({ status: 401 });
await client.login('password');
const upload = FakeUpload.instances[0]!;
upload.status = 401;
upload.onload?.();
await rejected;
expect(save.mock.calls).toEqual([['new-token']]);
expect(onUnauthorized).not.toHaveBeenCalled();
});
it('settles an already cancelled upload without sending a request', async () => {
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const signal = AbortSignal.abort();
const settled = vi.fn();
void client.debug.upload(new File(['abc'], 'a.txt'), { signal }).catch(settled);
await new Promise((resolve) => setTimeout(resolve, 0));
expect(settled).toHaveBeenCalledWith(expect.objectContaining({ message: '上传已取消' }));
expect(FakeUpload.instances.every((upload) => !upload.sent)).toBe(true);
});
it.each(['load', 'error', 'abort'] as const)(
'releases abort and XHR handlers after %s',
async (event) => {
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const controller = new AbortController();
const remove = vi.spyOn(controller.signal, 'removeEventListener');
const result = client.debug.upload(new File(['abc'], 'a.txt'), {
signal: controller.signal,
});
const settled = result.catch(() => undefined);
const upload = FakeUpload.instances[0]!;
upload[`on${event}`]?.();
await settled;
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
expect(upload.onload).toBeNull();
expect(upload.onerror).toBeNull();
expect(upload.onabort).toBeNull();
expect(upload.upload.onprogress).toBeNull();
},
);
});
+68
View File
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest';
import { readSseJson } from '../src/lib/api/sse';
const encoder = new TextEncoder();
async function read(chunks: Uint8Array[]): Promise<unknown[]> {
const body = new ReadableStream<Uint8Array>({
start(controller) {
for (const chunk of chunks) {
controller.enqueue(chunk);
}
controller.close();
},
});
const frames: unknown[] = [];
for await (const frame of readSseJson(body)) {
frames.push(frame);
}
return frames;
}
describe('SSE JSON reader', () => {
it.each(['\n', '\r\n', '\r'])('handles fragmented UTF-8 and %j line endings', async (eol) => {
const bytes = encoder.encode(
`: heartbeat${eol}data: {"text":${eol}data: "中文"}${eol}${eol}`,
);
expect(await read(Array.from(bytes, (byte) => Uint8Array.of(byte)))).toEqual([
{ text: '中文' },
]);
});
it('discards an incomplete event at EOF', async () => {
expect(await read([encoder.encode('data: {"unfinished":true}\n')])).toEqual([]);
});
it('limits individual frames rather than the size of a network chunk', async () => {
const frame = 'data: ' + JSON.stringify({ text: 'x'.repeat(600_000) }) + '\n\n';
expect(await read([encoder.encode(frame.repeat(2))])).toHaveLength(2);
await expect(
read([encoder.encode('data: ' + 'x'.repeat(1024 * 1024))]),
).rejects.toMatchObject({ code: 'INVALID_RESPONSE' });
});
it('reports malformed JSON instead of treating the operation as successful', async () => {
await expect(read([encoder.encode('data: broken\n\n')])).rejects.toMatchObject({
code: 'INVALID_RESPONSE',
});
});
it('cancels a pending read and releases the lock on abort', async () => {
let cancelled = false;
const body = new ReadableStream<Uint8Array>({
cancel() {
cancelled = true;
},
});
const controller = new AbortController();
const reader = readSseJson(body, controller.signal);
const result = reader.next();
controller.abort();
await expect(result).rejects.toMatchObject({ name: 'AbortError' });
expect(cancelled).toBe(true);
expect(body.locked).toBe(false);
});
});