refactor: use native async discovery and simplify shared state

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:57:18 +08:00
1 parent 5032cbb8c0
commit 4e2b6b1200
87 files changed
+2063 -2002

No files matched your search

@@ -40,8 +40,7 @@ export interface ConnectionDiffLoopHandle {
export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): ConnectionDiffLoopHandle {
const intervalMs = opts.intervalMs ?? 500;
let lastSerialized = '';
let haveBaseline = false;
let lastSerialized: string | undefined | null = null;
let disposed = false;
// One-shot diagnostic latch: a projector that starts throwing only after
// a shape regression would otherwise wedge the baseline silently — no
@@ -112,13 +111,12 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
const serialized = JSON.stringify(comparable);
if (!haveBaseline) {
if (lastSerialized === null) {
// First successful observation. The SSE handler's sendAllInitial
// already shipped a `connections` frame to every connected client
// on connect, so the baseline is what they already have — emitting
// it again would be a duplicate. Just store it.
lastSerialized = serialized;
haveBaseline = true;
return;
}
@@ -144,7 +142,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
// lifetime by design, but tests / a future hot-reload scenario must be
// able to exit cleanly without an outstanding interval ref. Mirrors the
// tokenJanitor pattern in server.ts.
timer.unref?.();
timer.unref();
return {
dispose(): void {
+1 -4
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
@@ -434,10 +435,6 @@ function invoke(options: RestoreBackupOptions, operation: RestoreOperation): voi
options.beforeOperation?.(operation);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function isMissingPathError(error: unknown): boolean {
return (
typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
+1 -1
View File
@@ -853,7 +853,7 @@ export async function initWebUI(
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
// unbounded and replaces the per-request O(n) sweep we used to do.
const tokenJanitor = setInterval(purgeExpiredTokens, 60_000);
tokenJanitor.unref?.();
tokenJanitor.unref();
// ─── Login ───────────────────────────────────────────────────────────────
app.post('/api/login', async (c) => {
+65 -101
View File
@@ -1,21 +1,9 @@
/**
* 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 { errorMessage } from '@snowluma/common/errors';
import { createLogger } from '@snowluma/common/logger';
import type { StateBus, StateResource } from './state-bus';
const log = createLogger('WebUI.StateStream');
export interface StateStreamFrame {
resource: StateResource;
data: unknown;
@@ -45,112 +33,88 @@ const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connec
export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle {
const debounceMs = opts.debounceMs ?? 50;
const timers = new Map<StateResource, ReturnType<typeof setTimeout>>();
// Single-flight per resource: at most one in-flight flush per resource so
// an uneven snapshot latency cannot interleave sends out of order (a slow
// earlier snapshot landing AFTER a later one, leaving the client's last
// observed frame stale). Publishes arriving while a flush is in flight
// mark `pending` and rearm the debounce timer once the flush completes.
const inFlight = new Set<StateResource>();
const pending = new Set<StateResource>();
let disposed = false;
const flush = async (resource: StateResource): Promise<void> => {
if (disposed) {
return;
function resourceStream(resource: StateResource) {
let timer: ReturnType<typeof setTimeout> | null = null;
let task: Promise<void> | null = null;
let pending = false;
function clearTimer() {
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
inFlight.add(resource);
try {
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;
function flush(): Promise<void> {
if (disposed) {
return Promise.resolve();
}
if (task) {
return task;
}
clearTimer();
task = Promise.resolve()
.then(async () => {
if (disposed) {
return;
}
const data = await opts.snapshot(resource);
if (!disposed) {
opts.send({ resource, data });
}
})
.catch((error) => {
log.warn('state stream %s failed: %s', resource, errorMessage(error));
})
.finally(() => {
task = null;
if (pending) {
pending = false;
schedule();
}
});
return task;
}
function schedule(): void {
if (disposed) {
return;
}
try {
opts.send({ resource, data });
} catch {
// Downstream consumer (e.g. closed SSE controller) — same isolation
// contract as snapshot failures.
if (task) {
pending = true;
return;
}
} finally {
inFlight.delete(resource);
// If a publish arrived during the in-flight window, schedule one
// follow-up flush. Re-uses the debounce so a sustained publish
// stream produces at most one frame per (debounceMs + flushLatency),
// not back-to-back frames.
if (!disposed && pending.has(resource)) {
pending.delete(resource);
schedule(resource);
}
clearTimer();
timer = setTimeout(() => void flush(), debounceMs);
}
return { flush, schedule, clearTimer };
}
const streams = {
processes: resourceStream('processes'),
'qq-list': resourceStream('qq-list'),
connections: resourceStream('connections'),
};
const schedule = (resource: StateResource): void => {
if (disposed) {
return;
}
if (inFlight.has(resource)) {
// Defer to the post-flush re-arm; no new timer until the in-flight
// send completes. This is the load-bearing invariant for ordering.
pending.add(resource);
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);
const unsubscribe = opts.bus.subscribe((resource) => streams[resource].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. Each
// call goes through the single-flight gate so a concurrent bus
// publish during this initial fan-out coalesces correctly.
await Promise.all(ALL_RESOURCES.map((r) => flush(r)));
await Promise.all(ALL_RESOURCES.map((resource) => streams[resource].flush()));
},
dispose(): void {
if (disposed) {
return;
}
disposed = true;
unsubscribe();
for (const t of timers.values()) {
clearTimeout(t);
}
timers.clear();
pending.clear();
ALL_RESOURCES.forEach((resource) => streams[resource].clearTimer());
},
};
}
+10 -24
View File
@@ -1,45 +1,31 @@
import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
import type { BridgeSessionSource } from '../bridge/bridge-interface';
export interface StateWiring {
/** The bus the SSE handler subscribes to. */
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Replace the bridge subscription for account and connection invalidations. */
bindBridgeManager(bm: BridgeManager): void;
/** Unsubscribe and stop publishing. */
onSessionsChanged(): void;
dispose(): void;
}
export function createStateWiring(): StateWiring {
export function createStateWiring(bridgeManager: BridgeSessionSource): StateWiring {
const bus = new StateBus();
let subscriptions: (() => void)[] | null = [];
const publishAccount = (): void => {
// Publish the account list before its adapters are enumerated.
const publishAccountChange = (): void => {
bus.publish('qq-list');
bus.publish('connections');
};
const unsubscribe = bridgeManager.subscribeSessions({
started: publishAccountChange,
closed: publishAccountChange,
});
return {
bus,
onSessionsChanged: () => bus.publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
if (!subscriptions) {
return;
}
subscriptions.forEach((unsubscribe) => unsubscribe());
subscriptions = [
bm.addSessionStartedListener(publishAccount),
bm.addSessionClosedListener(publishAccount),
];
},
dispose(): void {
subscriptions?.forEach((unsubscribe) => unsubscribe());
subscriptions = null;
bus.dispose();
unsubscribe();
},
};
}
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
import fs from 'node:fs';
import path from 'node:path';
import type { LogCleanupResult, LogStorageStatus } from '@snowluma/common/log-file-transport';
@@ -377,10 +378,6 @@ function validateAccountStorageCategory(value: string): AccountStorageCategory {
throw new StorageManagementInputError(`unsupported account storage category: ${value}`);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function redactFilesystemPath(message: string, filePath: string, label: string): string {
const absolute = path.resolve(filePath);
return message.split(absolute).join(label).split(filePath).join(label);
+3 -6
View File
@@ -1,3 +1,4 @@
import { errorMessage } from '@snowluma/common/errors';
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
// helpers: validate a pasted pair (save path) and resolve the on-disk pair
@@ -25,10 +26,6 @@ export interface RequiredTlsContext {
key: Buffer;
}
function errMsg(e: unknown): string {
return e instanceof Error ? e.message : String(e);
}
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
if (!cert || !cert.toString().trim()) {
@@ -43,7 +40,7 @@ export function validateTlsPair(cert: string | Buffer, key: string | Buffer): Tl
tls.createSecureContext({ cert, key });
return { ok: true };
} catch (e) {
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
return { ok: false, reason: `invalid cert/key: ${errorMessage(e)}` };
}
}
@@ -63,7 +60,7 @@ export function resolveTlsContext(configDir: string): TlsResolution {
cert = fs.readFileSync(certPath);
key = fs.readFileSync(keyPath);
} catch (e) {
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
return { ok: false, reason: `failed to read cert/key: ${errorMessage(e)}` };
}
const valid = validateTlsPair(cert, key);