fix: unify stream cleanup and configuration response handling

This commit is contained in:
手瓜一十雪
2026-10-18 13:18:25 +08:00
parent 38a7c3da63
commit 1faa6c58fa
13 changed files with 463 additions and 247 deletions
+24 -50
View File
@@ -20,6 +20,7 @@ import os from 'os';
import path from 'path';
import { randomBytes } from 'crypto';
import { traceWebuiMutationRequestChunk } from './mutation-trace';
import { sseResponse } from './sse-response';
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
* kept distinct so the two cleanup stories don't entangle. */
@@ -203,70 +204,43 @@ export function buildStreamInvokeResponse(
signal: AbortSignal,
delay: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
return sseResponse(signal, (channel) => {
const isAlive = () => !channel.isClosed();
const onAbort = () => {
closed = true;
};
const emit = async (json: string): Promise<void> => {
if (!isAlive()) {
throw new Error('stream transport closed');
}
signal.addEventListener('abort', onAbort);
const isAlive = () => !closed && !signal.aborted;
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
const emit = async (json: string): Promise<void> => {
if (!isAlive()) {
throw new Error('stream transport closed');
}
while (isAlive() && (channel.desiredSize() ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
// Backpressure WITHOUT dropping: wait for the consumer to catch up.
let spins = 0;
if (!isAlive()) {
throw new Error('stream transport closed');
}
while (isAlive() && (controller.desiredSize ?? 1) <= 0 && spins < DRAIN_MAX_SPINS) {
await delay(DRAIN_WAIT_MS);
spins += 1;
}
if (!isAlive()) {
throw new Error('stream transport closed');
}
controller.enqueue(encoder.encode(`data: ${json}\n\n`));
};
channel.raw(channel.encode(`data: ${json}\n\n`));
};
const run = async () => {
try {
await driver(rawRequest, emit, isAlive);
} catch (err) {
if (isAlive()) {
const msg = err instanceof Error ? err.message : 'stream error';
try {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: 'failed', retcode: 1400, message: msg, wording: msg })}\n\n`,
),
);
} catch {
/* controller already torn down */
}
channel.send({ status: 'failed', retcode: 1400, message: msg, wording: msg });
}
} finally {
signal.removeEventListener('abort', onAbort);
try {
controller.close();
} catch {
/* already closed */
}
channel.close();
}
},
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
};
void run();
});
}
+3 -3
View File
@@ -753,8 +753,8 @@ export async function initWebUI(
const app = new Hono();
const shutdownStreams = new AbortController();
const sseResponse = (...args: Parameters<typeof createSseResponse>) =>
createSseResponse(args[0], args[1], shutdownStreams.signal);
const sseResponse = (c: Context, start: Parameters<typeof createSseResponse>[1]) =>
createSseResponse(c.req.raw.signal, start, shutdownStreams.signal);
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
const storageManagement = new StorageManagementService({
@@ -1726,7 +1726,7 @@ export async function initWebUI(
return buildStreamInvokeResponse(
(rq, emit, alive) => inst.invokeStream(rq, emit, alive),
rawRequest,
c.req.raw.signal,
AbortSignal.any([c.req.raw.signal, shutdownStreams.signal]),
);
});
+58 -64
View File
@@ -1,42 +1,25 @@
import { type Context } from 'hono';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('WebUI.SSE');
/**
* The per-connection channel handed to an SSE endpoint's `start` callback.
* Everything the endpoint needs to talk to the client, without owning the
* transport lifecycle (heartbeat / teardown / abort / headers).
*/
export interface SseChannel {
/** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */
raw(chunk: Uint8Array): void;
/** Encode a string to bytes (shared TextEncoder). */
encode(s: string): Uint8Array;
/** Convenience: enqueue one `data: <json>\n\n` frame. */
send(payload: unknown): void;
/** Register a cleanup to run once on teardown (unsubscribe / dispose). */
onClose(fn: () => void): void;
/** True after teardown — guard sends from late subscription callbacks. */
onClose(cleanup: () => void): void;
close(): void;
isClosed(): boolean;
/** Underlying controller backpressure signal, for `createFramePusher`. */
desiredSize(): number | null;
}
/**
* The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the
* TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown
* (clear heartbeat → run registered cleanups → close the controller), safe
* enqueue (a throw means the peer dropped → teardown), the abort listener, and
* the `text/event-stream` headers. `start` wires up the endpoint-specific
* subscription + initial sends via the channel.
*
* Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream`
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
* teardown-order / header change had to be kept in sync across all three.
*/
/** Owns stream cancellation, subscriptions and the keep-alive timer. */
export function sseResponse(
c: Context,
start: (ch: SseChannel) => void,
request: AbortSignal,
start: (channel: SseChannel) => void,
shutdown?: AbortSignal,
): Response {
const signal = shutdown ? AbortSignal.any([request, shutdown]) : request;
let cancel!: () => void;
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
@@ -44,67 +27,78 @@ export function sseResponse(
let heartbeat: ReturnType<typeof setInterval> | undefined;
const cleanups: Array<() => void> = [];
const teardown = () => {
const cleanup = (fn: () => void) => {
try {
fn();
} catch (error) {
log.warn('stream cleanup failed: %s', error);
}
};
const teardown = (closeStream = true) => {
if (closed) {
return;
}
closed = true;
clearInterval(heartbeat);
signal.removeEventListener('abort', onAbort);
cleanups.splice(0).forEach(cleanup);
if (heartbeat) {
clearInterval(heartbeat);
}
for (const fn of cleanups) {
try {
fn();
} catch {
/* ignore */
}
}
try {
if (closeStream) {
controller.close();
} catch {
/* ignore */
}
};
const onAbort = () => teardown();
cancel = () => teardown(false);
signal.addEventListener('abort', onAbort, { once: true });
if (signal.aborted) {
teardown();
return;
}
const raw = (chunk: Uint8Array) => {
if (closed) {
return;
}
try {
if (!closed) {
controller.enqueue(chunk);
} catch {
teardown();
}
};
const ch: SseChannel = {
const channel: SseChannel = {
raw,
encode: (s) => encoder.encode(s),
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
onClose: (fn) => {
cleanups.push(fn);
encode: (text) => encoder.encode(text),
send: (payload) => {
if (!closed) {
raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
}
},
onClose: (fn) => {
if (closed) {
cleanup(fn);
} else {
cleanups.push(fn);
}
},
close: () => teardown(),
isClosed: () => closed,
desiredSize: () => controller.desiredSize,
};
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
shutdown?.addEventListener('abort', teardown, { once: true });
cleanups.push(() => {
c.req.raw.signal.removeEventListener('abort', teardown);
shutdown?.removeEventListener('abort', teardown);
});
if (shutdown?.aborted) {
try {
start(channel);
if (!closed) {
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
}
} catch (error) {
teardown();
throw error;
}
},
cancel() {
cancel();
},
});
return new Response(stream, {
headers: {
+69 -11
View File
@@ -1,18 +1,75 @@
import { describe, it, expect, vi } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { sseResponse } from '../src/webui/sse-response';
// A minimal hono-Context stand-in: sseResponse only reads c.req.raw.signal.
function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
return { req: { raw: { signal } } } as unknown as Parameters<typeof sseResponse>[0];
}
describe('sseResponse', () => {
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
});
it('releases subscriptions immediately when the response body is canceled', async () => {
vi.useFakeTimers();
const request = new AbortController();
const cleanup = vi.fn();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
const response = sseResponse(request.signal, (ch) => {
channel = ch;
ch.onClose(cleanup);
});
await response.body!.cancel();
expect(channel.isClosed()).toBe(true);
expect(cleanup).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
request.abort();
expect(cleanup).toHaveBeenCalledOnce();
});
it('does not subscribe when the request was already aborted', () => {
vi.useFakeTimers();
const request = new AbortController();
request.abort();
const start = vi.fn();
sseResponse(request.signal, start);
expect(start).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(0);
});
it('releases subscriptions registered before and after an abort during setup', () => {
vi.useFakeTimers();
const request = new AbortController();
const before = vi.fn();
const after = vi.fn();
sseResponse(request.signal, (channel) => {
channel.onClose(before);
request.abort();
channel.onClose(after);
});
expect(before).toHaveBeenCalledOnce();
expect(after).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
it('releases subscriptions when endpoint setup throws', () => {
vi.useFakeTimers();
const request = new AbortController();
const cleanup = vi.fn();
expect(() =>
sseResponse(request.signal, (channel) => {
channel.onClose(cleanup);
throw new Error('setup failed');
}),
).toThrow('setup failed');
expect(cleanup).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
it('finishes active streams and releases subscriptions during server shutdown', async () => {
const request = new AbortController();
const shutdown = new AbortController();
let cleanups = 0;
const response = sseResponse(
fakeCtx(request.signal),
request.signal,
(channel) => {
channel.onClose(() => {
cleanups++;
@@ -26,9 +83,10 @@ describe('sseResponse', () => {
request.abort();
expect(cleanups).toBe(1);
});
it('returns an event-stream Response with the SSE headers', () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), () => {
const res = sseResponse(ac.signal, () => {
/* no-op */
});
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
@@ -39,7 +97,7 @@ describe('sseResponse', () => {
it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
const res = sseResponse(ac.signal, (ch) => {
ch.send({ type: 'ready' });
ch.raw(ch.encode(': heartbeat\n\n'));
});
@@ -56,7 +114,7 @@ describe('sseResponse', () => {
const cleanupA = vi.fn();
const cleanupB = vi.fn();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
const res = sseResponse(ac.signal, (ch) => {
channel = ch;
ch.onClose(cleanupA);
ch.onClose(cleanupB);
@@ -75,7 +133,7 @@ describe('sseResponse', () => {
it('send after teardown is a silent no-op', () => {
const ac = new AbortController();
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
sseResponse(fakeCtx(ac.signal), (ch) => {
sseResponse(ac.signal, (ch) => {
channel = ch;
});
ac.abort();
@@ -114,6 +114,45 @@ describe('streamUploadToDisk', () => {
describe('buildStreamInvokeResponse', () => {
const noDelay = async () => {};
it('cancels delivery while the action is still pending', async () => {
let finish!: () => void;
const pending = new Promise<void>((resolve) => {
finish = resolve;
});
let isAlive!: () => boolean;
const response = buildStreamInvokeResponse(
async (_request, _emit, alive) => {
isAlive = alive;
await pending;
},
'{}',
new AbortController().signal,
);
const canceled = response.body!.cancel();
try {
expect(isAlive()).toBe(false);
} finally {
finish();
await canceled;
}
});
it('does not invoke an action for an already aborted request', async () => {
const controller = new AbortController();
controller.abort();
let invoked = false;
const response = buildStreamInvokeResponse(
async () => {
invoked = true;
},
'{}',
controller.signal,
);
await readSse(response);
expect(invoked).toBe(false);
});
it('relays each emitted frame as one SSE event, in order', async () => {
const ac = new AbortController();
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- Release cancellation listeners as soon as a request stops waiting for a connection.
- Isolate WebSocket connection lifetimes and release request timers and abort listeners on every outcome.
- Reject duplicate in-flight WebSocket echoes instead of overwriting the original request.
- Add `getGroupShareLink()` and typed `get_group_share_link` support for group invitation links.
+11 -8
View File
@@ -82,16 +82,19 @@ export function raceWithAbort<T>(
return promise;
}
throwIfAborted(signal, message);
return new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
let onAbort!: () => void;
const aborted = new Promise<never>((_resolve, reject) => {
onAbort = () => {
reject(new SnowLumaAbortError(message, { cause: signal.reason }));
};
signal.addEventListener('abort', onAbort, { once: true });
promise.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
});
if (signal.aborted) {
onAbort();
} else {
signal.addEventListener('abort', onAbort, { once: true });
}
});
return Promise.race([aborted, promise]).finally(() => {
signal.removeEventListener('abort', onAbort);
});
}
+42 -1
View File
@@ -1,9 +1,50 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createRequestAbortState } from '../src/internal/abort';
import { createRequestAbortState, raceWithAbort } from '../src/internal/abort';
afterEach(() => vi.useRealTimers());
describe('request cancellation', () => {
it('honors an existing cancellation before a completed operation', async () => {
const controller = new AbortController();
controller.abort('already canceled');
await expect(
raceWithAbort(Promise.resolve('done'), controller.signal),
).rejects.toMatchObject({
cause: 'already canceled',
});
});
it('releases its listener when cancellation wins against a pending operation', async () => {
const operation = Promise.withResolvers<void>();
const controller = new AbortController();
const remove = vi.spyOn(controller.signal, 'removeEventListener');
const result = raceWithAbort(operation.promise, controller.signal);
controller.abort('canceled');
await expect(result).rejects.toMatchObject({ cause: 'canceled' });
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
operation.resolve();
});
it.each(['resolve', 'reject'] as const)(
'releases its listener when the operation will %s',
async (outcome) => {
const operation = Promise.withResolvers<string>();
const controller = new AbortController();
const remove = vi.spyOn(controller.signal, 'removeEventListener');
const result = raceWithAbort(operation.promise, controller.signal);
if (outcome === 'resolve') {
operation.resolve('done');
await expect(result).resolves.toBe('done');
} else {
operation.reject(new Error('failed'));
await expect(result).rejects.toThrow('failed');
}
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
},
);
it('keeps caller cancellation as the cause when the timeout expires later', () => {
vi.useFakeTimers();
const caller = new AbortController();
+3
View File
@@ -22,6 +22,9 @@ status, OneBot configuration, logs, storage, and server settings.
result; do not convert failed responses into successful feedback.
- JSON endpoints must return an object. Malformed or non-object responses are
reported as errors rather than displayed as empty lists or default settings.
- Configuration responses include `config`; saves also report `saved`, `applied`,
`online`, `errors`, and `message`. The UI uses these fields without legacy aliases
or a second request after saving.
- Password change flows use floating labels and inline validation consistently.
- Password strength details appear only while the new-password field has focus
and leave with the same motion language when focus moves away.
+53 -108
View File
@@ -32,6 +32,7 @@ import {
ApiError,
type ApiClient,
type ChangePasswordResult,
type ConfigSaveResult,
type CreateApiClientOptions,
type LoginResult,
type LogsStreamOptions,
@@ -128,61 +129,13 @@ class HttpApiClient implements ApiClient {
this.config = {
get: async (uin) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
const data = await this.getJson<{ config?: unknown } | unknown>(url);
const raw =
typeof data === 'object' &&
data != null &&
'config' in (data as Record<string, unknown>)
? (data as { config: unknown }).config
: data;
return normalizeOneBotConfig(raw);
const data = await this.getJson<{ config: unknown }>(url);
return normalizeOneBotConfig(data.config);
},
save: async (uin, config) => {
const url = `/api/config/${encodeURIComponent(uin)}`;
const result = await this.fetchJson<{
success?: boolean;
saved?: boolean;
applied?: boolean;
online?: boolean;
reloaded?: boolean;
errors?: Array<{
name: string;
kind?: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
phase: string;
message: string;
at: number;
restored?: boolean;
}>;
config?: unknown;
message?: string;
}>(url, {
method: 'POST',
body: JSON.stringify(config),
});
// Refetch the canonical persisted view after the save. Runtime apply
// is a separate fact and is preserved alongside that config.
let canonical =
result.config === undefined ? null : normalizeOneBotConfig(result.config);
if (canonical === null) {
try {
canonical = await this.config.get(uin);
} catch (error) {
// Legacy servers omit `config`. Their POST still confirmed the
// save, so a follow-up GET failure must not become "保存失败".
console.warn('config saved but canonical refetch failed', error);
canonical = config;
}
}
return {
config: canonical,
saved: result.saved ?? result.success === true,
applied: result.applied ?? result.reloaded === true,
online: result.online ?? result.reloaded === true,
errors: Array.isArray(result.errors) ? result.errors : [],
message: result.message ?? '配置保存成功',
};
const result = await this.postJson<ConfigSaveResult>(url, config);
return { ...result, config: normalizeOneBotConfig(result.config) };
},
};
@@ -747,14 +700,7 @@ class HttpApiClient implements ApiClient {
// ---------- SSE ----------
/**
* Open a token-authed SSE channel to `path`, dispatching each parsed frame to
* `onMessage` and surfacing transport state ('open' / 'reconnecting' /
* 'closed') via `onStatus`. The fetch stream reconnects after transport loss
* so it retains EventSource's user-visible behaviour while keeping the token
* in the WebUI session header. A malformed frame (or a throw from
* `onMessage`) is skipped. The returned disposer aborts the active request.
*/
/** Fetch-based SSE keeps the session token in a header and reconnects after transport loss. */
private openSseChannel<T>(
path: string,
onMessage: (data: T) => void,
@@ -770,28 +716,47 @@ class HttpApiClient implements ApiClient {
let active: AbortController | null = null;
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
const clearReconnect = () => {
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
};
const disconnect = () => {
clearReconnect();
active?.abort();
active = null;
};
const scheduleReconnect = () => {
if (disposed || reconnectTimer !== null) {
return;
}
onStatus?.('reconnecting');
reconnectTimer = setTimeout(() => {
reconnectTimer = null;
void connect();
}, 1_000);
onStatus?.('reconnecting');
};
const connect = async () => {
if (disposed || active) {
return;
}
const token = this.currentToken;
if (disposed || !token) {
onStatus?.('closed');
if (!token) {
dispose();
return;
}
const controller = new AbortController();
active = controller;
const isCurrent = () =>
!disposed && active === controller && !controller.signal.aborted;
try {
const response = await fetch(path, {
@@ -803,12 +768,15 @@ class HttpApiClient implements ApiClient {
signal: controller.signal,
});
if (!isCurrent()) {
await response.body?.cancel();
return;
}
if (response.status === 401) {
disposed = true;
active = null;
dispose();
this.setToken(null);
this.onUnauthorized?.();
onStatus?.('closed');
return;
}
@@ -822,9 +790,13 @@ class HttpApiClient implements ApiClient {
let buffer = '';
try {
while (!disposed) {
while (isCurrent()) {
const { done, value } = await reader.read();
if (!isCurrent()) {
break;
}
if (done) {
buffer += decoder.decode();
break;
@@ -836,7 +808,7 @@ class HttpApiClient implements ApiClient {
throw new Error('SSE frame buffer exceeded 1 MiB');
}
for (;;) {
while (isCurrent()) {
const lf = buffer.indexOf('\n\n');
const crlf = buffer.indexOf('\r\n\r\n');
let separator = -1;
@@ -880,18 +852,14 @@ class HttpApiClient implements ApiClient {
/* already closed */
}
try {
reader.releaseLock();
} catch {
/* already released */
}
reader.releaseLock();
}
if (!disposed) {
if (isCurrent()) {
scheduleReconnect();
}
} catch {
if (!disposed && !controller.signal.aborted) {
if (isCurrent()) {
scheduleReconnect();
}
} finally {
@@ -901,28 +869,18 @@ class HttpApiClient implements ApiClient {
}
};
const onPageHide = () => {
active?.abort();
};
const onPageHide = disconnect;
const onPageShow = (event: PageTransitionEvent) => {
if (event.persisted && !disposed) {
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
clearReconnect();
void connect();
}
};
const onVisible = () => {
if (document.visibilityState === 'visible' && !disposed && !active) {
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
clearReconnect();
void connect();
}
};
@@ -936,9 +894,7 @@ class HttpApiClient implements ApiClient {
document.addEventListener('freeze', onPageHide);
}
void connect();
return () => {
const dispose = () => {
if (disposed) {
return;
}
@@ -952,15 +908,12 @@ class HttpApiClient implements ApiClient {
document.removeEventListener('freeze', onPageHide);
}
if (reconnectTimer !== null) {
clearTimeout(reconnectTimer);
}
reconnectTimer = null;
active?.abort();
active = null;
disconnect();
onStatus?.('closed');
};
void connect();
return dispose;
}
private openLogStream(options: LogsStreamOptions): () => void {
@@ -985,12 +938,7 @@ class HttpApiClient implements ApiClient {
};
}
/** Open the single shared /api/logs/stream connection; every frame and status
* change fans out to all subscribers, each isolated so one throwing handler
* can't drop the frame for the others (and a subscriber unsubscribed mid-frame
* is skipped). A no-token attempt does NOT cache a dead disposer — it reports
* 'closed' and returns so a later subscribe / setToken can open for real,
* avoiding poisoning the shared cache. */
/** Isolate subscribers and leave unauthenticated attempts free to reconnect after login. */
private openSharedLogStream(): void {
if (!this.currentToken) {
this.lastLogStatus = 'closed';
@@ -1042,10 +990,7 @@ class HttpApiClient implements ApiClient {
);
}
/** Token changed (login / re-login / logout): the shared stream baked the old
* token into its URL, so tear it down and reopen with the new one if anyone is
* still listening. Without this a re-login would leave the feed retrying a
* stale-token URL forever. */
/** A new request must pick up the changed session token. */
private reopenSharedLogStream(): void {
if (this.logStreamDispose) {
this.logStreamDispose();
+5 -1
View File
@@ -45,7 +45,11 @@ function normalizeNotifications(raw: unknown): { channelIds: string[] } {
* into the canonical {@link OneBotConfig} the editor expects.
*/
export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
const cfg = (raw ?? {}) as Record<string, unknown>;
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
throw new Error('服务端返回了无效的配置');
}
const cfg = raw as Record<string, unknown>;
const nets = (cfg.networks as Record<string, unknown> | undefined) ?? {};
const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
const legacyReport = !!cfg.reportSelfMessage;
@@ -0,0 +1,53 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createApiClient } from '../src/lib/api/client';
import { normalizeOneBotConfig } from '../src/lib/onebot-config';
afterEach(() => vi.unstubAllGlobals());
describe('API client configuration', () => {
const config = normalizeOneBotConfig({});
const tokenStore = { load: () => 'token', save: vi.fn() };
it('keeps persisted configuration separate from failed runtime application', async () => {
const result = {
config,
saved: true,
applied: false,
online: true,
errors: [{ name: 'http', phase: 'start', message: 'port in use', at: 1 }],
message: '配置已保存,应用失败',
};
const fetchMock = vi.fn().mockResolvedValue(Response.json(result));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.config.save('12345', config)).resolves.toEqual(result);
expect(fetchMock).toHaveBeenCalledOnce();
});
it('rejects a save response without configuration instead of refetching or returning the form', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(Response.json({ success: true, reloaded: true }))
.mockRejectedValue(new Error('refetch failed'));
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore });
await expect(client.config.save('12345', config)).rejects.toThrow('无效的配置');
expect(fetchMock).toHaveBeenCalledOnce();
});
it('reads the configuration from the server envelope', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ config })));
const client = createApiClient({ tokenStore });
await expect(client.config.get('12345')).resolves.toEqual(config);
});
it('rejects a response without the configuration envelope', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json(config)));
const client = createApiClient({ tokenStore });
await expect(client.config.get('12345')).rejects.toThrow('无效的配置');
});
});
@@ -3,8 +3,10 @@ import { createApiClient } from '../src/lib/api/client';
const encoder = new TextEncoder();
describe('API client SSE authentication', () => {
describe('API client SSE lifecycle', () => {
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllGlobals();
});
@@ -47,6 +49,12 @@ describe('API client SSE authentication', () => {
});
it('clears the session and stops reconnecting after an unauthorized response', async () => {
const page = new EventTarget();
const document = new EventTarget();
const removePageListener = vi.spyOn(page, 'removeEventListener');
const removeDocumentListener = vi.spyOn(document, 'removeEventListener');
vi.stubGlobal('window', page);
vi.stubGlobal('document', document);
const save = vi.fn();
const onUnauthorized = vi.fn();
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 401 }));
@@ -63,6 +71,99 @@ describe('API client SSE authentication', () => {
expect(save).toHaveBeenCalledWith(null);
expect(statuses.at(-1)).toBe('closed');
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(removePageListener).toHaveBeenCalledWith('pagehide', expect.any(Function));
expect(removePageListener).toHaveBeenCalledWith('pageshow', expect.any(Function));
expect(removeDocumentListener).toHaveBeenCalledWith(
'visibilitychange',
expect.any(Function),
);
expect(removeDocumentListener).toHaveBeenCalledWith('freeze', expect.any(Function));
});
it('stops delivering the current frame batch after disposal', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(
new Response(
'data: {"kind":"ready"}\n\ndata: {"kind":"invalidate","resource":"qq-list"}\n\n',
),
),
);
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const onEvent = vi.fn(() => dispose());
const dispose = client.stateStream({ onEvent });
await vi.waitFor(() => expect(onEvent).toHaveBeenCalled());
expect(onEvent).toHaveBeenCalledOnce();
});
it('ignores a delayed unauthorized response from a disposed connection', async () => {
vi.useFakeTimers();
const response = Promise.withResolvers<Response>();
vi.stubGlobal(
'fetch',
vi.fn(() => response.promise),
);
const save = vi.fn();
const onUnauthorized = vi.fn();
const client = createApiClient({
tokenStore: { load: () => 'token', save },
onUnauthorized,
});
const dispose = client.stateStream({ onEvent: vi.fn() });
dispose();
response.resolve(new Response(null, { status: 401 }));
await vi.advanceTimersByTimeAsync(0);
expect(onUnauthorized).not.toHaveBeenCalled();
expect(save).not.toHaveBeenCalled();
});
it('clears the reconnect timer when disposed by the status callback', async () => {
vi.useFakeTimers();
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('')));
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const dispose = client.stateStream({
onEvent: vi.fn(),
onStatus: (status) => {
if (status === 'reconnecting') {
dispose();
}
},
});
await vi.advanceTimersByTimeAsync(0);
expect(vi.getTimerCount()).toBe(0);
});
it('suspends reconnects until the page returns and keeps one active request', async () => {
vi.useFakeTimers();
const page = new EventTarget();
vi.stubGlobal('window', page);
vi.stubGlobal('document', Object.assign(new EventTarget(), { visibilityState: 'visible' }));
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(''))
.mockImplementation(
(_url: string, init: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init.signal!.addEventListener('abort', () => reject(init.signal!.reason), {
once: true,
});
}),
);
vi.stubGlobal('fetch', fetchMock);
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
const onStatus = vi.fn();
const dispose = client.stateStream({ onEvent: vi.fn(), onStatus });
await vi.advanceTimersByTimeAsync(0);
expect(onStatus).toHaveBeenCalledWith('reconnecting');
page.dispatchEvent(new Event('pagehide'));
await vi.advanceTimersByTimeAsync(1000);
expect(fetchMock).toHaveBeenCalledOnce();
page.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
page.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
expect(fetchMock).toHaveBeenCalledTimes(2);
dispose();
});
it('reconnects after a completed stream without leaking the token', async () => {