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 { buildBackup, planRestore, validateBackup } from './backup';
|
||||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||||
import { createFramePusher } from './debug-stream';
|
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 { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||||
import { findAvailablePort } from './port';
|
import { findAvailablePort } from './port';
|
||||||
import {
|
import {
|
||||||
@@ -313,10 +315,7 @@ export async function initWebUI(
|
|||||||
oneBotManager: OneBotManager,
|
oneBotManager: OneBotManager,
|
||||||
hookManager?: HookManager,
|
hookManager?: HookManager,
|
||||||
notificationManager?: NotificationManager,
|
notificationManager?: NotificationManager,
|
||||||
// `stateBus` is consumed in phase 3 by the /api/state/stream handler.
|
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string; stateBus?: StateBus } = {},
|
||||||
// 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 } = {},
|
|
||||||
): Promise<{ port: number }> {
|
): Promise<{ port: number }> {
|
||||||
// Resolve the client IP for per-IP rate limiting from the configured
|
// Resolve the client IP for per-IP rate limiting from the configured
|
||||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||||
@@ -929,6 +928,77 @@ export async function initWebUI(
|
|||||||
return c.json({ list: oneBotManager.getConnectionStatuses() });
|
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) => {
|
app.get('/api/logs', (c) => {
|
||||||
const limit = Number(c.req.query('limit') ?? 300);
|
const limit = Number(c.req.query('limit') ?? 300);
|
||||||
return c.json({ list: getRecentLogs(limit) });
|
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();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { StateBus, type StateResource } from '../src/webui/state-bus';
|
||||||
|
import { bindStateStream } from '../src/webui/state-stream';
|
||||||
|
|
||||||
|
interface CapturedFrame {
|
||||||
|
resource: StateResource;
|
||||||
|
data: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSnapshotFn(table: Partial<Record<StateResource, unknown>>) {
|
||||||
|
return vi.fn(async (resource: StateResource): Promise<unknown> => table[resource]);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('bindStateStream', () => {
|
||||||
|
beforeEach(() => { vi.useFakeTimers(); });
|
||||||
|
afterEach(() => { vi.useRealTimers(); });
|
||||||
|
|
||||||
|
it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
const snapshot = makeSnapshotFn({
|
||||||
|
'processes': [{ pid: 4242, name: 'qq', status: 'available' }],
|
||||||
|
'qq-list': [{ uin: '12345', nickname: 'me' }],
|
||||||
|
'connections': [{ uin: '12345', nickname: 'me', adapters: [] }],
|
||||||
|
});
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus,
|
||||||
|
snapshot,
|
||||||
|
send: (f) => sent.push(f),
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
await handle.sendAllInitial();
|
||||||
|
|
||||||
|
expect(snapshot).toHaveBeenCalledTimes(3);
|
||||||
|
expect(new Set(sent.map((f) => f.resource))).toEqual(new Set(['processes', 'qq-list', 'connections']));
|
||||||
|
const procFrame = sent.find((f) => f.resource === 'processes');
|
||||||
|
expect(procFrame?.data).toEqual([{ pid: 4242, name: 'qq', status: 'available' }]);
|
||||||
|
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a single bus publish reaches send() exactly once after debounceMs', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
const snapshot = makeSnapshotFn({ 'processes': [{ pid: 9999 }] });
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus,
|
||||||
|
snapshot,
|
||||||
|
send: (f) => sent.push(f),
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
|
||||||
|
bus.publish('processes');
|
||||||
|
expect(sent).toHaveLength(0); // still debounced
|
||||||
|
await vi.advanceTimersByTimeAsync(49);
|
||||||
|
expect(sent).toHaveLength(0);
|
||||||
|
await vi.advanceTimersByTimeAsync(2);
|
||||||
|
expect(sent).toEqual([{ resource: 'processes', data: [{ pid: 9999 }] }]);
|
||||||
|
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('coalesces a burst of publishes for the SAME resource into one send', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
const snapshot = makeSnapshotFn({ 'processes': 'fresh' });
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus, snapshot,
|
||||||
|
send: (f) => sent.push(f),
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (let i = 0; i < 20; i++) bus.publish('processes');
|
||||||
|
await vi.advanceTimersByTimeAsync(51);
|
||||||
|
expect(sent).toEqual([{ resource: 'processes', data: 'fresh' }]);
|
||||||
|
// Snapshot was only invoked once for the whole burst.
|
||||||
|
expect(snapshot).toHaveBeenCalledExactlyOnceWith('processes');
|
||||||
|
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('each resource has its own independent debounce timer', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
const snapshot = makeSnapshotFn({
|
||||||
|
'processes': 'p',
|
||||||
|
'qq-list': 'q',
|
||||||
|
'connections': 'c',
|
||||||
|
});
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus, snapshot,
|
||||||
|
send: (f) => sent.push(f),
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
|
||||||
|
bus.publish('processes');
|
||||||
|
await vi.advanceTimersByTimeAsync(30);
|
||||||
|
bus.publish('qq-list');
|
||||||
|
await vi.advanceTimersByTimeAsync(25); // processes fires at t=50 (5ms after this), qq-list pending till t=80
|
||||||
|
expect(sent.map((f) => f.resource)).toEqual(['processes']);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(30);
|
||||||
|
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list']);
|
||||||
|
|
||||||
|
bus.publish('connections');
|
||||||
|
await vi.advanceTimersByTimeAsync(51);
|
||||||
|
expect(sent.map((f) => f.resource)).toEqual(['processes', 'qq-list', 'connections']);
|
||||||
|
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dispose() stops further sends, both pending and future', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
const snapshot = makeSnapshotFn({ 'processes': 'x' });
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus, snapshot,
|
||||||
|
send: (f) => sent.push(f),
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
|
||||||
|
bus.publish('processes');
|
||||||
|
handle.dispose();
|
||||||
|
await vi.advanceTimersByTimeAsync(200);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
|
||||||
|
// Subsequent publishes are dead too.
|
||||||
|
bus.publish('processes');
|
||||||
|
await vi.advanceTimersByTimeAsync(200);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('snapshot() rejection is isolated — the failed resource is skipped and others keep flowing', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
const snapshot = vi.fn(async (resource: StateResource): Promise<unknown> => {
|
||||||
|
if (resource === 'processes') throw new Error('listProcesses failed');
|
||||||
|
if (resource === 'qq-list') return [{ uin: '1' }];
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus, snapshot,
|
||||||
|
send: (f) => sent.push(f),
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
|
||||||
|
bus.publish('processes');
|
||||||
|
bus.publish('qq-list');
|
||||||
|
await vi.advanceTimersByTimeAsync(60);
|
||||||
|
|
||||||
|
// qq-list went through; processes didn't (snapshot threw).
|
||||||
|
expect(sent.find((f) => f.resource === 'qq-list')?.data).toEqual([{ uin: '1' }]);
|
||||||
|
expect(sent.find((f) => f.resource === 'processes')).toBeUndefined();
|
||||||
|
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('send() throw is isolated — the next publish still reaches a healthy send()', async () => {
|
||||||
|
const bus = new StateBus();
|
||||||
|
const sent: CapturedFrame[] = [];
|
||||||
|
let mode: 'throw' | 'ok' = 'throw';
|
||||||
|
const snapshot = makeSnapshotFn({ 'processes': 'x' });
|
||||||
|
const handle = bindStateStream({
|
||||||
|
bus, snapshot,
|
||||||
|
send: (f) => {
|
||||||
|
if (mode === 'throw') throw new Error('controller dead');
|
||||||
|
sent.push(f);
|
||||||
|
},
|
||||||
|
debounceMs: 50,
|
||||||
|
});
|
||||||
|
|
||||||
|
bus.publish('processes');
|
||||||
|
await vi.advanceTimersByTimeAsync(60);
|
||||||
|
expect(sent).toEqual([]);
|
||||||
|
|
||||||
|
mode = 'ok';
|
||||||
|
bus.publish('processes');
|
||||||
|
await vi.advanceTimersByTimeAsync(60);
|
||||||
|
expect(sent).toEqual([{ resource: 'processes', data: 'x' }]);
|
||||||
|
|
||||||
|
handle.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user