refactor: clarify async state and subscription ownership

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:42:54 +08:00
1 parent f6ca9d5f65
commit c54aeffc77
20 files changed
+698 -316

No files matched your search

+3 -4
View File
@@ -4,7 +4,6 @@ import {
HookPipeRequestError,
PIPE_STATUS_CONNECTION_UNAVAILABLE,
QqHookClient,
type QqHookSendReply,
} from './qq-hook-client';
export type OutboundHealthListener = (healthy: boolean) => void;
@@ -33,16 +32,16 @@ export class HookPacketClient implements PacketSender {
}
try {
const reply = (await this.client.send(serviceCmd, body, {
const reply = await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
})) as QqHookSendReply;
});
this.setOutboundHealthy(true);
return {
success: reply.error === 0,
gotResponse: true,
errorCode: reply.error,
errorMessage: reply.message || '',
errorMessage: reply.message,
responseData: reply.body,
};
} catch (error) {
+35 -15
View File
@@ -560,7 +560,7 @@ export class QqHookClient extends EventEmitter {
private controlWriteChain: Promise<unknown> = Promise.resolve();
private closed = false;
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
private loginWaiters: Deferred<QqHookLoginState>[] = [];
private readonly loginWaiters = new Set<Deferred<QqHookLoginState>>();
constructor(
pid: number,
@@ -612,13 +612,22 @@ export class QqHookClient extends EventEmitter {
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
await this.connect();
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (this.loginState.loggedIn) {
return this.getLoginState();
}
const deferred = createDeferred<QqHookLoginState>();
this.loginWaiters.push(deferred);
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
this.loginWaiters.add(deferred);
try {
return await withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
} finally {
this.loginWaiters.delete(deferred);
}
}
static controlPipeName(pid: number, runtimeDir = resolveHookRuntimeDir(pid)): string {
@@ -735,6 +744,21 @@ export class QqHookClient extends EventEmitter {
return { control, recv: recvInfo };
}
send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options?: QqHookSendOptions & { wantReply?: true },
): Promise<QqHookSendReply>;
send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options: QqHookSendOptions & { wantReply: false },
): Promise<{ requestId: number }>;
send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
options?: QqHookSendOptions,
): Promise<QqHookSendReply | { requestId: number }>;
async send(
cmd: string,
body: Buffer | Uint8Array | string | null | undefined,
@@ -849,9 +873,7 @@ export class QqHookClient extends EventEmitter {
body: Buffer | Uint8Array | string | null | undefined,
options: Omit<QqHookSendOptions, 'wantReply'> = {},
): Promise<{ requestId: number }> {
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{
requestId: number;
}>;
return this.send(cmd, body, { ...options, wantReply: false });
}
async sendAndWait(
@@ -859,7 +881,7 @@ export class QqHookClient extends EventEmitter {
body: Buffer | Uint8Array | string | null | undefined,
options: Omit<QqHookSendOptions, 'wantReply'> = {},
): Promise<QqHookSendReply> {
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
return this.send(cmd, body, { ...options, wantReply: true });
}
async sendMany(
@@ -971,12 +993,11 @@ export class QqHookClient extends EventEmitter {
}
private rejectLoginWaiters(error: Error): void {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) {
for (const waiter of this.loginWaiters) {
waiter.reject(error);
}
this.loginWaiters.clear();
}
private rejectControlPending(error: Error): void {
@@ -1266,12 +1287,11 @@ export class QqHookClient extends EventEmitter {
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) {
for (const waiter of this.loginWaiters) {
waiter.resolve({ ...next });
}
this.loginWaiters.clear();
}
});
}
@@ -133,6 +133,20 @@ afterEach(async () => {
tmpDir = null;
});
describe('QqHookClient login wait lifecycle', () => {
it('rejects when closed while resuming a completed connection', async () => {
const client = new QqHookClient(12345);
vi.spyOn(client, 'connect').mockResolvedValue({
pid: 12345,
pipeName: 'test',
recvPipe: false,
});
const waiting = client.waitForLogin();
client.close();
await expect(waiting).rejects.toThrow('closed');
});
});
describe('listLiveLinuxPipePids', () => {
it('ignores stale-looking control socket names when the probe rejects them', async () => {
const runtimeDir = await makeRuntimeDir();
+13 -23
View File
@@ -1,19 +1,4 @@
/**
* Single-flight + TTL memoization.
*
* Concentrates the "don't refetch what's fresh, and don't stampede the same
* key with concurrent loads" pattern that was hand-rolled (slightly
* differently each time) across the codebase — e.g. `ContactsApi`'s group
* member-list cache and the WebUI update-check. Each copy re-implemented the
* same fiddly trio: a TTL freshness check, an in-flight promise map to
* de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any
* of the three subtly wrong (forgetting the `finally`, caching an error,
* racing the timestamp) is a real hazard — so it lives in one place.
*
* The underlying concern is Tencent risk-control: a busy OneBot client can
* fan out one uncached OIDB fetch per inbound message, and sustained bursts
* trip a ban. TTL + single-flight collapse that fan-out.
*/
/** TTL caching and request deduplication to limit repeated upstream requests. */
export interface SingleFlightCacheOptions<K, V> {
/** Freshness window in ms. A cached entry older than this is reloaded. */
@@ -70,30 +55,35 @@ export class SingleFlightCache<K, V> {
return existing;
}
const task = (async () => {
const load = async (): Promise<V> => {
const value = await this.load(key);
if (this.shouldCache(value)) {
if (this.inflight.get(key) === task && this.shouldCache(value)) {
this.fresh.set(key, { at: this.now(), value });
}
return value;
})().finally(() => {
// Run after registration even when load throws synchronously.
this.inflight.delete(key);
};
const task = load().finally(() => {
if (this.inflight.get(key) === task) {
this.inflight.delete(key);
}
});
this.inflight.set(key, task);
return task;
}
/** Drop a cached entry. Does not abort an in-flight load. */
/** Detach the entry and its pending load; existing callers still settle. */
invalidate(key: K): void {
this.fresh.delete(key);
this.inflight.delete(key);
}
/** Drop all cached entries. Does not abort in-flight loads. */
/** Detach all entries and pending loads without aborting existing callers. */
clear(): void {
this.fresh.clear();
this.inflight.clear();
}
}
@@ -13,6 +13,46 @@ function deferred<T>() {
}
describe('SingleFlightCache', () => {
it.each(['invalidate', 'clear'] as const)(
'%s detaches pending loads from the cache',
async (operation) => {
const old = deferred<string>();
const current = deferred<string>();
const load = vi
.fn()
.mockReturnValueOnce(old.promise)
.mockReturnValueOnce(current.promise);
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const first = cache.get('key');
cache[operation]('key');
const second = cache.get('key');
expect(load).toHaveBeenCalledTimes(2);
old.resolve('old');
await expect(first).resolves.toBe('old');
expect(cache.get('key')).toBe(second);
current.resolve('current');
await expect(second).resolves.toBe('current');
await expect(cache.get('key')).resolves.toBe('current');
expect(load).toHaveBeenCalledTimes(2);
},
);
it('does not let a late invalidated result overwrite a newer value', async () => {
const old = deferred<string>();
const load = vi.fn().mockReturnValueOnce(old.promise).mockResolvedValue('current');
const cache = createSingleFlightCache<string, string>({ ttlMs: 1000, load });
const first = cache.get('key');
cache.invalidate('key');
await expect(cache.get('key')).resolves.toBe('current');
old.resolve('old');
await first;
await expect(cache.get('key')).resolves.toBe('current');
});
it('caches within the TTL and reloads once expired', async () => {
let clock = 1000;
const load = vi.fn(async (k: string) => `${k}@${clock}`);
+21 -13
View File
@@ -58,23 +58,31 @@ export class BridgeManager {
);
}
private sessionStartedListeners_: SessionStartedCallback[] = [];
private sessionClosedListeners_: SessionClosedCallback[] = [];
private readonly sessionStartedListeners_ = new Set<SessionStartedCallback>();
private readonly sessionClosedListeners_ = new Set<SessionClosedCallback>();
/** Additive subscription: every observer (OneBotManager, NotificationManager,
* …) receives every session edge. (Was a single `set*Callback` setter —
* converted to N listeners so a second observer can't clobber the first.)
* The close edge carries the final detached PID and the bridge so observers
* can identify the process and read its nickname before disposal. */
addSessionStartedListener(cb: SessionStartedCallback): void {
this.sessionStartedListeners_.push(cb);
/** Each subscription has an independent, idempotent unsubscribe handle. */
addSessionStartedListener(cb: SessionStartedCallback): () => void {
const listener: SessionStartedCallback = (...args) => cb(...args);
this.sessionStartedListeners_.add(listener);
return () => {
this.sessionStartedListeners_.delete(listener);
};
}
addSessionClosedListener(cb: SessionClosedCallback): void {
this.sessionClosedListeners_.push(cb);
/** 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);
};
}
private fireSessionStarted(uin: string, bridge: Bridge): void {
for (const cb of this.sessionStartedListeners_) {
for (const cb of [...this.sessionStartedListeners_]) {
try {
cb(uin, bridge);
} catch (err) {
@@ -87,7 +95,7 @@ export class BridgeManager {
}
private fireSessionClosed(uin: string, bridge: Bridge, pid: number): void {
for (const cb of this.sessionClosedListeners_) {
for (const cb of [...this.sessionClosedListeners_]) {
try {
cb(uin, bridge, pid);
} catch (err) {
+9 -25
View File
@@ -1,21 +1,6 @@
/**
* StateBus — pure pub/sub for WebUI state-resource invalidations.
*
* Three resources are tracked: `processes`, `qq-list`, `connections`. A
* publisher (HookSession status change, BridgeManager session start/close,
* the connection-status diff loop) calls `publish(resource)` to signal "the
* snapshot for THIS resource is stale; whoever cares should re-read". The
* `/api/state/stream` SSE handler subscribes, debounces, and pushes fresh
* snapshots to connected WebUI clients.
*
* Intentionally pure pub/sub (no debounce, no snapshot caching): debounce
* and snapshot reads live with the subscriber so different consumers can
* coalesce on different cadences. Snapshot semantics on fan-out: the
* subscriber set is FROZEN at the start of each publish, so a listener
* that subscribes during the fan-out only sees the FOLLOWING publish, and
* a listener that unsubscribes mid-fan-out does not prevent its peers
* from completing.
*/
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('WebUI.State');
export type StateResource = 'processes' | 'qq-list' | 'connections';
@@ -54,18 +39,17 @@ export class StateBus {
return;
}
// Snapshot the current subscribers — any subscribe()/unsubscribe()
// called by a listener during the fan-out takes effect only for the
// NEXT publish, not this one.
const snapshot = [...this.listeners];
for (const fn of snapshot) {
try {
fn(resource);
} catch {
// Subscriber-internal failure is its own problem. The bus's job
// is to keep delivery moving — surfacing an error here would
// partially abort the fan-out and create skip-the-listener bugs.
} catch (error) {
log.warn(
'state listener failed: resource=%s error=%s',
resource,
error instanceof Error ? error.message : String(error),
);
}
}
}
+18 -53
View File
@@ -1,24 +1,3 @@
/**
* State-wiring — couples the publisher edges (HookManager session events,
* BridgeManager session-started / session-closed) to a fresh StateBus so the
* `/api/state/stream` SSE handler can push snapshot invalidations to the
* WebUI without REST polling.
*
* Decoupling rationale:
* - HookManager owns the per-process state-machine; it knows when a
* session's `listProcesses()` view changes. We feed it `onSessionsChanged`
* (callable from outside the bridge package) so this file is the ONLY
* place that imports both the bus and HookManager's dep shape.
* - BridgeManager fires `session-started` / `session-closed` listeners on
* account edges (the OneBot instance list mutates around these). We add
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
* attached; further session edges publish nothing. Process shutdown disposes
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
*/
import { StateBus } from './state-bus';
import type { BridgeManager } from '../bridge/manager';
@@ -27,53 +6,39 @@ export interface StateWiring {
readonly bus: StateBus;
/** Pass as the HookManager `onSessionsChanged` dep — publishes 'processes'. */
onSessionsChanged: () => void;
/** Hook into a BridgeManager so its session edges publish 'qq-list' and
* 'connections'. Can be called at most once per wiring (subsequent calls
* add duplicate listeners). */
/** Replace the bridge subscription for account and connection invalidations. */
bindBridgeManager(bm: BridgeManager): void;
/** Drop every listener + neuter the bus so further publishes do nothing. */
/** Unsubscribe and stop publishing. */
dispose(): void;
}
export function createStateWiring(): StateWiring {
const bus = new StateBus();
let disposed = false;
let subscriptions: (() => void)[] | null = [];
const publish = (resource: Parameters<StateBus['publish']>[0]): void => {
if (disposed) {
return;
}
bus.publish(resource);
const publishAccount = (): void => {
// Publish the account list before its adapters are enumerated.
bus.publish('qq-list');
bus.publish('connections');
};
return {
bus,
onSessionsChanged: () => publish('processes'),
onSessionsChanged: () => bus.publish('processes'),
bindBridgeManager(bm: BridgeManager): void {
// Account appeared: the qq-list response gains an entry and the
// connections response gains the new account's adapter row. Two
// distinct resource invalidations, in source-of-truth order
// (account exists → only then can adapters be enumerated for it).
bm.addSessionStartedListener(() => {
publish('qq-list');
publish('connections');
});
// Account disappeared: same two resources shrink, same order so a
// racy WebUI receiving both events independently sees the qq-list
// shrink before it tries to render connections for a uin that's
// about to vanish.
bm.addSessionClosedListener(() => {
publish('qq-list');
publish('connections');
});
},
dispose(): void {
if (disposed) {
if (!subscriptions) {
return;
}
disposed = true;
subscriptions.forEach((unsubscribe) => unsubscribe());
subscriptions = [
bm.addSessionStartedListener(publishAccount),
bm.addSessionClosedListener(publishAccount),
];
},
dispose(): void {
subscriptions?.forEach((unsubscribe) => unsubscribe());
subscriptions = null;
bus.dispose();
},
};
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeManager } from '../src/bridge/manager';
describe('BridgeManager session subscriptions', () => {
it('unsubscribes repeated registrations independently', async () => {
const manager = new BridgeManager();
const started = vi.fn();
const closed = vi.fn();
const offStarted = manager.addSessionStartedListener(started);
manager.addSessionStartedListener(started);
const offClosed = manager.addSessionClosedListener(closed);
manager.addSessionClosedListener(closed);
offStarted();
offStarted();
offClosed();
offClosed();
manager.onHookLogin(4001, '12345', {} as never);
manager.onPidDisconnected(4001);
expect(started).toHaveBeenCalledTimes(1);
expect(closed).toHaveBeenCalledTimes(1);
await manager.dispose();
});
it('keeps the current fan-out stable when a listener unsubscribes a peer', async () => {
const manager = new BridgeManager();
const peer = vi.fn();
manager.addSessionStartedListener(() => offPeer());
const offPeer = manager.addSessionStartedListener(peer);
manager.onHookLogin(4002, '12345', {} as never);
manager.onHookLogin(4003, '23456', {} as never);
expect(peer).toHaveBeenCalledTimes(1);
await manager.dispose();
});
});
@@ -4,6 +4,42 @@ import { createStateWiring } from '../src/webui/state-wiring';
import { BridgeManager } from '../src/bridge/manager';
describe('createStateWiring', () => {
it('replaces its bridge subscription without retaining the old manager', async () => {
const wiring = createStateWiring();
const old = new BridgeManager();
const current = new BridgeManager();
const listener = vi.fn();
wiring.bus.subscribe(listener);
wiring.bindBridgeManager(old);
wiring.bindBridgeManager(current);
wiring.bindBridgeManager(current);
old.onHookLogin(4100, '12345', {} as never);
expect(listener).not.toHaveBeenCalled();
current.onHookLogin(4200, '23456', {} as never);
expect(listener.mock.calls).toEqual([['qq-list'], ['connections']]);
wiring.dispose();
await old.dispose();
await current.dispose();
});
it('unsubscribes on disposal and does not bind again', async () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
const subscribe = vi.spyOn(bm, 'addSessionStartedListener');
const publish = vi.spyOn(wiring.bus, 'publish');
wiring.bindBridgeManager(bm);
wiring.dispose();
wiring.dispose();
wiring.bindBridgeManager(bm);
bm.onHookLogin(4300, '34567', {} as never);
expect(publish).not.toHaveBeenCalled();
expect(subscribe).toHaveBeenCalledTimes(1);
await bm.dispose();
});
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
const wiring = createStateWiring();
expect(wiring.bus).toBeInstanceOf(StateBus);
+2
View File
@@ -2,6 +2,8 @@
## Unreleased
- Isolate WebSocket connection lifetimes and release request timers and abort listeners on every outcome.
- Reject duplicate in-flight WebSocket echoes instead of overwriting the original request.
- Add `getGroupShareLink()` and typed `get_group_share_link` support for group invitation links.
- Breaking: require Node.js 24 or newer.
- Add `CustomReplySegment` and `message.customReply()` for inline quote previews inside merged-forward nodes.
+2
View File
@@ -212,6 +212,8 @@ await bot.raw('send_group_forward_msg', {
每次请求都支持覆盖 `echo`、超时和 `AbortSignal`:
WebSocket 并发请求必须使用不同的 `echo`;重复值会被拒绝。省略时由 SDK 自动生成。
```ts
const controller = new AbortController();
+122 -95
View File
@@ -59,7 +59,6 @@ import type {
WsRole,
} from '../types/index';
import type {
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
@@ -75,6 +74,17 @@ export type {
WebSocketConstructor,
} from './websocket-types';
interface SocketConnection {
socket: WebSocketLike;
opened: Promise<void>;
dispose(error: Error): void;
}
interface PendingRequest {
resolve(response: ApiResponse): void;
reject(error: Error): void;
}
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
readonly url: string;
@@ -88,8 +98,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly middlewares: EventMiddleware[] = [];
private socket: WebSocketLike | null = null;
private connectPromise: Promise<void> | null = null;
private connection: SocketConnection | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private closedByUser = false;
@@ -112,7 +121,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
return this.connection?.socket.readyState === WEBSOCKET_OPEN;
}
/** Subscribes to low-level client events. Returns an unsubscribe function. */
@@ -249,43 +258,63 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
/** Connects to SnowLuma's OneBot WebSocket endpoint. */
async connect(): Promise<void> {
if (this.isConnected) {
return;
}
if (this.connectPromise) {
return this.connectPromise;
if (this.connection) {
return this.connection.opened;
}
this.closedByUser = false;
this.connectPromise = new Promise((resolve, reject) => {
const url = appendAccessToken(this.url, this.accessToken);
const socket = new this.WebSocketCtor(url, this.protocols);
this.socket = socket;
const cleanup = [
addSocketListener(socket, 'open', () => {
cleanup.forEach((off) => off());
this.bindSocket(socket);
this.reconnectAttempts = 0;
this.connectPromise = null;
this.emitter.emit('open', undefined);
resolve();
}),
addSocketListener(socket, 'error', (error) => {
this.emitter.emit('error', unwrapEventPayload(error));
}),
addSocketListener(socket, 'close', (...args) => {
cleanup.forEach((off) => off());
this.connectPromise = null;
this.socket = null;
reject(new SnowLumaConnectionError('SnowLuma WebSocket closed before opening'));
this.handleClose(args);
}),
];
const socket = new this.WebSocketCtor(
appendAccessToken(this.url, this.accessToken),
this.protocols,
);
let resolveOpening!: () => void;
let rejectOpening!: (error: Error) => void;
const opened = new Promise<void>((resolve, reject) => {
resolveOpening = resolve;
rejectOpening = reject;
});
const listeners: (() => void)[] = [];
const connection: SocketConnection = {
socket,
opened,
dispose: (error) => {
listeners.forEach((off) => off());
rejectOpening(error);
},
};
this.connection = connection;
listeners.push(
addSocketListener(socket, 'open', () => {
if (this.connection !== connection) {
return;
}
return this.connectPromise;
this.reconnectAttempts = 0;
resolveOpening();
this.emitter.emit('open', undefined);
}),
addSocketListener(socket, 'message', (...args) => {
if (this.connection === connection) {
this.handleMessage(args);
}
}),
addSocketListener(socket, 'error', (error) => {
if (this.connection === connection) {
this.emitter.emit('error', unwrapEventPayload(error));
}
}),
addSocketListener(socket, 'close', (...args) => {
if (this.connection !== connection) {
return;
}
this.connection = null;
connection.dispose(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.handleClose(args);
}),
);
return opened;
}
/** Closes the socket and rejects all pending API requests. */
@@ -297,14 +326,19 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
this.reconnectTimer = null;
}
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket client closed'));
const error = new SnowLumaConnectionError('SnowLuma WebSocket client closed');
const connection = this.connection;
this.connection = null;
connection?.dispose(error);
this.rejectPending(error);
if (this.socket && this.socket.readyState !== WEBSOCKET_CLOSED) {
this.socket.close(code, reason);
if (connection && connection.socket.readyState !== WEBSOCKET_CLOSED) {
const off = addSocketListener(connection.socket, 'close', (...args) => {
off();
this.emitter.emit('close', closeInfo(args));
});
connection.socket.close(code, reason);
}
this.socket = null;
this.connectPromise = null;
}
/** Sends one OneBot action over WebSocket and returns the raw response envelope. */
@@ -321,7 +355,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
);
throwIfAborted(options?.signal);
const socket = this.socket;
const socket = this.connection?.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
@@ -331,26 +365,38 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
const key = echoKey(echo);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const promise = new Promise<ApiResponse>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let abortListener: (() => void) | undefined;
if (this.pending.has(key)) {
throw new SnowLumaConnectionError(
'A WebSocket request with this echo is already pending',
);
}
return new Promise<ApiResponse<ActionResult<TAction>>>((resolve, reject) => {
const cleanup = (): void => {
this.pending.delete(key);
if (timer) {
clearTimeout(timer);
}
if (abortListener) {
options?.signal?.removeEventListener('abort', abortListener);
}
options?.signal?.removeEventListener('abort', abortListener);
};
timer =
const pending: PendingRequest = {
resolve: (response) => {
cleanup();
resolve(response as ApiResponse<ActionResult<TAction>>);
},
reject: (error) => {
cleanup();
reject(error);
},
};
const timer =
timeoutMs > 0
? setTimeout(() => {
this.pending.delete(key);
cleanup();
reject(
pending.reject(
new SnowLumaTimeoutError(
`SnowLuma WebSocket request timed out after ${timeoutMs}ms`,
timeoutMs,
@@ -359,47 +405,33 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
}, timeoutMs)
: null;
abortListener = () => {
this.pending.delete(key);
cleanup();
reject(
const abortListener = () => {
pending.reject(
new SnowLumaAbortError('SnowLuma WebSocket request aborted', {
cause: options?.signal?.reason,
}),
);
};
this.pending.set(key, pending);
options?.signal?.addEventListener('abort', abortListener, { once: true });
this.pending.set(key, { resolve, reject, timer, cleanup });
try {
socket.send(
JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}),
);
} catch (error) {
pending.reject(
new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', {
cause: error,
}),
);
}
});
try {
socket.send(
JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}),
);
} catch (error) {
const pending = this.pending.get(key);
pending?.cleanup?.();
this.pending.delete(key);
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', {
cause: error,
});
}
return promise as Promise<ApiResponse<ActionResult<TAction>>>;
}
private bindSocket(socket: WebSocketLike): void {
addSocketListener(socket, 'message', (...args) => this.handleMessage(args));
addSocketListener(socket, 'error', (error) =>
this.emitter.emit('error', unwrapEventPayload(error)),
);
addSocketListener(socket, 'close', (...args) => this.handleClose(args));
}
private handleMessage(args: unknown[]): void {
@@ -425,21 +457,21 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
const pending = this.pending.get(key);
if (pending) {
this.pending.delete(key);
pending.cleanup?.();
let response: ApiResponse;
try {
const response = assertApiResponse(parsed);
pending.resolve(response);
this.emitter.emit('response', response);
response = assertApiResponse(parsed);
} catch (error) {
pending.reject(
new SnowLumaParseError('SnowLuma WebSocket response is invalid', {
cause: error,
}),
);
return;
}
pending.resolve(response);
this.emitter.emit('response', response);
return;
}
}
@@ -475,8 +507,6 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.socket = null;
this.connectPromise = null;
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.emitter.emit('close', info);
@@ -520,11 +550,8 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
private rejectPending(error: Error): void {
for (const pending of this.pending.values()) {
pending.cleanup?.();
pending.reject(error);
}
this.pending.clear();
}
}
@@ -53,10 +53,3 @@ export interface SnowLumaWebSocketEvents {
response: ApiResponse;
raw: unknown;
}
export interface PendingRequest {
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
}
+163 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaWebSocketClient,
@@ -75,6 +75,168 @@ const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
};
describe('SnowLumaWebSocketClient', () => {
afterEach(() => {
vi.useRealTimers();
});
it('rejects duplicate in-flight echoes without replacing the original request', async () => {
const client = new SnowLumaWebSocketClient({ webSocket: MockWebSocket });
const opening = client.connect();
const socket = MockWebSocket.instances.at(-1)!;
socket.open();
await opening;
const first = client.getStatus({ echo: 'same' });
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
await expect(client.getStatus({ echo: 'same' })).rejects.toThrow('already pending');
expect(socket.sent).toHaveLength(1);
socket.message(
JSON.stringify({ status: 'ok', retcode: 0, data: { online: true }, echo: 'same' }),
);
await expect(first).resolves.toEqual({ online: true });
client.close();
});
it.each(['response', 'abort', 'timeout', 'send failure', 'invalid response', 'close'] as const)(
'releases the timer and abort listener after %s',
async (outcome) => {
vi.useFakeTimers();
const client = new SnowLumaWebSocketClient({
webSocket: MockWebSocket,
requestTimeoutMs: 1000,
});
const opening = client.connect();
const socket = MockWebSocket.instances.at(-1)!;
socket.open();
await opening;
const controller = new AbortController();
const remove = vi.spyOn(controller.signal, 'removeEventListener');
if (outcome === 'send failure') {
vi.spyOn(socket, 'send').mockImplementation(() => {
throw new Error('send failed');
});
}
const request = client.getStatus({ echo: 'request', signal: controller.signal });
const settled = request.then(
() => 'resolved',
() => 'rejected',
);
await vi.advanceTimersByTimeAsync(0);
switch (outcome) {
case 'response':
socket.message(
JSON.stringify({ status: 'ok', retcode: 0, data: {}, echo: 'request' }),
);
break;
case 'invalid response':
socket.message(JSON.stringify({ echo: 'request' }));
break;
case 'abort':
controller.abort();
break;
case 'timeout':
await vi.advanceTimersByTimeAsync(1000);
break;
case 'close':
client.close();
break;
}
expect(await settled).toBe(outcome === 'response' ? 'resolved' : 'rejected');
expect(vi.getTimerCount()).toBe(0);
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function));
client.close();
},
);
it('reconnects after a remote close and cancels scheduled retries when closed by the caller', async () => {
vi.useFakeTimers();
const client = new SnowLumaWebSocketClient({
webSocket: MockWebSocket,
reconnect: { minDelayMs: 10 },
});
const opening = client.connect();
const first = MockWebSocket.instances.at(-1)!;
first.open();
await opening;
first.close();
await vi.advanceTimersByTimeAsync(10);
const second = MockWebSocket.instances.at(-1)!;
expect(second).not.toBe(first);
second.open();
await vi.advanceTimersByTimeAsync(0);
expect(client.isConnected).toBe(true);
second.close();
client.close();
expect(vi.getTimerCount()).toBe(0);
});
it('retries after the WebSocket constructor throws', async () => {
let attempts = 0;
class RetrySocket extends MockWebSocket {
constructor(url: string) {
if (attempts++ === 0) {
throw new Error('constructor failed');
}
super(url);
}
}
const client = new SnowLumaWebSocketClient({ webSocket: RetrySocket });
await expect(client.connect()).rejects.toThrow('constructor failed');
const connecting = client.connect();
expect(attempts).toBe(2);
MockWebSocket.instances.at(-1)!.open();
await connecting;
client.close();
});
it('ignores events from a closed socket after a new connection opens', async () => {
class DelayedCloseSocket extends MockWebSocket {
override close(): void {
this.readyState = 2;
}
}
const client = new SnowLumaWebSocketClient({ webSocket: DelayedCloseSocket });
const first = client.connect();
const oldSocket = MockWebSocket.instances.at(-1)!;
oldSocket.open();
await first;
client.close();
const second = client.connect();
const currentSocket = MockWebSocket.instances.at(-1)!;
currentSocket.open();
await second;
const raw = vi.fn();
client.on('raw', raw);
oldSocket.message(JSON.stringify(PRIVATE_EVENT));
oldSocket.emit('close', { code: 1000 });
expect(client.isConnected).toBe(true);
expect(raw).not.toHaveBeenCalled();
client.close();
});
it('settles an opening connection when the caller closes it before the close event', async () => {
class DelayedCloseSocket extends MockWebSocket {
override close(): void {
this.readyState = 2;
}
}
const client = new SnowLumaWebSocketClient({ webSocket: DelayedCloseSocket });
const opening = client.connect();
const oldSocket = MockWebSocket.instances.at(-1)!;
const result = expect(opening).rejects.toThrow('closed');
client.close();
await result;
oldSocket.open();
expect(client.isConnected).toBe(false);
});
it('matches API responses by echo', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
@@ -139,9 +139,7 @@ export function FileSource({
onChange={(e) => onChange(e.target.value)}
placeholder="/path/on/server/file.jpg"
/>
<span className="text-xs text-muted-foreground">
这是 <strong>运行 bot 的服务器</strong> 上的路径,不是你本机的。
</span>
<span className="text-xs text-muted-foreground">使用服务器上的文件路径</span>
</div>
)}
@@ -188,7 +186,7 @@ export function FileSource({
</>
) : (
<>
<FileUp className="h-4 w-4" /> 选择或拖入文件上传到服务器
<FileUp className="h-4 w-4" /> 选择或拖入文件
</>
)}
</label>
@@ -1,8 +1,3 @@
// TaskBadge — the app-wide floating indicator for in-flight debug tasks. Sits
// bottom-right on every page so a streaming upload/download stays visible after
// you switch tabs. Collapsed: a chip with a ring-progress + count. Expanded: a
// list with per-task progress, cancel (running) / dismiss (finished). Renders
// nothing when there are no tasks at all.
import { useState } from 'react';
import { AnimatePresence, motion } from 'motion/react';
import { CheckCircle2, Loader2, X, XCircle } from 'lucide-react';
@@ -37,7 +32,7 @@ function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
>
<X className="h-3.5 w-3.5" />
</button>
) : (
) : task.status !== 'running' ? (
<button
type="button"
onClick={onDismiss}
@@ -46,7 +41,7 @@ function Row({ task, onDismiss }: { task: DebugTask; onDismiss: () => void }) {
>
<X className="h-3.5 w-3.5" />
</button>
)}
) : null}
</div>
{task.status === 'running' && (
<div className="h-1 overflow-hidden rounded-full bg-muted">
@@ -129,7 +124,7 @@ export function TaskBadge() {
)}
{count > 0 ? (
<span>
{count} 个任务进行中{ringPct !== null ? ` · ${ringPct}%` : ''}
{count} 个任务{ringPct !== null ? ` · ${ringPct}%` : ''}
</span>
) : (
<span className="text-muted-foreground">任务完成</span>
@@ -1,40 +1,28 @@
// DebugTaskContext — an app-level registry of in-flight debug-console tasks
// (file uploads, streaming invocations) so they survive tab/page switches
// WITHIN the app (their state lives above the page, not in the unmounting tab).
// A full page unload (refresh / close) can't be survived, so a beforeunload
// guard warns while any task runs. Finished tasks linger briefly for history.
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
useReducer,
type ReactNode,
} from 'react';
export type DebugTaskStatus = 'running' | 'done' | 'failed' | 'canceled';
export type DebugTaskKind = 'upload' | 'stream' | 'invoke';
export interface DebugTask {
id: string;
kind: DebugTaskKind;
label: string;
status: DebugTaskStatus;
/** 0..1 when determinate; undefined = indeterminate. */
progress?: number;
detail?: string;
startedAt: number;
endedAt?: number;
/** Cancel the underlying work (abort the fetch / xhr). */
cancel?: () => void;
}
import {
debugTasksReducer,
type DebugTask,
type DebugTaskStatus,
type DebugTaskUpdate,
} from '@/lib/debug-tasks';
export type { DebugTask, DebugTaskStatus, DebugTaskKind } from '@/lib/debug-tasks';
interface DebugTaskContextValue {
tasks: DebugTask[];
/** Register a task; returns its id. */
start: (task: Omit<DebugTask, 'id' | 'status' | 'startedAt'> & { id?: string }) => string;
update: (id: string, patch: Partial<Omit<DebugTask, 'id'>>) => void;
start: (
task: Omit<DebugTask, 'id' | 'status' | 'startedAt' | 'endedAt'> & { id?: string },
) => string;
update: (id: string, patch: DebugTaskUpdate) => void;
/** Mark terminal (done/failed/canceled) and stamp endedAt. */
finish: (id: string, status: Exclude<DebugTaskStatus, 'running'>, detail?: string) => void;
remove: (id: string) => void;
@@ -47,60 +35,32 @@ let seq = 0;
const nextId = () => `dt-${Date.now().toString(36)}-${(seq++).toString(36)}`;
export function DebugTaskProvider({ children }: { children: ReactNode }) {
const [tasks, setTasks] = useState<DebugTask[]>([]);
const [tasks, dispatch] = useReducer(debugTasksReducer, []);
const start = useCallback<DebugTaskContextValue['start']>((t) => {
const id = t.id ?? nextId();
setTasks((prev) => {
const next = [{ ...t, id, status: 'running' as const, startedAt: Date.now() }, ...prev];
if (next.length <= 50) {
return next;
}
// Over cap: evict the OLDEST finished tasks only — never drop a running
// task (that would orphan its finish()/cancel handle while it keeps going).
const running = next.filter((x) => x.status === 'running').length;
const finished = next.filter((x) => x.status !== 'running');
const drop = new Set(finished.slice(Math.max(0, 50 - running)).map((x) => x.id));
return next.filter((x) => !drop.has(x.id));
});
dispatch({ type: 'start', task: { ...t, id, status: 'running', startedAt: Date.now() } });
return id;
}, []);
const update = useCallback<DebugTaskContextValue['update']>((id, patch) => {
setTasks((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
dispatch({ type: 'update', id, patch });
}, []);
const finish = useCallback<DebugTaskContextValue['finish']>((id, status, detail) => {
setTasks((prev) =>
prev.map((t) =>
t.id === id
? {
...t,
status,
detail: detail ?? t.detail,
endedAt: Date.now(),
cancel: undefined,
}
: t,
),
);
dispatch({ type: 'finish', id, status, detail, endedAt: Date.now() });
}, []);
const remove = useCallback<DebugTaskContextValue['remove']>((id) => {
setTasks((prev) => prev.filter((t) => t.id !== id));
dispatch({ type: 'remove', id });
}, []);
const clearFinished = useCallback(() => {
setTasks((prev) => prev.filter((t) => t.status === 'running'));
dispatch({ type: 'clearFinished' });
}, []);
// beforeunload guard: a real page unload kills in-flight tasks, so warn while
// any task is still running (within-app navigation is safe — state is here).
const anyRunning = tasks.some((task) => task.status === 'running');
useEffect(() => {
const anyRunning = tasks.some((t) => t.status === 'running');
if (!anyRunning) {
return;
}
@@ -112,7 +72,7 @@ export function DebugTaskProvider({ children }: { children: ReactNode }) {
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [tasks]);
}, [anyRunning]);
const value = useMemo<DebugTaskContextValue>(
() => ({ tasks, start, update, finish, remove, clearFinished }),
@@ -135,16 +95,23 @@ export function useDebugTasks(): DebugTaskContextValue {
export function useRunningTaskSummary(): { count: number; progress: number | null } {
const { tasks } = useDebugTasks();
return useMemo(() => {
const running = tasks.filter((t) => t.status === 'running');
let count = 0;
let determinate = 0;
let total = 0;
if (running.length === 0) {
return { count: 0, progress: null };
for (const task of tasks) {
if (task.status !== 'running') {
continue;
}
count++;
if (task.progress !== undefined) {
determinate++;
total += task.progress;
}
}
const determinate = running.filter((t) => typeof t.progress === 'number');
const progress = determinate.length
? determinate.reduce((s, t) => s + (t.progress ?? 0), 0) / determinate.length
: null;
return { count: running.length, progress };
return { count, progress: determinate ? total / determinate : null };
}, [tasks]);
}
+65
View File
@@ -0,0 +1,65 @@
export type DebugTaskStatus = 'running' | 'done' | 'failed' | 'canceled';
export type DebugTaskKind = 'upload' | 'stream' | 'invoke';
export interface DebugTask {
id: string;
kind: DebugTaskKind;
label: string;
status: DebugTaskStatus;
/** 0..1; undefined means indeterminate. */
progress?: number;
detail?: string;
startedAt: number;
endedAt?: number;
cancel?: () => void;
}
export type DebugTaskUpdate = Partial<Pick<DebugTask, 'progress' | 'detail' | 'label'>>;
export type DebugTaskAction =
| { type: 'start'; task: DebugTask }
| { type: 'update'; id: string; patch: DebugTaskUpdate }
| {
type: 'finish';
id: string;
status: Exclude<DebugTaskStatus, 'running'>;
detail?: string;
endedAt: number;
}
| { type: 'remove'; id: string }
| { type: 'clearFinished' };
function trimFinished(tasks: DebugTask[]): DebugTask[] {
let remaining = Math.max(0, 50 - tasks.filter((task) => task.status === 'running').length);
return tasks.filter((task) => task.status === 'running' || remaining-- > 0);
}
export function debugTasksReducer(tasks: DebugTask[], action: DebugTaskAction): DebugTask[] {
switch (action.type) {
case 'start':
return trimFinished([action.task, ...tasks]);
case 'update':
return tasks.map((task) =>
task.id === action.id && task.status === 'running'
? { ...task, ...action.patch }
: task,
);
case 'finish':
return trimFinished(
tasks.map((task) =>
task.id === action.id && task.status === 'running'
? {
...task,
status: action.status,
detail: action.detail ?? task.detail,
endedAt: action.endedAt,
cancel: undefined,
}
: task,
),
);
case 'remove':
return tasks.filter((task) => task.id !== action.id || task.status === 'running');
case 'clearFinished':
return tasks.filter((task) => task.status === 'running');
}
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import { debugTasksReducer, type DebugTask } from '../src/lib/debug-tasks';
function running(id: string): DebugTask {
return { id, kind: 'upload', label: id, status: 'running', startedAt: 1, progress: 0 };
}
describe('debug task lifecycle', () => {
it('keeps the first terminal result when late progress or completion arrives', () => {
const finished = debugTasksReducer([running('a')], {
type: 'finish',
id: 'a',
status: 'canceled',
detail: 'Canceled',
endedAt: 2,
});
const updated = debugTasksReducer(finished, {
type: 'update',
id: 'a',
patch: { progress: 1 },
});
const completed = debugTasksReducer(updated, {
type: 'finish',
id: 'a',
status: 'done',
endedAt: 3,
});
expect(completed).toEqual(finished);
});
it('cannot dismiss running tasks or lose them while clearing history', () => {
const task = running('a');
expect(debugTasksReducer([task], { type: 'remove', id: 'a' })).toEqual([task]);
expect(debugTasksReducer([task], { type: 'clearFinished' })).toEqual([task]);
});
it('keeps every running task and trims history as they finish', () => {
let tasks: DebugTask[] = [];
for (let i = 0; i < 55; i++) {
tasks = debugTasksReducer(tasks, { type: 'start', task: running(String(i)) });
}
expect(tasks).toHaveLength(55);
for (let i = 0; i < 55; i++) {
tasks = debugTasksReducer(tasks, {
type: 'finish',
id: String(i),
status: 'done',
endedAt: 2,
});
}
expect(tasks).toHaveLength(50);
expect(tasks.every((task) => task.status === 'done')).toBe(true);
expect(tasks.some((task) => task.id === '0')).toBe(false);
});
it('releases cancellation and removes only completed tasks', () => {
const tasks = debugTasksReducer(
[{ ...running('a'), cancel: () => undefined }, running('b')],
{
type: 'finish',
id: 'a',
status: 'failed',
detail: 'Upload failed',
endedAt: 2,
},
);
expect(tasks[0]).toMatchObject({
status: 'failed',
detail: 'Upload failed',
endedAt: 2,
cancel: undefined,
});
expect(debugTasksReducer(tasks, { type: 'remove', id: 'a' })).toEqual([running('b')]);
});
});