feat(sdk): support streaming file transfers

This commit is contained in:
DrSmoothl committed 2026-10-23 13:43:35 +08:00
1 parent 166fcd8613
commit 9b5ce9b502
17 files changed
+1960 -14

No files matched your search

+44 -1
View File
@@ -1,10 +1,13 @@
import { createSnowLumaApiError } from '../errors.js';
import { createSnowLumaApiError, SnowLumaConnectionError } from '../errors.js';
import { normalizeMessage } from '../messages/index.js';
import { downloadFileStream, uploadFileStream } from './file-streams.js';
import type {
ActionParams,
ActionResult,
ApiResponse,
DomainParams,
DownloadFileStreamOptions,
DownloadFileStreamParams,
DownloadFileParams,
ForwardMessageParams,
GetForwardMsgParams,
@@ -19,6 +22,11 @@ import type {
SendMsgParams,
SetGroupReactionParams,
SnowLumaAction,
SnowLumaStreamAction,
StreamApiResponse,
StreamRequestOptions,
UploadFileSource,
UploadFileStreamOptions,
} from '../types/index.js';
/**
@@ -35,6 +43,41 @@ export abstract class SnowLumaApiClient {
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>>;
/** Returns every stream envelope, including a terminal failed response.
* Custom request-only subclasses remain valid and can opt into streaming. */
requestStream<TAction extends SnowLumaStreamAction>(
_action: TAction,
_params: ActionParams<TAction>,
_options?: StreamRequestOptions,
): AsyncIterableIterator<StreamApiResponse<ActionResult<TAction>>> {
throw new SnowLumaConnectionError('This client transport does not implement streaming');
}
/** Returns every stream payload; failed responses throw SnowLumaApiError. */
async *stream<TAction extends SnowLumaStreamAction>(
action: TAction,
params: ActionParams<TAction>,
options?: StreamRequestOptions,
): AsyncGenerator<ActionResult<TAction>, void, void> {
for await (const response of this.requestStream(action, params, options)) {
if (response.status !== 'ok' || response.retcode !== 0) {
throw createSnowLumaApiError(response);
}
yield response.data;
}
}
/** Uploads bytes incrementally and returns the server's completed file metadata. */
uploadFileStream(source: UploadFileSource, options?: UploadFileStreamOptions) {
return uploadFileStream(this, source, options);
}
/** Yields decoded byte chunks; the iterator's return value is completion metadata. */
downloadFileStream(params: DownloadFileStreamParams, options?: DownloadFileStreamOptions) {
return downloadFileStream(this, params, options);
}
/** Sends a OneBot action and returns data, throwing SnowLumaApiError on failed responses. */
async call<TAction extends SnowLumaAction>(
action: TAction,
+329
View File
@@ -0,0 +1,329 @@
import { SnowLumaParseError } from '../errors.js';
import { raceWithAbort, throwIfAborted } from '../internal/abort.js';
import { readBytes } from '../internal/streaming.js';
import type {
DownloadFileStreamComplete,
DownloadFileStreamInfo,
DownloadFileStreamOptions,
DownloadFileStreamParams,
UploadFileSource,
UploadFileStreamComplete,
UploadFileStreamOptions,
UploadFileStreamParams,
UploadFileStreamResult,
} from '../types/index.js';
import type { SnowLumaApiClient } from './api-client.js';
function encodeBase64(bytes: Uint8Array): string {
const parts: string[] = [];
for (let i = 0; i < bytes.length; i += 0x8000) {
parts.push(String.fromCharCode(...bytes.subarray(i, i + 0x8000)));
}
return btoa(parts.join(''));
}
function decodeBase64(value: string): Uint8Array {
try {
const binary = atob(value);
if (btoa(binary) !== value) {
throw new Error('non-canonical base64');
}
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
} catch (cause) {
throw new SnowLumaParseError('Invalid base64 in download chunk', { cause });
}
}
function isSize(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
}
async function* sourceBytes(
source: UploadFileSource,
signal?: AbortSignal,
): AsyncGenerator<Uint8Array> {
throwIfAborted(signal);
if (source instanceof Uint8Array) {
yield source;
return;
}
if (source instanceof Blob) {
yield* readBytes(source.stream(), signal);
return;
}
if ('getReader' in source) {
yield* readBytes(source, signal);
return;
}
const iterator = source[Symbol.asyncIterator]();
let ended = false;
try {
while (true) {
throwIfAborted(signal);
const next = await raceWithAbort(iterator.next(), signal);
if (next.done) {
ended = true;
return;
}
yield next.value;
}
} finally {
if (!ended) {
await iterator.return?.();
}
}
}
async function* uploadChunks(
source: UploadFileSource,
fileSize: number,
chunkSize: number,
signal?: AbortSignal,
): AsyncGenerator<Uint8Array> {
let buffer = new Uint8Array(Math.min(chunkSize, fileSize));
let used = 0;
let received = 0;
for await (const bytes of sourceBytes(source, signal)) {
if (!(bytes instanceof Uint8Array)) {
throw new TypeError('Upload source must yield Uint8Array chunks');
}
received += bytes.byteLength;
if (received > fileSize) {
throw new RangeError('Upload source is longer than fileSize');
}
for (let offset = 0; offset < bytes.length;) {
const count = Math.min(buffer.length - used, bytes.length - offset);
buffer.set(bytes.subarray(offset, offset + count), used);
used += count;
offset += count;
if (used === buffer.length) {
yield buffer;
buffer = new Uint8Array(chunkSize);
used = 0;
}
}
}
if (received !== fileSize) {
throw new RangeError('Upload source is shorter than fileSize');
}
if (used > 0 || fileSize === 0) {
yield buffer.subarray(0, used);
}
}
async function uploadResponse(
client: SnowLumaApiClient,
params: UploadFileStreamParams,
options: UploadFileStreamOptions,
): Promise<UploadFileStreamResult> {
let result: UploadFileStreamResult | undefined;
for await (const frame of client.stream('upload_file_stream', params, options)) {
if (result !== undefined) {
throw new SnowLumaParseError('Upload request returned multiple acknowledgements');
}
result = frame;
}
if (!result) {
throw new SnowLumaParseError('Upload request returned no acknowledgement');
}
return result;
}
export async function uploadFileStream(
client: SnowLumaApiClient,
source: UploadFileSource,
options: UploadFileStreamOptions = {},
): Promise<UploadFileStreamComplete> {
throwIfAborted(options.signal);
const knownSize =
source instanceof Uint8Array
? source.byteLength
: source instanceof Blob
? source.size
: undefined;
const fileSize = options.fileSize ?? knownSize;
const chunkSize = options.chunkSize ?? 64 * 1024;
const streamId = options.streamId ?? globalThis.crypto.randomUUID();
if (!isSize(fileSize)) {
throw new RangeError('fileSize must be a non-negative safe integer for streaming sources');
}
if (knownSize !== undefined && knownSize !== fileSize) {
throw new RangeError('fileSize does not match the upload source');
}
if (!Number.isSafeInteger(chunkSize) || chunkSize < 1 || chunkSize > 1024 * 1024) {
throw new RangeError('chunkSize must be an integer between 1 and 1048576');
}
if (!/^[A-Za-z0-9_-]{1,128}$/.test(streamId)) {
throw new TypeError('streamId must contain 1–128 letters, digits, underscores or hyphens');
}
const totalChunks = Math.max(1, Math.ceil(fileSize / chunkSize));
let uploadedChunks = 0;
let uploadedBytes = 0;
for await (const bytes of uploadChunks(source, fileSize, chunkSize, options.signal)) {
throwIfAborted(options.signal);
const response = await uploadResponse(
client,
{
stream_id: streamId,
total_chunks: totalChunks,
file_size: fileSize,
filename: options.filename,
expected_sha256: options.expectedSha256,
file_retention: options.fileRetention,
chunk_index: uploadedChunks,
chunk_data: encodeBase64(bytes),
},
options,
);
uploadedChunks++;
uploadedBytes += bytes.byteLength;
if (
response.type !== 'stream' ||
response.status !== 'chunk_received' ||
response.stream_id !== streamId ||
response.total_chunks !== totalChunks ||
response.received_chunks !== uploadedChunks
) {
throw new SnowLumaParseError('Upload acknowledgement does not match the sent chunk');
}
await options.onProgress?.({
streamId,
uploadedBytes,
fileSize,
uploadedChunks,
totalChunks,
});
}
throwIfAborted(options.signal);
// A chunk request returns early in the server handler. Finalization must
// be a separate request, after the source has ended and every ACK arrived.
const result = await uploadResponse(
client,
{ stream_id: streamId, is_complete: true },
options,
);
if (
result.type !== 'response' ||
result.status !== 'file_complete' ||
result.stream_id !== streamId ||
result.received_chunks !== totalChunks ||
result.total_chunks !== totalChunks ||
result.file_size !== fileSize ||
typeof result.file_path !== 'string' ||
!result.file_path ||
typeof result.file_name !== 'string' ||
typeof result.sha256 !== 'string' ||
!/^[a-f0-9]{64}$/i.test(result.sha256) ||
(options.expectedSha256 !== undefined &&
result.sha256.toLowerCase() !== options.expectedSha256.toLowerCase())
) {
throw new SnowLumaParseError('Invalid upload completion metadata');
}
return result;
}
export async function* downloadFileStream(
client: SnowLumaApiClient,
params: DownloadFileStreamParams,
options: DownloadFileStreamOptions = {},
): AsyncGenerator<Uint8Array, DownloadFileStreamComplete, void> {
let info: DownloadFileStreamInfo | undefined;
let chunks = 0;
let bytes = 0;
for await (const frame of client.stream(
options.action ?? 'download_file_stream',
params,
options,
)) {
throwIfAborted(options.signal);
if (frame.type === 'stream' && frame.data_type === 'file_info') {
if (
info ||
typeof frame.file_name !== 'string' ||
!isSize(frame.file_size) ||
!isSize(frame.chunk_size) ||
frame.chunk_size === 0
) {
throw new SnowLumaParseError('Invalid or duplicate download file info');
}
info = frame;
await options.onInfo?.(info);
} else if (frame.type === 'stream' && frame.data_type === 'file_chunk') {
if (
!info ||
frame.index !== chunks ||
typeof frame.data !== 'string' ||
frame.base64_size !== frame.data.length ||
typeof frame.progress !== 'number' ||
!Number.isFinite(frame.progress) ||
frame.progress < 0 ||
frame.progress > 100
) {
throw new SnowLumaParseError('Invalid or out-of-order download chunk');
}
const data = decodeBase64(frame.data);
bytes += data.byteLength;
chunks++;
if (frame.size !== data.byteLength || (info.file_size > 0 && bytes > info.file_size)) {
throw new SnowLumaParseError('Download chunk size does not match its metadata');
}
yield data;
} else if (frame.type === 'response' && frame.data_type === 'file_complete') {
if (
!info ||
frame.file_name !== info.file_name ||
frame.total_chunks !== chunks ||
frame.total_bytes !== bytes ||
(info.file_size > 0 && info.file_size !== bytes) ||
typeof frame.message !== 'string'
) {
throw new SnowLumaParseError('Download completion does not match received bytes');
}
return frame;
} else {
throw new SnowLumaParseError('Unexpected download frame');
}
}
throw new SnowLumaParseError('Download ended before file completion');
}
+61 -1
View File
@@ -6,8 +6,9 @@ import {
SnowLumaTransportError,
} from '../errors.js';
import { SnowLumaApiClient, toJsonObject } from './api-client.js';
import { createRequestAbortState, isAbortError } from '../internal/abort.js';
import { createRequestAbortState, isAbortError, throwIfAborted } from '../internal/abort.js';
import { assertApiResponse } from '../internal/json.js';
import { isStreamTerminal, readHttpFrames, streamLimits } from '../internal/streaming.js';
import type {
ActionParams,
ActionResult,
@@ -16,6 +17,9 @@ import type {
RequestOptions,
SnowLumaAction,
SnowLumaClientOptions,
SnowLumaStreamAction,
StreamApiResponse,
StreamRequestOptions,
} from '../types/index.js';
/** Options for the HTTP transport client. */
@@ -109,6 +113,62 @@ export class SnowLumaHttpClient extends SnowLumaApiClient {
}
}
override async *requestStream<TAction extends SnowLumaStreamAction>(
action: TAction,
params: ActionParams<TAction>,
options?: StreamRequestOptions,
): AsyncGenerator<StreamApiResponse<ActionResult<TAction>>, void, void> {
const { maxBufferBytes } = streamLimits(options);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
try {
throwIfAborted(abort.signal);
const response = await this.fetchImpl(this.baseUrl, {
method: 'POST',
headers: this.createHeaders(),
body: JSON.stringify({ action, params, echo: options?.echo }),
signal: abort.signal,
});
if (!response.body) {
throw new SnowLumaParseError('SnowLuma HTTP stream has no response body');
}
for await (const frame of readHttpFrames(response.body, maxBufferBytes, abort.signal)) {
throwIfAborted(abort.signal);
const terminal = isStreamTerminal(action, frame);
yield frame as StreamApiResponse<ActionResult<TAction>>;
if (terminal) {
return;
}
}
throw new SnowLumaParseError('SnowLuma HTTP stream ended before its terminal frame');
} catch (error) {
if (abort.isTimedOut()) {
throw new SnowLumaTimeoutError(
`SnowLuma stream timed out after ${timeoutMs}ms`,
timeoutMs,
{ cause: error },
);
}
if (abort.isExternallyAborted()) {
throw new SnowLumaAbortError('SnowLuma stream aborted', { cause: error });
}
if (error instanceof SnowLumaTransportError) {
throw error;
}
throw new SnowLumaConnectionError('SnowLuma HTTP stream failed', { cause: error });
} finally {
abort.cleanup();
}
}
private createHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
+146 -11
View File
@@ -24,7 +24,13 @@ import {
type EventPredicate,
} from '../events/index.js';
import { SnowLumaApiClient, toJsonObject } from './api-client.js';
import { raceWithAbort, throwIfAborted } from '../internal/abort.js';
import { createRequestAbortState, raceWithAbort, throwIfAborted } from '../internal/abort.js';
import {
isStreamTerminal,
parseStreamResponse,
StreamQueue,
streamLimits,
} from '../internal/streaming.js';
import {
appendAccessToken,
assertApiResponse,
@@ -56,6 +62,9 @@ import type {
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
SnowLumaStreamAction,
StreamApiResponse,
StreamRequestOptions,
WsRole,
} from '../types/index.js';
import type {
@@ -81,7 +90,8 @@ interface SocketConnection {
}
interface PendingRequest {
resolve(response: ApiResponse): void;
stream?: boolean;
resolve(response: ApiResponse, bytes: number): void;
reject(error: Error): void;
}
@@ -434,21 +444,141 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
});
}
override async *requestStream<TAction extends SnowLumaStreamAction>(
action: TAction,
params: ActionParams<TAction>,
options?: StreamRequestOptions,
): AsyncGenerator<StreamApiResponse<ActionResult<TAction>>, void, void> {
const queue = new StreamQueue<StreamApiResponse<ActionResult<TAction>>>(
streamLimits(options),
);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
const echo = options?.echo ?? createEcho();
const key = echoKey(echo);
const cleanup = (): void => {
// A completed stream can still be drained while a new request uses
// this echo. Its iterator cleanup must not remove the new request.
if (this.pending.get(key) === pending) {
this.pending.delete(key);
}
abort.signal.removeEventListener('abort', onAbort);
abort.cleanup();
};
const pending: PendingRequest = {
stream: true,
resolve: (response, bytes) => {
try {
queue.push(response as StreamApiResponse<ActionResult<TAction>>, bytes);
if (isStreamTerminal(action, response)) {
queue.finish();
cleanup();
}
} catch (error) {
pending.reject(
error instanceof Error ? error : new SnowLumaConnectionError(String(error)),
);
}
},
reject: (error) => {
queue.fail(error);
cleanup();
},
};
const onAbort = (): void => {
pending.reject(
abort.isTimedOut()
? new SnowLumaTimeoutError(
`SnowLuma stream timed out after ${timeoutMs}ms`,
timeoutMs,
)
: new SnowLumaAbortError('SnowLuma stream aborted', {
cause: options?.signal?.reason,
}),
);
};
try {
throwIfAborted(abort.signal);
await raceWithAbort(this.connect(), abort.signal);
throwIfAborted(abort.signal);
const socket = this.connection?.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
}
if (this.pending.has(key)) {
throw new SnowLumaConnectionError(
'A WebSocket request with this echo is already pending',
);
}
this.pending.set(key, pending);
abort.signal.addEventListener('abort', onAbort, { once: true });
try {
socket.send(JSON.stringify({ action, params, echo }));
} catch (cause) {
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket stream', {
cause,
});
}
while (true) {
throwIfAborted(options?.signal);
const next = await queue.next();
if (next.done) {
return;
}
yield next.value;
}
} catch (error) {
if (abort.isTimedOut() && !(error instanceof SnowLumaTimeoutError)) {
throw new SnowLumaTimeoutError(
`SnowLuma stream timed out after ${timeoutMs}ms`,
timeoutMs,
{ cause: error },
);
}
throw error;
} finally {
cleanup();
}
}
private handleMessage(args: unknown[]): void {
const raw = unwrapMessagePayload(args[0]);
this.emitter.emit('raw', raw);
let parsed: unknown;
let text: string;
try {
parsed = JSON.parse(rawToString(raw));
text = rawToString(raw);
parsed = JSON.parse(text);
} catch (error) {
this.emitter.emit(
'error',
new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', {
cause: error,
}),
);
const failure = new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', {
cause: error,
});
// Without a readable echo, a lost stream frame cannot be attributed
// safely. Fail active streams instead of reporting partial success.
for (const pending of this.pending.values()) {
if (pending.stream) {
pending.reject(failure);
}
}
this.emitter.emit('error', failure);
return;
}
@@ -460,7 +590,9 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
let response: ApiResponse;
try {
response = assertApiResponse(parsed);
response = pending.stream
? parseStreamResponse(parsed)
: assertApiResponse(parsed);
} catch (error) {
pending.reject(
new SnowLumaParseError('SnowLuma WebSocket response is invalid', {
@@ -470,7 +602,10 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
return;
}
pending.resolve(response);
pending.resolve(
response,
pending.stream ? new TextEncoder().encode(text).byteLength : 0,
);
this.emitter.emit('response', response);
return;
}