fix: unify stream cleanup and async request ownership
This commit is contained in:
1 parent
9b165a8971
commit
fb39af6c28
13 files changed
+667
-461
No files matched your search
@@ -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();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user