feat(webui): /api/state/stream SSE — push processes/qq-list/connections
Phase 3 of switching the three dashboard resources from REST polling to
SSE push.
- New pure helper packages/core/src/webui/state-stream.ts owns the
debounce/snapshot/fan-out logic, decoupled from Hono so it's unit-testable
with fake timers (7 tests cover initial-snapshot, single-publish coalesce,
per-resource independent debounce, dispose-cancels-pending, snapshot
rejection isolation, send() throw isolation).
- /api/state/stream handler in server.ts mirrors the /api/debug/stream
pattern: ReadableStream + createFramePusher (drop-under-backpressure with
the same {kind:'dropped'} marker), 15s heartbeats, abort-signal teardown.
On connect: one frame per resource. After: a fresh-snapshot frame per
StateBus invalidation, 50ms per-resource debounce.
- The endpoint 503s when stateBus is absent (build without state-wiring),
so clients can still fall back to the REST endpoints; the existing
GET /api/processes etc remain in place for initial fetch + reconcile.
44 test files, 426/426 core suite green.
This commit is contained in:
3 files changed
+356
-4
No files matched your search
@@ -21,6 +21,8 @@ import { coerceSettingsPatch } from './system-settings';
|
||||
import { buildBackup, planRestore, validateBackup } from './backup';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
import { createFramePusher } from './debug-stream';
|
||||
import { bindStateStream } from './state-stream';
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { findAvailablePort } from './port';
|
||||
import {
|
||||
@@ -313,10 +315,7 @@ export async function initWebUI(
|
||||
oneBotManager: OneBotManager,
|
||||
hookManager?: HookManager,
|
||||
notificationManager?: NotificationManager,
|
||||
// `stateBus` is consumed in phase 3 by the /api/state/stream handler.
|
||||
// Threading it through here in phase 2 so the wiring in index.ts can stay
|
||||
// committed independently of the SSE endpoint.
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: import('./state-bus').StateBus } = {},
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
|
||||
): Promise<{ port: number }> {
|
||||
// Resolve the client IP for per-IP rate limiting from the configured
|
||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||
@@ -929,6 +928,77 @@ export async function initWebUI(
|
||||
return c.json({ list: oneBotManager.getConnectionStatuses() });
|
||||
});
|
||||
|
||||
// Combined SSE feed for the dashboard's three live resources — processes,
|
||||
// qq-list, connections. Replaces the 3s REST polling tick in
|
||||
// app-layout.tsx; the REST endpoints above stay for the initial fetch
|
||||
// before SSE connects and for the slow (30s) reconciliation fallback.
|
||||
//
|
||||
// On connect: one frame per resource with the current snapshot. After
|
||||
// that: a fresh snapshot per resource only when the StateBus signals a
|
||||
// change (HookSession status-changed, BridgeManager session edges, the
|
||||
// connection-status diff loop). 50ms per-resource debounce coalesces a
|
||||
// burst (e.g. multiple HookSessions flipping status simultaneously).
|
||||
const stateBus = listener.stateBus;
|
||||
app.get('/api/state/stream', (c) => {
|
||||
if (!stateBus) {
|
||||
// Build without state-wiring (e.g. a future headless mode) — clients
|
||||
// fall back to the REST endpoints. Treat as endpoint-not-here.
|
||||
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' });
|
||||
|
||||
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' },
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/logs', (c) => {
|
||||
const limit = Number(c.req.query('limit') ?? 300);
|
||||
return c.json({ list: getRecentLogs(limit) });
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Bind a StateBus to an SSE-friendly `send` callback: every publish becomes
|
||||
* a debounced fresh-snapshot frame, and `sendAllInitial()` primes a new
|
||||
* connection with one frame per resource.
|
||||
*
|
||||
* Decoupled from the HTTP layer so the route handler in server.ts can drop
|
||||
* its responsibility down to "open a ReadableStream, hand its enqueue to
|
||||
* bindStateStream, abort tears it down". Pure logic = unit-testable with
|
||||
* fake timers; no Response/controller mocking needed.
|
||||
*
|
||||
* Per-resource debounce, not global: an 'qq-list' churn during a slow
|
||||
* 'processes' burst must not delay the qq-list frame, and a 'connections'
|
||||
* diff loop running at 500ms must not coalesce 10 unrelated processes
|
||||
* events into one. Each resource is its own timer.
|
||||
*/
|
||||
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
|
||||
export interface StateStreamFrame {
|
||||
resource: StateResource;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
export interface BindStateStreamOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current snapshot for one resource. May be sync or async. */
|
||||
snapshot: (resource: StateResource) => unknown | Promise<unknown>;
|
||||
/** Receive a fresh frame; called once per debounced publish.
|
||||
* Exceptions are caught — a dead controller must not abort the bus
|
||||
* subscription or break sibling resources. */
|
||||
send: (frame: StateStreamFrame) => void;
|
||||
/** Coalesce window in milliseconds; default 50. */
|
||||
debounceMs?: number;
|
||||
}
|
||||
|
||||
export interface StateStreamHandle {
|
||||
/** Emit one frame per resource using the current snapshot. Use on connect. */
|
||||
sendAllInitial(): Promise<void>;
|
||||
/** Stop subscribing + cancel pending timers. Subsequent bus publishes
|
||||
* produce nothing through this binding. */
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connections'];
|
||||
|
||||
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
|
||||
const debounceMs = opts.debounceMs ?? 50;
|
||||
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
|
||||
let disposed = false;
|
||||
|
||||
const flush = async (resource: StateResource): Promise<void> => {
|
||||
if (disposed) return;
|
||||
let data: unknown;
|
||||
try {
|
||||
data = await opts.snapshot(resource);
|
||||
} catch {
|
||||
// Per-resource snapshot failure (e.g. listProcesses threw): skip
|
||||
// this frame so siblings keep flowing. The next publish for the
|
||||
// same resource gets a fresh attempt.
|
||||
return;
|
||||
}
|
||||
if (disposed) return;
|
||||
try {
|
||||
opts.send({ resource, data });
|
||||
} catch {
|
||||
// Downstream consumer (e.g. closed SSE controller) — same isolation
|
||||
// contract as snapshot failures.
|
||||
}
|
||||
};
|
||||
|
||||
const schedule = (resource: StateResource): void => {
|
||||
if (disposed) return;
|
||||
const existing = timers.get(resource);
|
||||
if (existing) clearTimeout(existing);
|
||||
const t = setTimeout(() => {
|
||||
timers.delete(resource);
|
||||
void flush(resource);
|
||||
}, debounceMs);
|
||||
timers.set(resource, t);
|
||||
};
|
||||
|
||||
const unsubscribe = opts.bus.subscribe(schedule);
|
||||
|
||||
return {
|
||||
async sendAllInitial(): Promise<void> {
|
||||
if (disposed) return;
|
||||
// Fire all three in parallel. Each resource's snapshot is independent
|
||||
// so a slow listProcesses() doesn't gate qq-list/connections.
|
||||
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
|
||||
},
|
||||
dispose(): void {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
for (const t of timers.values()) clearTimeout(t);
|
||||
timers.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user