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

+1 -1
View File
@@ -318,7 +318,7 @@ export class ExtrasApi {
),
);
}, receiptTimeoutMs);
timeout.unref?.();
timeout.unref();
}),
]));
@@ -17,3 +17,12 @@ export interface BridgeInterface extends BridgeContext {
* QQ has not emitted its cache notification since SnowLuma attached. */
getOnlineClients(): readonly Readonly<OnlineDeviceInfo>[] | null;
}
export interface BridgeSessionListener {
started?(uin: string, bridge: BridgeInterface): void;
closed?(uin: string, bridge: BridgeInterface, pid: number): void;
}
export interface BridgeSessionSource {
subscribeSessions(listener: BridgeSessionListener): () => void;
}
+47 -70
View File
@@ -4,31 +4,28 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { Bridge } from './bridge';
export type SessionStartedCallback = (uin: string, bridge: Bridge) => void;
export type SessionClosedCallback = (uin: string, bridge: Bridge, pid: number) => void;
interface QQSession {
bridge: Bridge;
}
import type { BridgeSessionListener, BridgeSessionSource } from './bridge-interface';
const log = createLogger('Bridge');
const packetLog = createLogger('Bridge.Packet');
const runtimeLog = createLogger('Bridge.Runtime');
export class BridgeManager {
private sessions_ = new Map<string, QQSession>();
private pidToUin_ = new Map<number, string>();
export class BridgeManager implements BridgeSessionSource {
private readonly bridges = new Map<string, Bridge>();
private readonly pidToUin_ = new Map<number, string>();
private readonly closingSessions_ = new Map<string, Promise<void>>();
private readonly closeErrors_: unknown[] = [];
private readonly sessionSubscriptions = new Set<{ listener: BridgeSessionListener }>();
/** Hook callbacks remain synchronous; shutdown awaits every detached account. */
async dispose(): Promise<void> {
for (const [uin, session] of this.sessions_) {
this.closeSession(uin, session.bridge);
this.sessionSubscriptions.clear();
for (const [uin, session] of this.bridges) {
this.closeSession(uin, session);
}
this.sessions_.clear();
this.bridges.clear();
this.pidToUin_.clear();
await Promise.allSettled(this.closingSessions_.values());
@@ -58,33 +55,21 @@ export class BridgeManager {
);
}
private readonly sessionStartedListeners_ = new Set<SessionStartedCallback>();
private readonly sessionClosedListeners_ = new Set<SessionClosedCallback>();
/** Each subscription has an independent, idempotent unsubscribe handle. */
addSessionStartedListener(cb: SessionStartedCallback): () => void {
const listener: SessionStartedCallback = (...args) => cb(...args);
this.sessionStartedListeners_.add(listener);
/** Listener changes take effect on the next event. Close observers run before
* Bridge disposal, so the final process and account identity remain readable. */
subscribeSessions(listener: BridgeSessionListener): () => void {
const subscription = { listener };
this.sessionSubscriptions.add(subscription);
return () => {
this.sessionStartedListeners_.delete(listener);
};
}
/** The close edge includes the final PID and bridge before disposal. */
addSessionClosedListener(cb: SessionClosedCallback): () => void {
const listener: SessionClosedCallback = (...args) => cb(...args);
this.sessionClosedListeners_.add(listener);
return () => {
this.sessionClosedListeners_.delete(listener);
this.sessionSubscriptions.delete(subscription);
};
}
private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of [...this.sessionStartedListeners_]) {
for (const { listener } of [...this.sessionSubscriptions]) {
try {
cb(uin, bridge);
listener.started?.(uin, bridge);
} catch (err) {
log.warn(
'session-started listener threw: %s',
@@ -95,9 +80,9 @@ export class BridgeManager {
}
private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
for (const cb of [...this.sessionClosedListeners_]) {
for (const { listener } of [...this.sessionSubscriptions]) {
try {
cb(uin, bridge, pid);
listener.closed?.(uin, bridge, pid);
} catch (err) {
log.warn(
'session-closed listener threw: %s',
@@ -120,7 +105,7 @@ export class BridgeManager {
try {
const closed = this.detachPidFromSession(pid, uin);
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
const activePid = this.bridges.get(uin)?.activePid ?? null;
if (closed) {
runtimeLog.trace(
@@ -160,15 +145,15 @@ export class BridgeManager {
throw new Error(message);
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session || !session.bridge.hasPid(pid)) {
if (!session || !session.hasPid(pid)) {
const message = `BridgeManager invariant violated: receive health PID=${pid} is not owned by UIN=${uin}`;
log.error(message);
throw new Error(message);
}
session.bridge.setPidReceiveHealthy(pid, healthy);
session.setPidReceiveHealthy(pid, healthy);
}
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
@@ -196,14 +181,14 @@ export class BridgeManager {
uin,
previousUin,
);
const previousSession = this.sessions_.get(previousUin);
const previousSession = this.bridges.get(previousUin);
runtimeLog.trace(
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
pid,
uin,
previousSession ? 'previous_session_retained' : 'previous_session_closed',
previousUin,
previousSession?.bridge.activePid ?? null,
previousSession?.activePid ?? null,
);
}
@@ -214,7 +199,7 @@ export class BridgeManager {
uin,
);
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
this.fireSessionStarted(uin, session);
}
runtimeLog.trace(
@@ -223,7 +208,7 @@ export class BridgeManager {
uin,
previousUin && previousUin !== uin ? 'rebound' : 'bound',
created,
session.bridge.activePid,
session.activePid,
Date.now() - startedAt,
);
} catch (error) {
@@ -284,13 +269,13 @@ export class BridgeManager {
// Notify session started on first real packet
if (created) {
log.debug('session started: UIN=%s', uin);
this.fireSessionStarted(uin, session.bridge);
this.fireSessionStarted(uin, session);
}
// Dispatch packet to bridge. The pipeline preserves synchronous parsing and
// dispatch; its promise only marks completion of any async enrichment.
handedToPipeline = true;
completion = session.bridge.onPacket(pkt);
completion = session.onPacket(pkt);
} catch (error) {
this.tracePacketFailure(
pkt,
@@ -336,7 +321,7 @@ export class BridgeManager {
uin: string,
packetClient: PacketSender,
source: 'login' | 'packet',
): { session: QQSession; created: boolean } {
): { session: Bridge; created: boolean } {
const previousUin = this.pidToUin_.get(pid);
if (previousUin && previousUin !== uin) {
@@ -351,7 +336,7 @@ export class BridgeManager {
}
const result = this.ensureSession(uin);
result.session.bridge.bindPid(pid, packetClient);
result.session.bindPid(pid, packetClient);
this.pidToUin_.set(pid, uin);
return result;
}
@@ -363,7 +348,7 @@ export class BridgeManager {
return null;
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -371,7 +356,7 @@ export class BridgeManager {
throw new Error(message);
}
const packetClient = session.bridge.packetClientForPid(pid);
const packetClient = session.packetClientForPid(pid);
if (packetClient) {
return packetClient;
@@ -391,7 +376,7 @@ export class BridgeManager {
throw new Error(message);
}
const session = this.sessions_.get(uin);
const session = this.bridges.get(uin);
if (!session) {
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
@@ -399,7 +384,7 @@ export class BridgeManager {
throw new Error(message);
}
if (!session.bridge.hasPid(pid)) {
if (!session.hasPid(pid)) {
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
log.error(message);
throw new Error(message);
@@ -408,22 +393,22 @@ export class BridgeManager {
// Validation is complete. Mutate both sides only after the ownership
// invariant is known to hold, so a fail-fast error preserves the evidence.
this.pidToUin_.delete(pid);
session.bridge.detachPid(pid);
session.detachPid(pid);
if (!session.bridge.empty) {
if (!session.empty) {
return false;
}
this.sessions_.delete(uin);
this.bridges.delete(uin);
log.debug('session closed: UIN=%s', uin);
// Fire before dispose() so listeners can still read bridge.identity.
this.fireSessionClosed(uin, session.bridge, pid);
this.closeSession(uin, session.bridge);
this.fireSessionClosed(uin, session, pid);
this.closeSession(uin, session);
return true;
}
private ensureSession(uin: string): { session: QQSession; created: boolean } {
let session = this.sessions_.get(uin);
private ensureSession(uin: string): { session: Bridge; created: boolean } {
const session = this.bridges.get(uin);
if (session) {
return { session, created: false };
@@ -432,20 +417,12 @@ export class BridgeManager {
const bridge = new Bridge(
IdentityService.openForUin(uin, 'data', this.closingSessions_.get(uin)),
);
session = { bridge };
this.sessions_.set(uin, session);
this.bridges.set(uin, bridge);
// Each downstream consumer (e.g. OneBotInstance) subscribes to
// `bridge.events` directly via the per-kind bus — there is no longer a
// generic firehose to wire here.
return { session, created: true };
return { session: bridge, created: true };
}
getSession(uin: string): QQSession | null {
return this.sessions_.get(uin) ?? null;
}
get sessions(): Map<string, { bridge: Bridge }> {
return this.sessions_;
getBridge(uin: string): Bridge | null {
return this.bridges.get(uin) ?? null;
}
}
+2 -4
View File
@@ -77,12 +77,13 @@ async function main() {
const bridgeManager = new BridgeManager();
bindSystemFaceCatalog(bridgeManager);
const oneBotManager = new OneBotManager();
oneBotManager.bind(bridgeManager);
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
// WebUI state-push wiring: HookManager + BridgeManager edges publish
// `processes` / `qq-list` / `connections` invalidations into a bus the
// /api/state/stream SSE handler subscribes to (no REST polling required).
const stateWiring = createStateWiring();
const stateWiring = createStateWiring(bridgeManager);
const hookManager = new HookManager({
bridgeManager,
autoLoadOnDiscovery,
@@ -93,9 +94,6 @@ async function main() {
log.info('hook auto-load enabled: every discovered QQ process will be injected');
}
oneBotManager.bind(bridgeManager);
stateWiring.bindBridgeManager(bridgeManager);
// Global notification subsystem (account up/down → webhook). Bound AFTER
// OneBotManager so the nickname fallback is already populated when it observes.
// Lifecycle events identify their PID; an older process with the same UIN
+1 -1
View File
@@ -337,7 +337,7 @@ export function startNativeStageSync(options: StageSyncOptions): { stop: () => v
tick();
const timer = setInterval(tick, options.intervalMs ?? 500);
timer.unref?.();
timer.unref();
return {
stop() {
stopped = true;
+27 -18
View File
@@ -9,10 +9,11 @@
// SMTP send, the clock) are injected so the class is fully unit-testable; the
// real wiring lives in `createNotificationManager()` at the bottom.
import { positiveIntEnv } from '@snowluma/common/env';
import { errorMessage } from '@snowluma/common/errors';
import type { HookProcessInfo } from '@snowluma/bridge/types';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from '@snowluma/onebot/config';
import type { BridgeManager } from '../bridge/manager';
import type { BridgeSessionSource } from '../bridge/bridge-interface';
import {
isEmailChannel,
loadNotificationsConfig,
@@ -93,10 +94,6 @@ interface AccountNotificationContext {
pid: number | null;
}
function errMsg(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/**
* Pure: the channels a UIN should be notified through — globally enabled AND
* opted into by the UIN — preserving config order. Exported for unit tests.
@@ -118,6 +115,7 @@ export class NotificationManager {
private readonly deliveries = new Map<string, Promise<void>>();
private readonly historyLimit: number;
private disposed = false;
private unsubscribeSessions: (() => void) | null = null;
constructor(deps: NotificationManagerDeps) {
this.deps = deps;
@@ -126,13 +124,17 @@ export class NotificationManager {
/** Subscribe to the global session online/offline edges. Register AFTER
* OneBotManager so the nickname fallback is already populated. */
bind(bridgeManager: BridgeManager): void {
bridgeManager.addSessionStartedListener((uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
);
bridgeManager.addSessionClosedListener((uin, bridge, pid) =>
this.handleOffline(uin, bridge.identity.nickname, pid),
);
bind(bridgeManager: BridgeSessionSource): void {
if (this.disposed) {
return;
}
this.unsubscribeSessions?.();
this.unsubscribeSessions = bridgeManager.subscribeSessions({
started: (uin, bridge) =>
this.handleOnline(uin, bridge.identity.nickname, bridge.activePid),
closed: (uin, bridge, pid) => this.handleOffline(uin, bridge.identity.nickname, pid),
});
}
handleOnline(uin: string, nickname?: string, pid: number | null = null): void {
@@ -158,7 +160,7 @@ export class NotificationManager {
try {
debounceSeconds = this.deps.loadConfig().debounceSeconds;
} catch (err) {
log.warn('offline(%s) skipped — config load failed: %s', uin, errMsg(err));
log.warn('offline(%s) skipped — config load failed: %s', uin, errorMessage(err));
return;
}
@@ -234,7 +236,12 @@ export class NotificationManager {
const cfg = this.deps.loadConfig();
channels = selectChannels(cfg.channels, this.deps.loadChannelIds(uin));
} catch (err) {
log.warn('notify(%s, %s) skipped — config load failed: %s', uin, event, errMsg(err));
log.warn(
'notify(%s, %s) skipped — config load failed: %s',
uin,
event,
errorMessage(err),
);
return;
}
@@ -247,7 +254,7 @@ export class NotificationManager {
try {
facts = await this.deps.resolveProcess?.(uin, account.pid);
} catch (err) {
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errMsg(err));
log.warn('resolveProcess(%s, %s) failed: %s', uin, account.pid, errorMessage(err));
}
const vars: Record<string, string> = {
@@ -318,7 +325,7 @@ export class NotificationManager {
return await this.deps.post(ch.url, renderTemplate(ch.bodyTemplate, vars), ch.headers);
} catch (err) {
return { ok: false, error: errMsg(err) };
return { ok: false, error: errorMessage(err) };
}
}
@@ -332,7 +339,7 @@ export class NotificationManager {
try {
channel = this.deps.loadConfig().channels.find((c) => c.id === channelId);
} catch (err) {
return { ok: false, found: false, error: errMsg(err) };
return { ok: false, found: false, error: errorMessage(err) };
}
if (!channel) {
@@ -371,6 +378,8 @@ export class NotificationManager {
}
this.disposed = true;
this.unsubscribeSessions?.();
this.unsubscribeSessions = null;
for (const timer of this.timers.values()) {
clearTimeout(timer);
@@ -399,7 +408,7 @@ export function createDefaultPost(
error: res.ok ? undefined : `HTTP ${res.status}`,
};
} catch (err) {
return { ok: false, error: errMsg(err) };
return { ok: false, error: errorMessage(err) };
}
};
}
+12 -10
View File
@@ -6,7 +6,7 @@ import {
type SysFaceCatalogStorage,
} from '@snowluma/protocol/sys-face-store';
import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage';
import type { BridgeManager } from './bridge/manager';
import type { BridgeSessionSource } from './bridge/bridge-interface';
const log = createLogger('SysFace');
@@ -19,7 +19,7 @@ export interface SystemFaceCatalogBindingOptions {
/** Attach the shared system-face catalog to Bridge login edges. The first
* account restores + refreshes it; later accounts reuse the same result. */
export function bindSystemFaceCatalog(
manager: BridgeManager,
manager: BridgeSessionSource,
options: SystemFaceCatalogBindingOptions = {},
): void {
const store = options.store ?? sysFaceStore;
@@ -30,13 +30,15 @@ export function bindSystemFaceCatalog(
);
store.configureStorage(storage);
manager.addSessionStartedListener((uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
manager.subscribeSessions({
started: (uin, bridge) => {
void store.prewarm(bridge).catch((error) => {
log.error(
'system face catalog login prewarm failed: uin=%s error=%s',
uin,
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
});
},
});
}
@@ -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);