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
@@ -43,11 +43,12 @@ export function sseResponse(
|
|||||||
closed = true;
|
closed = true;
|
||||||
clearInterval(heartbeat);
|
clearInterval(heartbeat);
|
||||||
signal.removeEventListener('abort', onAbort);
|
signal.removeEventListener('abort', onAbort);
|
||||||
cleanups.splice(0).forEach(cleanup);
|
|
||||||
|
|
||||||
if (closeStream) {
|
if (closeStream) {
|
||||||
controller.close();
|
controller.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cleanups.splice(0).forEach(cleanup);
|
||||||
};
|
};
|
||||||
|
|
||||||
const onAbort = () => teardown();
|
const onAbort = () => teardown();
|
||||||
|
|||||||
@@ -6,12 +6,7 @@ import type { MessageStore } from '../message-store';
|
|||||||
import type { OneBotInstanceContext } from '../instance-context';
|
import type { OneBotInstanceContext } from '../instance-context';
|
||||||
import { resolveRemoteMediaUrl } from '../media-url-resolver';
|
import { resolveRemoteMediaUrl } from '../media-url-resolver';
|
||||||
import { segmentsToRawMessage } from '../helper/cq';
|
import { segmentsToRawMessage } from '../helper/cq';
|
||||||
import {
|
import { pttTransKey, requestPttTransText } from './ptt-trans-waiter';
|
||||||
deliverPttTransText,
|
|
||||||
failPttTransWaiter,
|
|
||||||
pttTransKey,
|
|
||||||
waitPttTransText,
|
|
||||||
} from './ptt-trans-waiter';
|
|
||||||
import type { JsonObject, JsonValue } from '../types';
|
import type { JsonObject, JsonValue } from '../types';
|
||||||
|
|
||||||
const log = createLogger('OneBot');
|
const log = createLogger('OneBot');
|
||||||
@@ -197,15 +192,8 @@ export async function fetchPttText(
|
|||||||
// c2c: receiver is self (inbound voice); group: the group uin.
|
// c2c: receiver is self (inbound voice); group: the group uin.
|
||||||
const peerUin = isGroup ? Number(event.group_id) || cached.sessionId : selfId;
|
const peerUin = isGroup ? Number(event.group_id) || cached.sessionId : selfId;
|
||||||
|
|
||||||
// Register the waiter BEFORE triggering, so a fast async push can't race
|
const text = await requestPttTransText(pttTransKey(selfId, messageId), 20_000, () =>
|
||||||
// ahead of us. The trigger response may carry the text inline (already
|
bridge.apis.extras.translatePttToText({
|
||||||
// transcribed) — settle immediately then; otherwise the Event 0x210
|
|
||||||
// subType-61 push resolves the waiter via the event-pipeline subscription.
|
|
||||||
const key = pttTransKey(selfId, messageId);
|
|
||||||
const waiter = waitPttTransText(key, 20000);
|
|
||||||
|
|
||||||
try {
|
|
||||||
const syncText = await bridge.apis.extras.translatePttToText({
|
|
||||||
isGroup,
|
isGroup,
|
||||||
msgId: messageId,
|
msgId: messageId,
|
||||||
senderUin,
|
senderUin,
|
||||||
@@ -215,16 +203,9 @@ export async function fetchPttText(
|
|||||||
duration: cached.duration ?? 0,
|
duration: cached.duration ?? 0,
|
||||||
size: cached.fileSize ?? 0,
|
size: cached.fileSize ?? 0,
|
||||||
format: cached.voiceFormat ?? 0,
|
format: cached.voiceFormat ?? 0,
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
if (syncText) {
|
return { text };
|
||||||
deliverPttTransText(key, syncText);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
failPttTransWaiter(key, e instanceof Error ? e : new Error(String(e)));
|
|
||||||
}
|
|
||||||
|
|
||||||
return { text: await waiter };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getImageInfo(
|
export async function getImageInfo(
|
||||||
|
|||||||
@@ -1,69 +1,58 @@
|
|||||||
// Correlates an async voice-to-text result back to the fetch_ptt_text call
|
|
||||||
// that triggered it. QQ delivers the text via an Event 0x210 subType-61 push
|
|
||||||
// (decoded into a `ptt_trans_result` event), not in the request response — so
|
|
||||||
// the action registers a waiter keyed by `${selfUin}:${msgId}`, fires the
|
|
||||||
// trigger request, and the push subscription resolves the waiter by msgId.
|
|
||||||
|
|
||||||
interface Pending {
|
interface Pending {
|
||||||
resolve: (text: string) => void;
|
resolve(text: string): void;
|
||||||
reject: (err: Error) => void;
|
reject(error: Error): void;
|
||||||
timer: ReturnType<typeof setTimeout>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const pending = new Map<string, Pending>();
|
const pending = new Map<string, Pending>();
|
||||||
|
|
||||||
export function pttTransKey(selfUin: number, msgId: number): string {
|
export function pttTransKey(selfUin: number, msgId: number): string {
|
||||||
return `${selfUin}:${msgId}`;
|
return selfUin + ':' + msgId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Register before triggering; only this request may settle its own response or timeout. */
|
||||||
* Register a waiter for `key`'s transcription. Rejects after `timeoutMs`.
|
export function requestPttTransText(
|
||||||
* A new waiter for the same key supersedes (rejects) the previous one.
|
key: string,
|
||||||
*/
|
timeoutMs: number,
|
||||||
export function waitPttTransText(key: string, timeoutMs: number): Promise<string> {
|
trigger: () => Promise<string>,
|
||||||
const existing = pending.get(key);
|
): Promise<string> {
|
||||||
|
pending.get(key)?.reject(new Error('语音转文字请求被新的请求取代'));
|
||||||
if (existing) {
|
|
||||||
clearTimeout(existing.timer);
|
|
||||||
pending.delete(key);
|
|
||||||
existing.reject(new Error('语音转文字请求被新的请求取代'));
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Promise<string>((resolve, reject) => {
|
return new Promise<string>((resolve, reject) => {
|
||||||
const timer = setTimeout(() => {
|
const settle = (finish: () => void) => {
|
||||||
if (pending.get(key)?.timer === timer) {
|
if (pending.get(key) !== waiter) {
|
||||||
pending.delete(key);
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
reject(new Error('语音转文字超时(未收到结果推送)'));
|
clearTimeout(timer);
|
||||||
|
pending.delete(key);
|
||||||
|
finish();
|
||||||
|
};
|
||||||
|
|
||||||
|
const waiter: Pending = {
|
||||||
|
resolve: (text) => settle(() => resolve(text)),
|
||||||
|
reject: (error) => settle(() => reject(error)),
|
||||||
|
};
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
waiter.reject(new Error('语音转文字超时(未收到结果推送)'));
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
timer.unref();
|
timer.unref();
|
||||||
pending.set(key, { resolve, reject, timer });
|
pending.set(key, waiter);
|
||||||
|
|
||||||
|
void Promise.resolve()
|
||||||
|
.then(trigger)
|
||||||
|
.then(
|
||||||
|
(text) => {
|
||||||
|
if (text) {
|
||||||
|
waiter.resolve(text);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(error: unknown) =>
|
||||||
|
waiter.reject(error instanceof Error ? error : new Error(String(error))),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Resolve a waiting fetch_ptt_text with the recognised text. No-op if none. */
|
/** QQ push results identify the account and message, not an individual trigger request. */
|
||||||
export function deliverPttTransText(key: string, text: string): void {
|
export function deliverPttTransText(key: string, text: string): void {
|
||||||
const p = pending.get(key);
|
pending.get(key)?.resolve(text);
|
||||||
|
|
||||||
if (!p) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
clearTimeout(p.timer);
|
|
||||||
pending.delete(key);
|
|
||||||
p.resolve(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Reject a waiter (e.g. the trigger request itself failed). No-op if none. */
|
|
||||||
export function failPttTransWaiter(key: string, err: Error): void {
|
|
||||||
const p = pending.get(key);
|
|
||||||
|
|
||||||
if (!p) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
clearTimeout(p.timer);
|
|
||||||
pending.delete(key);
|
|
||||||
p.reject(err);
|
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,7 @@
|
|||||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||||
import { fetchPttText, getImageInfo, getRecordInfo } from '../src/modules/media-actions';
|
import { fetchPttText, getImageInfo, getRecordInfo } from '../src/modules/media-actions';
|
||||||
import {
|
import { deliverPttTransText, pttTransKey } from '../src/modules/ptt-trans-waiter';
|
||||||
deliverPttTransText,
|
|
||||||
failPttTransWaiter,
|
|
||||||
pttTransKey,
|
|
||||||
} from '../src/modules/ptt-trans-waiter';
|
|
||||||
import type { CachedImage, CachedRecord, MediaStore } from '../src/media-store';
|
import type { CachedImage, CachedRecord, MediaStore } from '../src/media-store';
|
||||||
import type { MessageStore } from '../src/message-store';
|
import type { MessageStore } from '../src/message-store';
|
||||||
import type { JsonObject } from '../src/types';
|
import type { JsonObject } from '../src/types';
|
||||||
@@ -21,7 +17,7 @@ afterEach(() => {
|
|||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
|
|
||||||
for (const key of usedPttKeys) {
|
for (const key of usedPttKeys) {
|
||||||
failPttTransWaiter(key, new Error('test cleanup'));
|
deliverPttTransText(key, 'test cleanup');
|
||||||
}
|
}
|
||||||
|
|
||||||
usedPttKeys.clear();
|
usedPttKeys.clear();
|
||||||
@@ -113,6 +109,60 @@ function fakeBridge(
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('fetchPttText', () => {
|
describe('fetchPttText', () => {
|
||||||
|
it('times out even while the trigger response is still pending', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
trackPttKey(SELF_ID, 40100);
|
||||||
|
const trigger = Promise.withResolvers<string>();
|
||||||
|
const settled = vi.fn();
|
||||||
|
const request = fetchPttText(
|
||||||
|
fakeMessageStore(recordEvent()),
|
||||||
|
fakeRecordStore(cachedRecord()),
|
||||||
|
fakeBridge({ translatePttToText: vi.fn(() => trigger.promise) }),
|
||||||
|
SELF_ID,
|
||||||
|
40100,
|
||||||
|
);
|
||||||
|
const done = request.then(settled, settled);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await vi.advanceTimersByTimeAsync(20_000);
|
||||||
|
expect(settled).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ message: '语音转文字超时(未收到结果推送)' }),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
trigger.resolve('late');
|
||||||
|
await done;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not let an old trigger failure reject the replacement request', async () => {
|
||||||
|
const key = trackPttKey(SELF_ID, 40101);
|
||||||
|
const trigger = Promise.withResolvers<string>();
|
||||||
|
const firstTrigger = vi.fn(() => trigger.promise);
|
||||||
|
const first = fetchPttText(
|
||||||
|
fakeMessageStore(recordEvent()),
|
||||||
|
fakeRecordStore(cachedRecord()),
|
||||||
|
fakeBridge({ translatePttToText: firstTrigger }),
|
||||||
|
SELF_ID,
|
||||||
|
40101,
|
||||||
|
).catch((error) => error);
|
||||||
|
await vi.waitFor(() => expect(firstTrigger).toHaveBeenCalledOnce());
|
||||||
|
const secondTrigger = vi.fn(async () => '');
|
||||||
|
const second = fetchPttText(
|
||||||
|
fakeMessageStore(recordEvent()),
|
||||||
|
fakeRecordStore(cachedRecord()),
|
||||||
|
fakeBridge({ translatePttToText: secondTrigger }),
|
||||||
|
SELF_ID,
|
||||||
|
40101,
|
||||||
|
);
|
||||||
|
const result = second.catch((error) => error);
|
||||||
|
|
||||||
|
await vi.waitFor(() => expect(secondTrigger).toHaveBeenCalledOnce());
|
||||||
|
trigger.reject(new Error('old trigger failed'));
|
||||||
|
await first;
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
|
deliverPttTransText(key, 'new text');
|
||||||
|
await expect(result).resolves.toEqual({ text: 'new text' });
|
||||||
|
});
|
||||||
it('throws when the message event is missing', async () => {
|
it('throws when the message event is missing', async () => {
|
||||||
await expect(
|
await expect(
|
||||||
fetchPttText(
|
fetchPttText(
|
||||||
|
|||||||
@@ -1,152 +1,102 @@
|
|||||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
import {
|
import {
|
||||||
deliverPttTransText,
|
deliverPttTransText,
|
||||||
failPttTransWaiter,
|
|
||||||
pttTransKey,
|
pttTransKey,
|
||||||
waitPttTransText,
|
requestPttTransText,
|
||||||
} from '../src/modules/ptt-trans-waiter';
|
} from '../src/modules/ptt-trans-waiter';
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => vi.useRealTimers());
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('pttTransKey', () => {
|
describe('PTT transcription requests', () => {
|
||||||
it('joins selfUin and msgId with a colon', () => {
|
it('keeps accounts isolated for the same message id', async () => {
|
||||||
expect(pttTransKey(1787882683, 4001)).toBe('1787882683:4001');
|
const first = requestPttTransText(pttTransKey(10001, 1), 20_000, async () => '');
|
||||||
expect(pttTransKey(10001, 42)).toBe('10001:42');
|
const second = requestPttTransText(pttTransKey(10002, 1), 20_000, async () => '');
|
||||||
expect(pttTransKey(0, 0)).toBe('0:0');
|
deliverPttTransText(pttTransKey(10001, 1), 'first');
|
||||||
});
|
deliverPttTransText(pttTransKey(10002, 1), 'second');
|
||||||
});
|
await expect(first).resolves.toBe('first');
|
||||||
|
await expect(second).resolves.toBe('second');
|
||||||
describe('waitPttTransText / deliverPttTransText', () => {
|
|
||||||
it('resolves with the delivered text', async () => {
|
|
||||||
const waiter = waitPttTransText('1787882683:4001', 20_000);
|
|
||||||
deliverPttTransText('1787882683:4001', '今天天气不错');
|
|
||||||
await expect(waiter).resolves.toBe('今天天气不错');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('resolves empty text the same way as any other string', async () => {
|
it.each(['text', ''])('accepts a pushed transcription: %j', async (text) => {
|
||||||
const waiter = waitPttTransText('10001:1', 20_000);
|
const result = requestPttTransText('account:push', 20_000, async () => '');
|
||||||
deliverPttTransText('10001:1', '');
|
deliverPttTransText('account:push', text);
|
||||||
await expect(waiter).resolves.toBe('');
|
await expect(result).resolves.toBe(text);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is a no-op when no waiter is registered', () => {
|
it('registers before triggering so an immediate push is not lost', async () => {
|
||||||
expect(() => deliverPttTransText('10001:missing', '不会被消费')).not.toThrow();
|
const result = requestPttTransText('account:fast', 20_000, async () => {
|
||||||
|
deliverPttTransText('account:fast', 'pushed');
|
||||||
|
return 'inline';
|
||||||
|
});
|
||||||
|
await expect(result).resolves.toBe('pushed');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is a no-op after the waiter has already settled', async () => {
|
it('accepts an inline transcription', async () => {
|
||||||
const waiter = waitPttTransText('10001:2', 20_000);
|
await expect(
|
||||||
deliverPttTransText('10001:2', '第一次');
|
requestPttTransText('account:inline', 20_000, async () => 'inline'),
|
||||||
await expect(waiter).resolves.toBe('第一次');
|
).resolves.toBe('inline');
|
||||||
expect(() => deliverPttTransText('10001:2', '第二次')).not.toThrow();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not resolve a different key', async () => {
|
it.each([new Error('failed'), 'failed'])(
|
||||||
const a = waitPttTransText('10001:10', 20_000);
|
'propagates a trigger failure: %s',
|
||||||
const b = waitPttTransText('10001:11', 20_000);
|
async (failure) => {
|
||||||
deliverPttTransText('10001:10', '甲');
|
await expect(
|
||||||
await expect(a).resolves.toBe('甲');
|
requestPttTransText('account:failure', 20_000, async () => {
|
||||||
failPttTransWaiter('10001:11', new Error('桥接失败'));
|
throw failure;
|
||||||
await expect(b).rejects.toThrow('桥接失败');
|
}),
|
||||||
|
).rejects.toThrow('failed');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('handles a synchronous trigger failure', async () => {
|
||||||
|
await expect(
|
||||||
|
requestPttTransText('account:sync-failure', 20_000, () => {
|
||||||
|
throw new Error('sync');
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('sync');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('allows a new waiter on the same key after settle', async () => {
|
it.each(['resolve', 'reject'] as const)(
|
||||||
const first = waitPttTransText('10001:3', 20_000);
|
'ignores a superseded trigger that later calls %s',
|
||||||
deliverPttTransText('10001:3', '一次');
|
async (settle) => {
|
||||||
await expect(first).resolves.toBe('一次');
|
const oldTrigger = Promise.withResolvers<string>();
|
||||||
|
const old = requestPttTransText('account:replace', 20_000, () => oldTrigger.promise);
|
||||||
|
const rejected = expect(old).rejects.toThrow('被新的请求取代');
|
||||||
|
const current = requestPttTransText('account:replace', 20_000, async () => '');
|
||||||
|
await rejected;
|
||||||
|
|
||||||
const second = waitPttTransText('10001:3', 20_000);
|
if (settle === 'resolve') {
|
||||||
deliverPttTransText('10001:3', '二次');
|
oldTrigger.resolve('stale');
|
||||||
await expect(second).resolves.toBe('二次');
|
} else {
|
||||||
});
|
oldTrigger.reject(new Error('stale'));
|
||||||
});
|
}
|
||||||
|
|
||||||
describe('failPttTransWaiter', () => {
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||||
it('rejects the waiter with the provided error', async () => {
|
deliverPttTransText('account:replace', 'current');
|
||||||
const err = new Error('触发失败');
|
await expect(current).resolves.toBe('current');
|
||||||
const waiter = waitPttTransText('10001:20', 20_000);
|
},
|
||||||
failPttTransWaiter('10001:20', err);
|
);
|
||||||
await expect(waiter).rejects.toBe(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is a no-op when no waiter is registered', () => {
|
it('times out while the trigger is pending and ignores its eventual failure', async () => {
|
||||||
expect(() => failPttTransWaiter('10001:gone', new Error('无人等待'))).not.toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is a no-op after the waiter has already settled', async () => {
|
|
||||||
const waiter = waitPttTransText('10001:21', 20_000);
|
|
||||||
failPttTransWaiter('10001:21', new Error('第一次失败'));
|
|
||||||
await expect(waiter).rejects.toThrow('第一次失败');
|
|
||||||
expect(() => failPttTransWaiter('10001:21', new Error('第二次失败'))).not.toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('waitPttTransText supersede', () => {
|
|
||||||
it('rejects the previous waiter when the same key is waited again', async () => {
|
|
||||||
const first = waitPttTransText('10001:30', 20_000);
|
|
||||||
const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代');
|
|
||||||
const second = waitPttTransText('10001:30', 20_000);
|
|
||||||
await firstRejected;
|
|
||||||
deliverPttTransText('10001:30', '新请求结果');
|
|
||||||
await expect(second).resolves.toBe('新请求结果');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('lets failPttTransWaiter settle only the replacement waiter', async () => {
|
|
||||||
const first = waitPttTransText('10001:31', 20_000);
|
|
||||||
const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代');
|
|
||||||
const second = waitPttTransText('10001:31', 20_000);
|
|
||||||
await firstRejected;
|
|
||||||
const err = new Error('trigger failed');
|
|
||||||
failPttTransWaiter('10001:31', err);
|
|
||||||
await expect(second).rejects.toBe(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not time out the replacement when the superseded timeout would have fired', async () => {
|
|
||||||
vi.useFakeTimers();
|
vi.useFakeTimers();
|
||||||
const first = waitPttTransText('10001:32', 1_000);
|
const trigger = Promise.withResolvers<string>();
|
||||||
const firstRejected = expect(first).rejects.toThrow('语音转文字请求被新的请求取代');
|
const result = requestPttTransText('account:timeout', 1_000, () => trigger.promise);
|
||||||
const second = waitPttTransText('10001:32', 20_000);
|
const rejected = expect(result).rejects.toThrow('超时');
|
||||||
await firstRejected;
|
|
||||||
await vi.advanceTimersByTimeAsync(1_000);
|
await vi.advanceTimersByTimeAsync(1_000);
|
||||||
deliverPttTransText('10001:32', '未被旧超时打断');
|
await rejected;
|
||||||
await expect(second).resolves.toBe('未被旧超时打断');
|
const next = requestPttTransText('account:timeout', 1_000, async () => '');
|
||||||
});
|
trigger.reject(new Error('late failure'));
|
||||||
});
|
await vi.advanceTimersByTimeAsync(0);
|
||||||
|
deliverPttTransText('account:timeout', 'next');
|
||||||
describe('waitPttTransText timeout', () => {
|
await expect(next).resolves.toBe('next');
|
||||||
it('rejects after timeoutMs when no result is delivered', async () => {
|
expect(vi.getTimerCount()).toBe(0);
|
||||||
vi.useFakeTimers();
|
});
|
||||||
const waiter = waitPttTransText('10001:40', 20_000);
|
|
||||||
const rejected = expect(waiter).rejects.toThrow('语音转文字超时(未收到结果推送)');
|
it('clears the timeout after a successful result', async () => {
|
||||||
await vi.advanceTimersByTimeAsync(19_999);
|
vi.useFakeTimers();
|
||||||
await vi.advanceTimersByTimeAsync(1);
|
const result = requestPttTransText('account:done', 1_000, async () => 'done');
|
||||||
await rejected;
|
await expect(result).resolves.toBe('done');
|
||||||
});
|
expect(vi.getTimerCount()).toBe(0);
|
||||||
|
expect(() => deliverPttTransText('account:done', 'late')).not.toThrow();
|
||||||
it('does not reject after deliver even if the original timeout later elapses', async () => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
const waiter = waitPttTransText('10001:41', 20_000);
|
|
||||||
deliverPttTransText('10001:41', '同步转写');
|
|
||||||
await expect(waiter).resolves.toBe('同步转写');
|
|
||||||
await vi.advanceTimersByTimeAsync(20_000);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not reject again after fail even if the original timeout later elapses', async () => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
const waiter = waitPttTransText('10001:42', 20_000);
|
|
||||||
failPttTransWaiter('10001:42', new Error('请求失败'));
|
|
||||||
await expect(waiter).rejects.toThrow('请求失败');
|
|
||||||
await vi.advanceTimersByTimeAsync(20_000);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ignores deliver and fail after the timeout has already settled the waiter', async () => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
const waiter = waitPttTransText('10001:43', 20_000);
|
|
||||||
const rejected = expect(waiter).rejects.toThrow('语音转文字超时(未收到结果推送)');
|
|
||||||
await vi.advanceTimersByTimeAsync(20_000);
|
|
||||||
await rejected;
|
|
||||||
expect(() => deliverPttTransText('10001:43', '来晚了')).not.toThrow();
|
|
||||||
expect(() => failPttTransWaiter('10001:43', new Error('也来晚了'))).not.toThrow();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -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
|
existing clients when the dedicated header is absent. Both layers still require
|
||||||
their own valid credentials.
|
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 account detection
|
||||||
|
|
||||||
Process cards use QQ's local account data before injection and the hook's confirmed
|
Process cards use QQ's local account data before injection and the hook's confirmed
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ import {
|
|||||||
type TotpStatus,
|
type TotpStatus,
|
||||||
} from './types';
|
} from './types';
|
||||||
import { localStorageTokenStore } from './token-store';
|
import { localStorageTokenStore } from './token-store';
|
||||||
|
import { readSseJson } from './sse';
|
||||||
import { WEBUI_SESSION_HEADER, webuiSessionHeaders } from './session-headers';
|
import { WEBUI_SESSION_HEADER, webuiSessionHeaders } from './session-headers';
|
||||||
|
|
||||||
const DEFAULT_TOKEN_KEY = 'snowluma_token';
|
const DEFAULT_TOKEN_KEY = 'snowluma_token';
|
||||||
@@ -263,22 +264,13 @@ class HttpApiClient implements ApiClient {
|
|||||||
return data.appearance;
|
return data.appearance;
|
||||||
},
|
},
|
||||||
uploadBackground: async (file) => {
|
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();
|
const form = new FormData();
|
||||||
form.append('file', file);
|
form.append('file', file);
|
||||||
const res = await fetch('/api/ui/background', {
|
const res = await this.request('/api/ui/background', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: webuiSessionHeaders(this.currentToken),
|
|
||||||
body: form,
|
body: form,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.status === 401) {
|
|
||||||
this.setToken(null);
|
|
||||||
this.onUnauthorized?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const payload = await readJson<ErrorPayload>(res);
|
const payload = await readJson<ErrorPayload>(res);
|
||||||
throw new ApiError(
|
throw new ApiError(
|
||||||
@@ -480,7 +472,8 @@ class HttpApiClient implements ApiClient {
|
|||||||
// ---------- HTTP helpers ----------
|
// ---------- HTTP helpers ----------
|
||||||
|
|
||||||
async request(url: string, init: RequestInit = {}): Promise<Response> {
|
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')) {
|
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) {
|
||||||
headers.set('Content-Type', 'application/json');
|
headers.set('Content-Type', 'application/json');
|
||||||
@@ -489,8 +482,7 @@ class HttpApiClient implements ApiClient {
|
|||||||
const res = await this.fetchWithDeadline(url, { ...init, headers });
|
const res = await this.fetchWithDeadline(url, { ...init, headers });
|
||||||
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
this.setToken(null);
|
this.expireSession(token);
|
||||||
this.onUnauthorized?.();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return res;
|
||||||
@@ -552,6 +544,15 @@ class HttpApiClient implements ApiClient {
|
|||||||
|
|
||||||
// ---------- token management ----------
|
// ---------- 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 {
|
private setToken(token: string | null): void {
|
||||||
const changed = this.currentToken !== token;
|
const changed = this.currentToken !== token;
|
||||||
this.currentToken = token;
|
this.currentToken = token;
|
||||||
@@ -700,7 +701,7 @@ class HttpApiClient implements ApiClient {
|
|||||||
|
|
||||||
// ---------- SSE ----------
|
// ---------- 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>(
|
private openSseChannel<T>(
|
||||||
path: string,
|
path: string,
|
||||||
onMessage: (data: T) => void,
|
onMessage: (data: T) => void,
|
||||||
@@ -713,24 +714,45 @@ class HttpApiClient implements ApiClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
|
let suspended = false;
|
||||||
let active: AbortController | null = null;
|
let active: AbortController | null = null;
|
||||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const page = typeof window !== 'undefined' && typeof document !== 'undefined';
|
||||||
|
|
||||||
const clearReconnect = () => {
|
const cancelReconnect = () => {
|
||||||
if (reconnectTimer !== null) {
|
if (reconnectTimer !== null) {
|
||||||
clearTimeout(reconnectTimer);
|
clearTimeout(reconnectTimer);
|
||||||
reconnectTimer = null;
|
reconnectTimer = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const disconnect = () => {
|
const stopRequest = () => {
|
||||||
clearReconnect();
|
const request = active;
|
||||||
active?.abort();
|
|
||||||
active = null;
|
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 = () => {
|
const scheduleReconnect = () => {
|
||||||
if (disposed || reconnectTimer !== null) {
|
if (disposed || suspended || reconnectTimer !== null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -742,7 +764,7 @@ class HttpApiClient implements ApiClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const connect = async () => {
|
const connect = async () => {
|
||||||
if (disposed || active) {
|
if (disposed || suspended || active) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -755,8 +777,6 @@ class HttpApiClient implements ApiClient {
|
|||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
active = controller;
|
active = controller;
|
||||||
const isCurrent = () =>
|
|
||||||
!disposed && active === controller && !controller.signal.aborted;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(path, {
|
const response = await fetch(path, {
|
||||||
@@ -768,15 +788,14 @@ class HttpApiClient implements ApiClient {
|
|||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!isCurrent()) {
|
if (active !== controller || token !== this.currentToken) {
|
||||||
await response.body?.cancel();
|
await response.body?.cancel();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.status === 401) {
|
if (response.status === 401) {
|
||||||
dispose();
|
dispose();
|
||||||
this.setToken(null);
|
this.expireSession(token);
|
||||||
this.onUnauthorized?.();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -785,108 +804,54 @@ class HttpApiClient implements ApiClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onStatus?.('open');
|
onStatus?.('open');
|
||||||
const reader = response.body.getReader();
|
|
||||||
const decoder = new TextDecoder();
|
|
||||||
let buffer = '';
|
|
||||||
|
|
||||||
try {
|
for await (const frame of readSseJson<T>(response.body, controller.signal)) {
|
||||||
while (isCurrent()) {
|
if (active !== controller || token !== this.currentToken) {
|
||||||
const { done, value } = await reader.read();
|
break;
|
||||||
|
|
||||||
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 */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
try {
|
try {
|
||||||
await reader.cancel();
|
onMessage(frame);
|
||||||
} catch {
|
} catch (error) {
|
||||||
/* already closed */
|
console.error('实时消息处理失败', error);
|
||||||
}
|
}
|
||||||
|
|
||||||
reader.releaseLock();
|
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
if (isCurrent()) {
|
if (!controller.signal.aborted) {
|
||||||
scheduleReconnect();
|
console.warn('实时连接中断', error);
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
if (isCurrent()) {
|
|
||||||
scheduleReconnect();
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (active === controller) {
|
if (active === controller) {
|
||||||
active = null;
|
active = null;
|
||||||
|
scheduleReconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onPageHide = disconnect;
|
const onPageHide = () => {
|
||||||
|
suspended = true;
|
||||||
|
cancelReconnect();
|
||||||
|
stopRequest();
|
||||||
|
};
|
||||||
|
|
||||||
|
const resume = () => {
|
||||||
|
suspended = false;
|
||||||
|
cancelReconnect();
|
||||||
|
void connect();
|
||||||
|
};
|
||||||
|
|
||||||
const onPageShow = (event: PageTransitionEvent) => {
|
const onPageShow = (event: PageTransitionEvent) => {
|
||||||
if (event.persisted && !disposed) {
|
if (event.persisted) {
|
||||||
clearReconnect();
|
resume();
|
||||||
void connect();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onVisible = () => {
|
const onVisible = () => {
|
||||||
if (document.visibilityState === 'visible' && !disposed && !active) {
|
if (document.visibilityState === 'visible') {
|
||||||
clearReconnect();
|
resume();
|
||||||
void connect();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const page = typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
||||||
|
|
||||||
if (page) {
|
if (page) {
|
||||||
window.addEventListener('pagehide', onPageHide);
|
window.addEventListener('pagehide', onPageHide);
|
||||||
window.addEventListener('pageshow', onPageShow);
|
window.addEventListener('pageshow', onPageShow);
|
||||||
@@ -894,41 +859,22 @@ class HttpApiClient implements ApiClient {
|
|||||||
document.addEventListener('freeze', onPageHide);
|
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();
|
void connect();
|
||||||
return dispose;
|
return dispose;
|
||||||
}
|
}
|
||||||
|
|
||||||
private openLogStream(options: LogsStreamOptions): () => void {
|
private openLogStream(options: LogsStreamOptions): () => void {
|
||||||
this.logSubscribers.add(options);
|
const subscription = { ...options };
|
||||||
|
this.logSubscribers.add(subscription);
|
||||||
|
|
||||||
if (this.logStreamDispose) {
|
if (this.logStreamDispose) {
|
||||||
// A late subscriber joins the already-live shared connection — replay the
|
subscription.onStatus?.(this.lastLogStatus);
|
||||||
// current transport status so its badge isn't stuck at the default.
|
|
||||||
options.onStatus?.(this.lastLogStatus);
|
|
||||||
} else {
|
} else {
|
||||||
this.openSharedLogStream();
|
this.openSharedLogStream();
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
this.logSubscribers.delete(options);
|
this.logSubscribers.delete(subscription);
|
||||||
|
|
||||||
if (this.logSubscribers.size === 0 && this.logStreamDispose) {
|
if (this.logSubscribers.size === 0 && this.logStreamDispose) {
|
||||||
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 {
|
private openSharedLogStream(): void {
|
||||||
if (!this.currentToken) {
|
if (!this.currentToken) {
|
||||||
this.lastLogStatus = 'closed';
|
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 {
|
private reopenSharedLogStream(): void {
|
||||||
if (this.logStreamDispose) {
|
if (this.logStreamDispose) {
|
||||||
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(
|
private async openDebugInvokeStream(
|
||||||
uin: string,
|
uin: string,
|
||||||
action: string,
|
action: string,
|
||||||
@@ -1014,7 +957,8 @@ class HttpApiClient implements ApiClient {
|
|||||||
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
|
onFrame: (frame: import('@/types').DebugStreamFrame) => void,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const headers = webuiSessionHeaders(this.currentToken, {
|
const token = this.currentToken;
|
||||||
|
const headers = webuiSessionHeaders(token, {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Accept: 'text/event-stream',
|
Accept: 'text/event-stream',
|
||||||
'Cache-Control': 'no-cache',
|
'Cache-Control': 'no-cache',
|
||||||
@@ -1029,8 +973,7 @@ class HttpApiClient implements ApiClient {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
this.setToken(null);
|
this.expireSession(token);
|
||||||
this.onUnauthorized?.();
|
|
||||||
throw new ApiError(401, '未授权');
|
throw new ApiError(401, '未授权');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1043,137 +986,79 @@ class HttpApiClient implements ApiClient {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const reader = res.body.getReader();
|
for await (const frame of readSseJson<import('@/types').DebugStreamFrame>(
|
||||||
const decoder = new TextDecoder();
|
res.body,
|
||||||
let buf = '';
|
signal,
|
||||||
|
)) {
|
||||||
const takeFrames = (raw: string) => {
|
onFrame(frame);
|
||||||
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 */
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Upload a browser file to a server temp path. Uses XHR (not fetch) so the
|
/** XHR exposes upload progress; every settlement releases its abort listener. */
|
||||||
// upload progress callback can fire — fetch can't observe request-body
|
private async uploadDebugFile(
|
||||||
// progress. Returns the parsed { path, size }.
|
|
||||||
private uploadDebugFile(
|
|
||||||
file: File,
|
file: File,
|
||||||
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
|
opts?: { filename?: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
|
||||||
): Promise<import('@/types').DebugUploadResult> {
|
): Promise<import('@/types').DebugUploadResult> {
|
||||||
return new Promise((resolve, reject) => {
|
const signal = opts?.signal;
|
||||||
const name = opts?.filename ?? file.name;
|
|
||||||
const xhr = new XMLHttpRequest();
|
|
||||||
xhr.open('POST', `/api/debug/upload?filename=${encodeURIComponent(name)}`);
|
|
||||||
|
|
||||||
if (this.currentToken) {
|
if (signal?.aborted) {
|
||||||
xhr.setRequestHeader(WEBUI_SESSION_HEADER, this.currentToken);
|
throw new ApiError(0, '上传已取消');
|
||||||
}
|
}
|
||||||
|
|
||||||
xhr.responseType = 'json';
|
const token = this.currentToken;
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
const onAbort = () => xhr.abort();
|
||||||
|
|
||||||
xhr.upload.onprogress = (e) => {
|
try {
|
||||||
if (e.lengthComputable) {
|
return await new Promise<import('@/types').DebugUploadResult>((resolve, reject) => {
|
||||||
opts?.onProgress?.(e.loaded / e.total);
|
const name = opts?.filename ?? file.name;
|
||||||
}
|
xhr.open('POST', '/api/debug/upload?filename=' + encodeURIComponent(name));
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onload = () => {
|
if (token) {
|
||||||
if (xhr.status === 401) {
|
xhr.setRequestHeader(WEBUI_SESSION_HEADER, token);
|
||||||
this.setToken(null);
|
|
||||||
this.onUnauthorized?.();
|
|
||||||
reject(new ApiError(401, '未授权'));
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = (xhr.response ?? {}) as import('@/types').DebugUploadResult;
|
xhr.responseType = 'json';
|
||||||
|
|
||||||
if (xhr.status >= 200 && xhr.status < 300 && body.path) {
|
xhr.upload.onprogress = (event) => {
|
||||||
resolve(body);
|
if (event.lengthComputable) {
|
||||||
} else {
|
opts?.onProgress?.(event.loaded / event.total);
|
||||||
reject(new ApiError(xhr.status, body.message || '上传失败'));
|
}
|
||||||
}
|
};
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onerror = () => reject(new ApiError(0, '上传网络错误'));
|
xhr.onload = () => {
|
||||||
xhr.onabort = () => reject(new ApiError(0, '上传已取消'));
|
if (xhr.status === 401) {
|
||||||
|
this.expireSession(token);
|
||||||
|
reject(new ApiError(401, '未授权'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (opts?.signal) {
|
const body = xhr.response as import('@/types').DebugUploadResult | null;
|
||||||
if (opts.signal.aborted) {
|
|
||||||
xhr.abort();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
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(
|
private openDebugStream(
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -322,6 +322,6 @@ export interface TokenStore {
|
|||||||
export interface CreateApiClientOptions {
|
export interface CreateApiClientOptions {
|
||||||
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
|
/** Persists the bearer token across reloads. Defaults to localStorage('snowluma_token'). */
|
||||||
tokenStore?: TokenStore;
|
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;
|
onUnauthorized?: () => void;
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,29 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('WebUI authentication behind a Basic-auth proxy', () => {
|
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([
|
it.each([
|
||||||
{ kind: 'object', headers: { Authorization: proxyAuthorization } },
|
{ kind: 'object', headers: { Authorization: proxyAuthorization } },
|
||||||
{ kind: 'Headers', headers: new Headers({ Authorization: proxyAuthorization }) },
|
{ kind: 'Headers', headers: new Headers({ Authorization: proxyAuthorization }) },
|
||||||
|
|||||||
@@ -10,6 +10,75 @@ describe('API client SSE lifecycle', () => {
|
|||||||
vi.unstubAllGlobals();
|
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 () => {
|
it('keeps Authorization available for the proxy while authenticating and parsing frames', async () => {
|
||||||
let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
|
let streamController: ReadableStreamDefaultController<Uint8Array> | undefined;
|
||||||
const stream = new ReadableStream<Uint8Array>({
|
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