feat(sdk): support streaming file transfers
This commit is contained in:
17 files changed
+1960
-14
No files matched your search
@@ -0,0 +1,288 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
SnowLumaAbortError,
|
||||
SnowLumaApiError,
|
||||
SnowLumaHttpClient,
|
||||
SnowLumaParseError,
|
||||
} from '../src/index.js';
|
||||
import type { JsonObject } from '../src/index.js';
|
||||
|
||||
const wrap = (data: unknown) => ({ status: 'ok', retcode: 0, stream: 'stream-action', data });
|
||||
const wire = (data: unknown) => JSON.stringify(wrap(data)) + '\r\n\r\n';
|
||||
const info = {
|
||||
type: 'stream',
|
||||
data_type: 'file_info',
|
||||
file_name: 'test',
|
||||
file_size: 2,
|
||||
chunk_size: 2,
|
||||
};
|
||||
const chunk = {
|
||||
type: 'stream',
|
||||
data_type: 'file_chunk',
|
||||
index: 0,
|
||||
data: 'YWI=',
|
||||
size: 2,
|
||||
base64_size: 4,
|
||||
progress: 100,
|
||||
};
|
||||
const complete = {
|
||||
type: 'response',
|
||||
data_type: 'file_complete',
|
||||
file_name: 'test',
|
||||
total_chunks: 1,
|
||||
total_bytes: 2,
|
||||
message: 'done',
|
||||
};
|
||||
|
||||
async function download(frames: unknown[], onInfo?: (value: unknown) => void) {
|
||||
const client = new SnowLumaHttpClient({
|
||||
fetch: async () => new Response(frames.map(wire).join('')),
|
||||
});
|
||||
const stream = client.downloadFileStream({ file: 'test' }, { onInfo });
|
||||
const chunks: Uint8Array[] = [];
|
||||
|
||||
while (true) {
|
||||
const result = await stream.next();
|
||||
|
||||
if (result.done) {
|
||||
return { chunks, complete: result.value };
|
||||
}
|
||||
|
||||
chunks.push(result.value);
|
||||
}
|
||||
}
|
||||
|
||||
describe('file download helper', () => {
|
||||
it('yields bytes, exposes metadata and returns verified completion', async () => {
|
||||
const onInfo = vi.fn();
|
||||
expect(await download([info, chunk, complete], onInfo)).toEqual({
|
||||
chunks: [new Uint8Array([97, 98])],
|
||||
complete,
|
||||
});
|
||||
expect(onInfo).toHaveBeenCalledExactlyOnceWith(info);
|
||||
});
|
||||
|
||||
it('accepts an unknown initial size and verifies the final totals', async () => {
|
||||
expect(
|
||||
(await download([{ ...info, file_size: 0 }, chunk, complete])).complete.total_bytes,
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it('supports empty files', async () => {
|
||||
expect(
|
||||
(
|
||||
await download([
|
||||
{ ...info, file_size: 0 },
|
||||
{ ...complete, total_chunks: 0, total_bytes: 0 },
|
||||
])
|
||||
).chunks,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['missing info', [chunk, complete]],
|
||||
['duplicate info', [info, info, chunk, complete]],
|
||||
['missing chunk', [info, complete]],
|
||||
['out-of-order index', [info, { ...chunk, index: 1 }, complete]],
|
||||
['invalid base64', [info, { ...chunk, data: '????' }, complete]],
|
||||
['non-canonical base64', [info, { ...chunk, data: 'YWL=' }, complete]],
|
||||
['wrong chunk size', [info, { ...chunk, size: 3 }, complete]],
|
||||
['wrong base64 size', [info, { ...chunk, base64_size: 5 }, complete]],
|
||||
['wrong final size', [info, chunk, { ...complete, total_bytes: 3 }]],
|
||||
['wrong final count', [info, chunk, { ...complete, total_chunks: 2 }]],
|
||||
['wrong info size', [{ ...info, file_size: 3 }, chunk, complete]],
|
||||
['wrong final name', [info, chunk, { ...complete, file_name: 'other' }]],
|
||||
['unexpected frame', [info, { type: 'stream', data_type: 'other' }, complete]],
|
||||
])('rejects %s', async (_name, frames) => {
|
||||
await expect(download(frames as unknown[])).rejects.toBeInstanceOf(SnowLumaParseError);
|
||||
});
|
||||
});
|
||||
|
||||
function uploader(transform?: (data: JsonObject, params: JsonObject) => JsonObject) {
|
||||
const calls: JsonObject[] = [];
|
||||
const fetch = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
|
||||
const { params } = JSON.parse(String(init?.body)) as { params: JsonObject };
|
||||
calls.push(params);
|
||||
const first = calls[0];
|
||||
const result: JsonObject = params.is_complete
|
||||
? {
|
||||
type: 'response',
|
||||
status: 'file_complete',
|
||||
stream_id: first.stream_id,
|
||||
received_chunks: first.total_chunks,
|
||||
total_chunks: first.total_chunks,
|
||||
file_size: first.file_size,
|
||||
file_path: '/remote/file',
|
||||
file_name: 'test',
|
||||
sha256: 'a'.repeat(64),
|
||||
}
|
||||
: {
|
||||
type: 'stream',
|
||||
status: 'chunk_received',
|
||||
stream_id: params.stream_id,
|
||||
received_chunks: Number(params.chunk_index) + 1,
|
||||
total_chunks: params.total_chunks,
|
||||
};
|
||||
return new Response(wire(transform ? transform(result, params) : result));
|
||||
});
|
||||
return { client: new SnowLumaHttpClient({ fetch }), calls, fetch };
|
||||
}
|
||||
|
||||
describe('file upload helper', () => {
|
||||
it('cancels a stalled readable source before any request is sent', async () => {
|
||||
const { client, fetch } = uploader();
|
||||
const cancel = vi.fn();
|
||||
const source = new ReadableStream<Uint8Array>({ cancel });
|
||||
const controller = new AbortController();
|
||||
const upload = client.uploadFileStream(source, { fileSize: 1, signal: controller.signal });
|
||||
await vi.waitFor(() => expect(source.locked).toBe(true));
|
||||
controller.abort();
|
||||
await expect(upload).rejects.toBeInstanceOf(SnowLumaAbortError);
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(source.locked).toBe(false);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not send later chunks or finalize after cancellation from a progress callback', async () => {
|
||||
const { client, calls } = uploader();
|
||||
const controller = new AbortController();
|
||||
await expect(
|
||||
client.uploadFileStream(new Uint8Array([1, 2]), {
|
||||
chunkSize: 1,
|
||||
signal: controller.signal,
|
||||
onProgress: () => controller.abort(),
|
||||
}),
|
||||
).rejects.toBeInstanceOf(SnowLumaAbortError);
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('re-chunks async input, awaits progress and separately finalizes after all ACKs', async () => {
|
||||
const { client, calls } = uploader();
|
||||
const progress = vi.fn();
|
||||
let readSecond = false;
|
||||
const source = (async function* () {
|
||||
yield new Uint8Array([1, 2, 3, 4]);
|
||||
expect(progress).toHaveBeenCalledTimes(2);
|
||||
readSecond = true;
|
||||
yield new Uint8Array([5]);
|
||||
})();
|
||||
const result = await client.uploadFileStream(source, {
|
||||
fileSize: 5,
|
||||
chunkSize: 2,
|
||||
filename: 'input',
|
||||
streamId: 'test',
|
||||
onProgress: progress,
|
||||
});
|
||||
expect(readSecond).toBe(true);
|
||||
expect(calls.map((params) => params.chunk_data)).toEqual([
|
||||
'AQI=',
|
||||
'AwQ=',
|
||||
'BQ==',
|
||||
undefined,
|
||||
]);
|
||||
expect(calls[0]).toMatchObject({ total_chunks: 3, file_size: 5, filename: 'input' });
|
||||
expect(calls[3]).toEqual({ stream_id: 'test', is_complete: true });
|
||||
expect(progress).toHaveBeenLastCalledWith({
|
||||
streamId: 'test',
|
||||
uploadedChunks: 3,
|
||||
totalChunks: 3,
|
||||
uploadedBytes: 5,
|
||||
fileSize: 5,
|
||||
});
|
||||
expect(result.file_path).toBe('/remote/file');
|
||||
});
|
||||
|
||||
it.each([new Uint8Array(), new Blob([]), new Blob(['ab'])])(
|
||||
'infers size for byte and Blob sources: %s',
|
||||
async (source) => {
|
||||
const { client, calls } = uploader();
|
||||
const result = await client.uploadFileStream(source);
|
||||
expect(result.file_size).toBe(source instanceof Blob ? source.size : source.length);
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0].total_chunks).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([0, 4])(
|
||||
'does not finalize a streaming source with mismatched size %i',
|
||||
async (fileSize) => {
|
||||
const { client, calls } = uploader();
|
||||
let closed = false;
|
||||
const source = (async function* () {
|
||||
try {
|
||||
yield new Uint8Array([1, 2]);
|
||||
} finally {
|
||||
closed = true;
|
||||
}
|
||||
})();
|
||||
await expect(
|
||||
client.uploadFileStream(source, { fileSize, chunkSize: 1 }),
|
||||
).rejects.toThrow('fileSize');
|
||||
expect(closed).toBe(true);
|
||||
expect(calls.some((call) => call.is_complete)).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('requires a declared size and validates options before making requests', async () => {
|
||||
const { client, fetch } = uploader();
|
||||
const source = (async function* () {
|
||||
yield new Uint8Array([1]);
|
||||
})();
|
||||
await expect(client.uploadFileStream(source)).rejects.toThrow('fileSize');
|
||||
await expect(client.uploadFileStream(new Uint8Array([1]), { fileSize: 2 })).rejects.toThrow(
|
||||
'fileSize',
|
||||
);
|
||||
await expect(
|
||||
client.uploadFileStream(new Uint8Array([1]), { chunkSize: 0 }),
|
||||
).rejects.toThrow('chunkSize');
|
||||
await expect(
|
||||
client.uploadFileStream(new Uint8Array([1]), { streamId: '../bad' }),
|
||||
).rejects.toThrow('streamId');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects incorrect ACKs and cancels a readable source on failure', async () => {
|
||||
const { client, calls } = uploader((data) => ({ ...data, received_chunks: 99 }));
|
||||
const cancel = vi.fn();
|
||||
const source = new ReadableStream<Uint8Array>({
|
||||
start(c) {
|
||||
c.enqueue(new Uint8Array([1, 2]));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
await expect(client.uploadFileStream(source, { fileSize: 2 })).rejects.toBeInstanceOf(
|
||||
SnowLumaParseError,
|
||||
);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(source.locked).toBe(false);
|
||||
});
|
||||
|
||||
it('stops after a failed chunk and preserves the server error', async () => {
|
||||
const fetch = vi.fn(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
status: 'failed',
|
||||
retcode: 1500,
|
||||
data: { type: 'error' },
|
||||
wording: 'disk full',
|
||||
}),
|
||||
),
|
||||
);
|
||||
const client = new SnowLumaHttpClient({ fetch });
|
||||
await expect(
|
||||
client.uploadFileStream(new Uint8Array(10), { chunkSize: 2 }),
|
||||
).rejects.toBeInstanceOf(SnowLumaApiError);
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('rejects inconsistent final metadata', async () => {
|
||||
const { client } = uploader((data, params) =>
|
||||
params.is_complete ? { ...data, file_size: 99 } : data,
|
||||
);
|
||||
await expect(client.uploadFileStream(new Uint8Array([1]))).rejects.toThrow(
|
||||
'completion metadata',
|
||||
);
|
||||
});
|
||||
});
|
||||
+26
@@ -1,12 +1,15 @@
|
||||
import type {
|
||||
ActionParams,
|
||||
ActionResult,
|
||||
DownloadFileStreamComplete,
|
||||
JsonObject,
|
||||
JsonValue,
|
||||
SnowLumaActionMap,
|
||||
SnowLumaHttpClient,
|
||||
SnowLumaKnownAction,
|
||||
SnowLumaWebSocketClient,
|
||||
StreamApiResponse,
|
||||
UploadFileStreamComplete,
|
||||
} from '@snowluma/sdk';
|
||||
import { actionParams, actionResults, type CoveredAction } from './action-contracts.js';
|
||||
|
||||
@@ -40,6 +43,29 @@ export type QuickAlias = AssertTrue<
|
||||
declare const http: SnowLumaHttpClient;
|
||||
declare const ws: SnowLumaWebSocketClient;
|
||||
|
||||
export const uploadedFile: Promise<UploadFileStreamComplete> = http.uploadFileStream(
|
||||
new Blob(['file']),
|
||||
);
|
||||
export const download: AsyncGenerator<Uint8Array, DownloadFileStreamComplete, void> =
|
||||
ws.downloadFileStream({ file_id: 'media' }, { action: 'download_file_image_stream' });
|
||||
export const rawFrames: AsyncIterableIterator<
|
||||
StreamApiResponse<ActionResult<'test_download_stream'>>
|
||||
> = http.requestStream('test_download_stream', {});
|
||||
|
||||
for await (const item of ws.stream('download_file_stream', { file: '/remote/file' })) {
|
||||
if (item.type === 'stream' && item.data_type === 'file_chunk') {
|
||||
const encoded: string = item.data;
|
||||
void encoded;
|
||||
}
|
||||
}
|
||||
|
||||
// @ts-expect-error single-response actions use request()/call()
|
||||
http.stream('get_status', {});
|
||||
// @ts-expect-error uploads accept bytes rather than text chunks
|
||||
http.uploadFileStream('text');
|
||||
// @ts-expect-error downloads require a file or file ID
|
||||
ws.downloadFileStream({});
|
||||
|
||||
const feeds = await http.raw('get_qzone_feeds', { page_num: '2', count: 10 });
|
||||
const more: boolean = feeds.has_more;
|
||||
const author: number = feeds.feeds[0].uin;
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
SnowLumaAbortError,
|
||||
SnowLumaApiError,
|
||||
SnowLumaAuthError,
|
||||
SnowLumaHttpClient,
|
||||
SnowLumaParseError,
|
||||
SnowLumaTimeoutError,
|
||||
} from '../src/index.js';
|
||||
|
||||
const data = { type: 'stream', data_type: 'data_chunk', data: '中文🙂' };
|
||||
const complete = { type: 'response', data_type: 'data_complete', data: 'done' };
|
||||
const frame = (payload: unknown) => ({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
stream: 'stream-action',
|
||||
data: payload,
|
||||
echo: 'stream',
|
||||
});
|
||||
const wire = (payload: unknown) => JSON.stringify(payload) + '\r\n\r\n';
|
||||
|
||||
async function collect<T>(stream: AsyncIterable<T>): Promise<T[]> {
|
||||
const results: T[] = [];
|
||||
|
||||
for await (const result of stream) {
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function clientFor(body: BodyInit | null) {
|
||||
return new SnowLumaHttpClient({ fetch: async () => new Response(body) });
|
||||
}
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe('HTTP streaming', () => {
|
||||
it('does not send an already-aborted request', async () => {
|
||||
const fetch = vi.fn();
|
||||
const client = new SnowLumaHttpClient({ fetch });
|
||||
await expect(
|
||||
client.stream('test_download_stream', {}, { signal: AbortSignal.abort() }).next(),
|
||||
).rejects.toBeInstanceOf(SnowLumaAbortError);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('honors cancellation between frames buffered in the same HTTP read', async () => {
|
||||
const controller = new AbortController();
|
||||
const client = clientFor(wire(frame(data)) + wire(frame(complete)));
|
||||
const stream = client.stream('test_download_stream', {}, { signal: controller.signal });
|
||||
await stream.next();
|
||||
controller.abort();
|
||||
await expect(stream.next()).rejects.toBeInstanceOf(SnowLumaAbortError);
|
||||
});
|
||||
|
||||
it.each(['one byte', 'one read'] as const)(
|
||||
'decodes split UTF-8 and delimiters: %s',
|
||||
async (mode) => {
|
||||
const bytes = new TextEncoder().encode(
|
||||
wire(frame(data)) + wire(frame(data)) + wire(frame(complete)),
|
||||
);
|
||||
let offset = 0;
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
if (offset === bytes.length) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const end = mode === 'one byte' ? offset + 1 : bytes.length;
|
||||
controller.enqueue(bytes.subarray(offset, end));
|
||||
offset = end;
|
||||
},
|
||||
});
|
||||
const fetch = vi.fn(async () => new Response(body));
|
||||
const client = new SnowLumaHttpClient({ fetch, accessToken: 'test-token' });
|
||||
const results = await collect(
|
||||
client.requestStream('test_download_stream', {}, { echo: 'stream' }),
|
||||
);
|
||||
expect(results.map((result) => result.data)).toEqual([data, data, complete]);
|
||||
expect(
|
||||
results.every(
|
||||
(result) => result.stream === 'stream-action' && result.echo === 'stream',
|
||||
),
|
||||
).toBe(true);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ Authorization: 'Bearer test-token' }),
|
||||
body: JSON.stringify({
|
||||
action: 'test_download_stream',
|
||||
params: {},
|
||||
echo: 'stream',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(body.locked).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it('delivers a frame before EOF and cancels the reader when iteration stops', async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(wire(frame(data))));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const stream = clientFor(body).stream('test_download_stream', {});
|
||||
expect(await stream.next()).toMatchObject({ value: data, done: false });
|
||||
await stream.return();
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(body.locked).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['', 'terminal'],
|
||||
[wire(frame(data)), 'terminal'],
|
||||
[wire({ status: 'ok', retcode: 0, data }), 'marker'],
|
||||
[wire({ status: 'ok', data }), 'envelope'],
|
||||
[wire(frame({ type: 'error' })), 'frame'],
|
||||
['{bad json}\r\n\r\n', 'JSON'],
|
||||
])('rejects incomplete or invalid responses: %s', async (body, message) => {
|
||||
await expect(collect(clientFor(body).stream('test_download_stream', {}))).rejects.toThrow(
|
||||
message,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects malformed UTF-8', async () => {
|
||||
await expect(
|
||||
collect(clientFor(new Uint8Array([0xff])).stream('test_download_stream', {})),
|
||||
).rejects.toBeInstanceOf(SnowLumaParseError);
|
||||
});
|
||||
|
||||
it('bounds individual frames while allowing multiple frames in one large read', async () => {
|
||||
const text = wire(frame(data)).repeat(10) + wire(frame(complete));
|
||||
await expect(
|
||||
collect(clientFor(text).stream('test_download_stream', {}, { maxBufferBytes: 200 })),
|
||||
).resolves.toHaveLength(11);
|
||||
await expect(
|
||||
collect(clientFor(text).stream('test_download_stream', {}, { maxBufferBytes: 10 })),
|
||||
).rejects.toThrow('maxBufferBytes');
|
||||
await expect(
|
||||
collect(
|
||||
clientFor('x'.repeat(500)).stream(
|
||||
'test_download_stream',
|
||||
{},
|
||||
{ maxBufferBytes: 10 },
|
||||
),
|
||||
),
|
||||
).rejects.toThrow('maxBufferBytes');
|
||||
});
|
||||
|
||||
it('returns raw failures and throws typed API errors from stream()', async () => {
|
||||
const failure = { status: 'failed', retcode: 1401, data: null, wording: 'denied' };
|
||||
expect(
|
||||
await collect(
|
||||
clientFor(JSON.stringify(failure)).requestStream('test_download_stream', {}),
|
||||
),
|
||||
).toMatchObject([failure]);
|
||||
await expect(
|
||||
collect(clientFor(JSON.stringify(failure)).stream('test_download_stream', {})),
|
||||
).rejects.toBeInstanceOf(SnowLumaAuthError);
|
||||
const stream = clientFor(wire(frame(data)) + wire({ ...failure, retcode: 1500 })).stream(
|
||||
'test_download_stream',
|
||||
{},
|
||||
);
|
||||
expect((await stream.next()).value).toEqual(data);
|
||||
await expect(stream.next()).rejects.toBeInstanceOf(SnowLumaApiError);
|
||||
});
|
||||
|
||||
it.each(['abort', 'timeout'] as const)('releases a pending body read on %s', async (reason) => {
|
||||
vi.useFakeTimers();
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({ cancel });
|
||||
const controller = new AbortController();
|
||||
const remove = vi.spyOn(controller.signal, 'removeEventListener');
|
||||
const stream = clientFor(body).stream(
|
||||
'test_download_stream',
|
||||
{},
|
||||
{ signal: controller.signal, timeoutMs: 100 },
|
||||
);
|
||||
const next = expect(stream.next()).rejects.toBeInstanceOf(
|
||||
reason === 'abort' ? SnowLumaAbortError : SnowLumaTimeoutError,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
if (reason === 'abort') {
|
||||
controller.abort();
|
||||
} else {
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
}
|
||||
|
||||
await next;
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(remove).toHaveBeenCalled();
|
||||
expect(body.locked).toBe(false);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('ends an upload ACK without waiting for a response-type frame or HTTP EOF', async () => {
|
||||
const ack = {
|
||||
type: 'stream',
|
||||
status: 'chunk_received',
|
||||
stream_id: 'id',
|
||||
received_chunks: 1,
|
||||
total_chunks: 2,
|
||||
};
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(wire(frame(ack))));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
expect(
|
||||
await collect(clientFor(body).stream('upload_file_stream', { stream_id: 'id' })),
|
||||
).toEqual([ack]);
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
SnowLumaAbortError,
|
||||
SnowLumaApiError,
|
||||
SnowLumaConnectionError,
|
||||
SnowLumaParseError,
|
||||
SnowLumaTimeoutError,
|
||||
SnowLumaWebSocketClient,
|
||||
type OneBotPrivateMessageEvent,
|
||||
} from '../src';
|
||||
@@ -74,6 +78,225 @@ const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
|
||||
sender: { user_id: 10001, nickname: 'tester' },
|
||||
};
|
||||
|
||||
describe('WebSocket streaming', () => {
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
async function connected() {
|
||||
const client = new SnowLumaWebSocketClient({
|
||||
webSocket: MockWebSocket,
|
||||
requestTimeoutMs: 1000,
|
||||
});
|
||||
const opening = client.connect();
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
socket.open();
|
||||
await opening;
|
||||
return { client, socket };
|
||||
}
|
||||
|
||||
const data = { type: 'stream', data_type: 'data_chunk', data: 'part' };
|
||||
const complete = { type: 'response', data_type: 'data_complete', data: 'done' };
|
||||
const frame = (echo: string, payload: unknown) =>
|
||||
JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
stream: 'stream-action',
|
||||
echo,
|
||||
data: payload,
|
||||
});
|
||||
|
||||
it('routes interleaved streams, normal responses and events independently', async () => {
|
||||
const { client, socket } = await connected();
|
||||
const event = vi.fn();
|
||||
client.onEvent(event);
|
||||
const first = client.stream('test_download_stream', {}, { echo: 'a' });
|
||||
const second = client.stream('test_download_stream', {}, { echo: 'b' });
|
||||
const a = first.next();
|
||||
const b = second.next();
|
||||
const status = client.getStatus({ echo: 'ordinary' });
|
||||
await vi.waitFor(() => expect(socket.sent).toHaveLength(3));
|
||||
socket.message(frame('b', data));
|
||||
socket.message(frame('a', data));
|
||||
socket.message(JSON.stringify(PRIVATE_EVENT));
|
||||
socket.message(
|
||||
JSON.stringify({ status: 'ok', retcode: 0, echo: 'ordinary', data: { online: true } }),
|
||||
);
|
||||
await expect(status).resolves.toEqual({ online: true });
|
||||
expect((await a).value).toEqual(data);
|
||||
expect((await b).value).toEqual(data);
|
||||
socket.message(frame('a', complete));
|
||||
socket.message(frame('b', complete));
|
||||
expect((await first.next()).value).toEqual(complete);
|
||||
expect((await second.next()).value).toEqual(complete);
|
||||
expect((await first.next()).done).toBe(true);
|
||||
expect((await second.next()).done).toBe(true);
|
||||
await vi.waitFor(() => expect(event).toHaveBeenCalledOnce());
|
||||
client.close();
|
||||
});
|
||||
|
||||
it('shares echo collision checks with single-response calls and preserves later requests', async () => {
|
||||
const { client, socket } = await connected();
|
||||
const stream = client.stream('test_download_stream', {}, { echo: 'same' });
|
||||
const first = stream.next();
|
||||
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
|
||||
await expect(client.getStatus({ echo: 'same' })).rejects.toThrow('already pending');
|
||||
await expect(
|
||||
client.stream('test_download_stream', {}, { echo: 'same' }).next(),
|
||||
).rejects.toThrow('already pending');
|
||||
socket.message(frame('same', data));
|
||||
await first;
|
||||
socket.message(frame('same', complete));
|
||||
const ordinary = client.getStatus({ echo: 'same' });
|
||||
await vi.waitFor(() => expect(socket.sent).toHaveLength(2));
|
||||
await stream.return();
|
||||
socket.message(
|
||||
JSON.stringify({ status: 'ok', retcode: 0, data: { online: true }, echo: 'same' }),
|
||||
);
|
||||
await expect(ordinary).resolves.toEqual({ online: true });
|
||||
client.close();
|
||||
});
|
||||
|
||||
it.each([
|
||||
'abort',
|
||||
'timeout',
|
||||
'close',
|
||||
'invalid frame',
|
||||
'invalid JSON',
|
||||
'send failure',
|
||||
'return',
|
||||
'complete',
|
||||
] as const)('releases stream timers and listeners after %s', async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const { client, socket } = await connected();
|
||||
const controller = new AbortController();
|
||||
const remove = vi.spyOn(controller.signal, 'removeEventListener');
|
||||
|
||||
if (outcome === 'send failure') {
|
||||
vi.spyOn(socket, 'send').mockImplementationOnce(() => {
|
||||
throw new Error('send');
|
||||
});
|
||||
}
|
||||
|
||||
const stream = client.stream(
|
||||
'test_download_stream',
|
||||
{},
|
||||
{ echo: 's', signal: controller.signal },
|
||||
);
|
||||
const next = stream.next();
|
||||
const settled = next.then(
|
||||
() => undefined,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
switch (outcome) {
|
||||
case 'abort':
|
||||
controller.abort();
|
||||
break;
|
||||
case 'timeout':
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
break;
|
||||
case 'close':
|
||||
socket.close();
|
||||
break;
|
||||
case 'invalid frame':
|
||||
socket.message(JSON.stringify({ echo: 's' }));
|
||||
break;
|
||||
case 'invalid JSON':
|
||||
socket.message('bad json');
|
||||
break;
|
||||
case 'return':
|
||||
socket.message(frame('s', data));
|
||||
await next;
|
||||
await stream.return();
|
||||
break;
|
||||
case 'complete':
|
||||
socket.message(frame('s', complete));
|
||||
await next;
|
||||
await stream.next();
|
||||
break;
|
||||
}
|
||||
|
||||
const error = await settled;
|
||||
const expected = {
|
||||
abort: SnowLumaAbortError,
|
||||
timeout: SnowLumaTimeoutError,
|
||||
close: SnowLumaConnectionError,
|
||||
'send failure': SnowLumaConnectionError,
|
||||
'invalid frame': SnowLumaParseError,
|
||||
'invalid JSON': SnowLumaParseError,
|
||||
};
|
||||
|
||||
if (outcome in expected) {
|
||||
expect(error).toBeInstanceOf(expected[outcome as keyof typeof expected]);
|
||||
} else {
|
||||
expect(error).toBeUndefined();
|
||||
}
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(remove).toHaveBeenCalled();
|
||||
client.close();
|
||||
});
|
||||
|
||||
it.each(['frames', 'bytes'] as const)(
|
||||
'fails a slow consumer when queued %s exceed its limit',
|
||||
async (limit) => {
|
||||
const { client, socket } = await connected();
|
||||
const stream = client.stream(
|
||||
'test_download_stream',
|
||||
{},
|
||||
{
|
||||
echo: 's',
|
||||
maxBufferedFrames: limit === 'frames' ? 1 : 256,
|
||||
maxBufferBytes: limit === 'bytes' ? 180 : 10000,
|
||||
},
|
||||
);
|
||||
const next = stream.next();
|
||||
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
|
||||
socket.message(frame('s', data));
|
||||
await next;
|
||||
socket.message(frame('s', data));
|
||||
socket.message(frame('s', data));
|
||||
await expect(stream.next()).rejects.toThrow('buffer limit');
|
||||
client.close();
|
||||
},
|
||||
);
|
||||
|
||||
it('throws a terminal API error after previously delivered frames', async () => {
|
||||
const { client, socket } = await connected();
|
||||
const stream = client.stream('test_download_stream', {}, { echo: 's' });
|
||||
const next = stream.next();
|
||||
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
|
||||
socket.message(frame('s', data));
|
||||
await next;
|
||||
socket.message(
|
||||
JSON.stringify({
|
||||
status: 'failed',
|
||||
retcode: 1500,
|
||||
echo: 's',
|
||||
data: { type: 'error' },
|
||||
wording: 'failed',
|
||||
}),
|
||||
);
|
||||
await expect(stream.next()).rejects.toBeInstanceOf(SnowLumaApiError);
|
||||
client.close();
|
||||
});
|
||||
|
||||
it('times out while opening without sending a request later', async () => {
|
||||
vi.useFakeTimers();
|
||||
const client = new SnowLumaWebSocketClient({ webSocket: MockWebSocket });
|
||||
const result = expect(
|
||||
client.stream('test_download_stream', {}, { timeoutMs: 20 }).next(),
|
||||
).rejects.toBeInstanceOf(SnowLumaTimeoutError);
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
await result;
|
||||
socket.open();
|
||||
expect(socket.sent).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
client.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SnowLumaWebSocketClient', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
|
||||
Reference in new issue
Block a user