refactor(core): extract sseResponse helper for the three WebUI SSE endpoints
/api/debug/stream、/api/state/stream、/api/logs/stream 各自逐字复制同一套 ~40 行
SSE 生命周期骨架(TextEncoder + closed 守卫 + 15s heartbeat + teardown + safe
enqueue + abort listener + event-stream headers);改一处 heartbeat 间隔/teardown
顺序/headers 要同步改三处,漏一处会 listener 泄漏。
- 新增 webui/sse-response.ts:sseResponse(c, start) 封装传输壳,给 start 回调一个
channel { raw, encode, send, onClose, isClosed, desiredSize }。各端点特有的订阅/
背压 framePusher/初始快照留在回调里。
- 三端点收敛:debug/state 用 createFramePusher(背压丢帧) + onClose 注册订阅;logs
直接 ch.send;state 的 503 守卫留在 helper 外。
- 新增 sse-response.test.ts(4 例)为这三个原本无生命周期测试的端点建立安全网。
行为严格不变:core 471 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认
helper 骨架与三端点等价、无时序/守卫回归。
This commit is contained in:
3 files changed
+177
-130
No files matched your search
@@ -23,6 +23,7 @@ import { buildBackup, planRestore, validateBackup } from './backup';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
import { createFramePusher } from './debug-stream';
|
||||
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
|
||||
import { sseResponse } from './sse-response';
|
||||
import { bindStateStream } from './state-stream';
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
import { startConnectionDiffLoop } from './connection-diff-loop';
|
||||
@@ -969,45 +970,21 @@ export async function initWebUI(
|
||||
// Live merged SSE of OneBot events + action calls across all accounts. Taps
|
||||
// are attached only while a client is connected (on-demand). A slow client is
|
||||
// dropped (not back-pressured onto the bot) with a periodic drop marker.
|
||||
app.get('/api/debug/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
const offs: Array<() => void> = [];
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const off of offs) { try { off(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: () => controller.desiredSize,
|
||||
enqueue: raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
});
|
||||
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
for (const inst of oneBotManager.getInstances()) {
|
||||
const uin = inst.uin;
|
||||
offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
|
||||
offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
|
||||
}
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
app.get('/api/debug/stream', (c) => sseResponse(c, (ch) => {
|
||||
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: ch.desiredSize,
|
||||
enqueue: ch.raw,
|
||||
encode: ch.encode,
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
});
|
||||
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
for (const inst of oneBotManager.getInstances()) {
|
||||
const uin = inst.uin;
|
||||
ch.onClose(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
|
||||
ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
|
||||
}
|
||||
}));
|
||||
|
||||
app.get('/api/qq-list', (c) => {
|
||||
const instances = oneBotManager.getInstances();
|
||||
@@ -1039,56 +1016,34 @@ export async function initWebUI(
|
||||
return c.text('state stream not configured', 503);
|
||||
}
|
||||
const liveBus = stateBus;
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let binding: { dispose(): void } | undefined;
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
binding?.dispose();
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: () => controller.desiredSize,
|
||||
enqueue: raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
});
|
||||
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
return sseResponse(c, (ch) => {
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: ch.desiredSize,
|
||||
enqueue: ch.raw,
|
||||
encode: ch.encode,
|
||||
});
|
||||
const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
|
||||
const handle = bindStateStream({
|
||||
bus: liveBus,
|
||||
snapshot: async (resource: StateResource): Promise<unknown> => {
|
||||
if (resource === 'processes') {
|
||||
if (!hookManager) return [];
|
||||
return hookManager.listProcesses();
|
||||
}
|
||||
if (resource === 'qq-list') {
|
||||
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
|
||||
}
|
||||
return oneBotManager.getConnectionStatuses();
|
||||
},
|
||||
send: (frame) => send(frame),
|
||||
debounceMs: 50,
|
||||
});
|
||||
binding = handle;
|
||||
// Prime with the initial snapshot; if the client never sees the
|
||||
// bus publish (idle system) it still has the current state.
|
||||
void handle.sendAllInitial();
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
const handle = bindStateStream({
|
||||
bus: liveBus,
|
||||
snapshot: async (resource: StateResource): Promise<unknown> => {
|
||||
if (resource === 'processes') {
|
||||
if (!hookManager) return [];
|
||||
return hookManager.listProcesses();
|
||||
}
|
||||
if (resource === 'qq-list') {
|
||||
return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
|
||||
}
|
||||
return oneBotManager.getConnectionStatuses();
|
||||
},
|
||||
send: (frame) => send(frame),
|
||||
debounceMs: 50,
|
||||
});
|
||||
ch.onClose(() => handle.dispose());
|
||||
// Prime with the initial snapshot; if the client never sees the
|
||||
// bus publish (idle system) it still has the current state.
|
||||
void handle.sendAllInitial();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1111,49 +1066,10 @@ export async function initWebUI(
|
||||
return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] });
|
||||
});
|
||||
|
||||
app.get('/api/logs/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
unsubscribe?.();
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const safeEnqueue = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try {
|
||||
controller.enqueue(chunk);
|
||||
} catch {
|
||||
// The peer dropped between abort and the next enqueue —
|
||||
// treat as end-of-stream so we don't leak listeners.
|
||||
teardown();
|
||||
}
|
||||
};
|
||||
const send = (event: unknown) => {
|
||||
safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
||||
};
|
||||
send({ type: 'ready' });
|
||||
unsubscribe = subscribeLogs((entry) => send(entry));
|
||||
heartbeat = setInterval(() => {
|
||||
safeEnqueue(encoder.encode(': heartbeat\n\n'));
|
||||
}, 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
});
|
||||
app.get('/api/logs/stream', (c) => sseResponse(c, (ch) => {
|
||||
ch.send({ type: 'ready' });
|
||||
ch.onClose(subscribeLogs((entry) => ch.send(entry)));
|
||||
}));
|
||||
|
||||
app.get('/api/processes', async (c) => {
|
||||
if (!hookManager) return c.json({ list: [] });
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { type Context } from 'hono';
|
||||
|
||||
/**
|
||||
* 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. */
|
||||
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.
|
||||
*/
|
||||
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
let heartbeat: ReturnType<typeof setInterval> | undefined;
|
||||
const cleanups: Array<() => void> = [];
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
const ch: SseChannel = {
|
||||
raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)),
|
||||
onClose: (fn) => { cleanups.push(fn); },
|
||||
isClosed: () => closed,
|
||||
desiredSize: () => controller.desiredSize,
|
||||
};
|
||||
start(ch);
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { 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', () => {
|
||||
it('returns an event-stream Response with the SSE headers', () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), () => { /* no-op */ });
|
||||
expect(res.headers.get('Content-Type')).toBe('text/event-stream');
|
||||
expect(res.headers.get('Cache-Control')).toBe('no-cache');
|
||||
expect(res.headers.get('Connection')).toBe('keep-alive');
|
||||
ac.abort(); // clear the heartbeat timer
|
||||
});
|
||||
|
||||
it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => {
|
||||
const ac = new AbortController();
|
||||
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
ch.send({ type: 'ready' });
|
||||
ch.raw(ch.encode(': heartbeat\n\n'));
|
||||
});
|
||||
const reader = res.body!.getReader();
|
||||
const dec = new TextDecoder();
|
||||
expect(dec.decode((await reader.read()).value)).toBe('data: {"type":"ready"}\n\n');
|
||||
expect(dec.decode((await reader.read()).value)).toBe(': heartbeat\n\n');
|
||||
ac.abort();
|
||||
await reader.cancel();
|
||||
});
|
||||
|
||||
it('abort runs registered cleanups exactly once, flips isClosed, and closes the stream', async () => {
|
||||
const ac = new AbortController();
|
||||
const cleanupA = vi.fn();
|
||||
const cleanupB = vi.fn();
|
||||
let channel!: Parameters<Parameters<typeof sseResponse>[1]>[0];
|
||||
const res = sseResponse(fakeCtx(ac.signal), (ch) => {
|
||||
channel = ch;
|
||||
ch.onClose(cleanupA);
|
||||
ch.onClose(cleanupB);
|
||||
});
|
||||
expect(channel.isClosed()).toBe(false);
|
||||
|
||||
ac.abort();
|
||||
expect(cleanupA).toHaveBeenCalledTimes(1);
|
||||
expect(cleanupB).toHaveBeenCalledTimes(1);
|
||||
expect(channel.isClosed()).toBe(true);
|
||||
|
||||
const r = await res.body!.getReader().read();
|
||||
expect(r.done).toBe(true);
|
||||
});
|
||||
|
||||
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) => { channel = ch; });
|
||||
ac.abort();
|
||||
expect(() => channel.send({ x: 1 })).not.toThrow();
|
||||
expect(channel.isClosed()).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user