refactor: use native async discovery and simplify shared state
This commit is contained in:
1 parent
5032cbb8c0
commit
4e2b6b1200
87 files changed
+2063
-2002
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger, runWithTraceRequest, type Logger } from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||
@@ -7,12 +8,11 @@ import { HookSession, type HookSessionDeps } from './hook-session';
|
||||
import {
|
||||
injectHookProcess,
|
||||
listHookProcesses,
|
||||
resolveHookNativePath,
|
||||
unloadHookProcess,
|
||||
type HookProcessBaseInfo,
|
||||
} from './injector';
|
||||
import { PipeWatcher } from './pipe-watcher';
|
||||
import { createNativeProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
import { createProcessEnumerator, type ProcessEnumerator } from './process-enumerator';
|
||||
import { QqHookClient } from './qq-hook-client';
|
||||
import { detectAccountLoginsForPids, type AccountLoginState } from './qq-account';
|
||||
import type { HookProcessAccount, HookProcessInfo } from './types';
|
||||
@@ -55,7 +55,7 @@ export type HookManagerDeps = {
|
||||
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
|
||||
watcherIntervalMs?: number;
|
||||
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
|
||||
listProcesses?: () => HookProcessBaseInfo[];
|
||||
listProcesses?: () => Promise<HookProcessBaseInfo[]>;
|
||||
/** Local account detection used to label each process with the account QQ is
|
||||
* signed in as. Receives the pids to label so each one is resolved against
|
||||
* the HOME it actually runs under (a container can give every QQ instance
|
||||
@@ -104,13 +104,7 @@ export class HookManager {
|
||||
private readonly makeClient: HookSessionDeps['makeClient'];
|
||||
private readonly pipeWatcher: PipeWatcher;
|
||||
private readonly ownsPipeWatcher: boolean;
|
||||
/** Watcher/API process enumeration — isolated + timeout-bounded by default
|
||||
* so a blocked native /proc walk can't freeze the loop (issue #158).
|
||||
* Resolves to `null` (UNKNOWN) on timeout/failure. */
|
||||
private readonly enumerate: () => Promise<HookProcessBaseInfo[] | null>;
|
||||
/** The owned enumerator (worker lifecycle), or null when a custom lister was
|
||||
* injected (tests) — nothing to tear down in that case. */
|
||||
private readonly enumerator: ProcessEnumerator | null;
|
||||
private readonly enumerator: ProcessEnumerator;
|
||||
private readonly detectAccounts: (pids: readonly number[]) => Promise<AccountLoginState[]>;
|
||||
private readonly accountReprobeIntervalMs: number;
|
||||
private readonly autoLoadOnDiscovery: boolean;
|
||||
@@ -149,37 +143,17 @@ export class HookManager {
|
||||
deps.accountReprobeIntervalMs ?? DEFAULT_ACCOUNT_REPROBE_INTERVAL_MS;
|
||||
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
|
||||
|
||||
// A custom lister (tests) is used directly — no worker, no isolation, just
|
||||
// an async wrap that maps a throw to the UNKNOWN sentinel. The default path
|
||||
// wraps the native enumerator in a worker with a timeout.
|
||||
if (deps.listProcesses) {
|
||||
const lister = deps.listProcesses;
|
||||
this.enumerator = null;
|
||||
|
||||
this.enumerate = async () => {
|
||||
try {
|
||||
return await lister();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
} else {
|
||||
this.enumerator = createNativeProcessEnumerator({
|
||||
addonPath: resolveHookNativePath('node'),
|
||||
fallbackSync: listHookProcesses,
|
||||
processName: defaultProcessName(),
|
||||
log: this.log,
|
||||
});
|
||||
this.enumerate = () => this.enumerator!.enumerate();
|
||||
}
|
||||
this.enumerator = createProcessEnumerator({
|
||||
listProcesses: deps.listProcesses ?? listHookProcesses,
|
||||
log: this.log,
|
||||
});
|
||||
|
||||
if (deps.pipeWatcher) {
|
||||
this.pipeWatcher = deps.pipeWatcher;
|
||||
this.ownsPipeWatcher = false;
|
||||
} else {
|
||||
this.pipeWatcher = new PipeWatcher({
|
||||
listProcesses: this.enumerate,
|
||||
listProcesses: this.enumerator.enumerate,
|
||||
listLivePipes: (processes) =>
|
||||
QqHookClient.listLivePipes(processes.map(({ pid }) => pid)),
|
||||
intervalMs: deps.watcherIntervalMs,
|
||||
@@ -196,7 +170,7 @@ export class HookManager {
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
await this.startPromise;
|
||||
const processes = await this.enumerate();
|
||||
const processes = await this.enumerator.enumerate();
|
||||
// A failed enumeration preserves the last known process set.
|
||||
const sessions =
|
||||
processes === null
|
||||
@@ -257,7 +231,7 @@ export class HookManager {
|
||||
this.sessions.clear();
|
||||
this.accounts.clear();
|
||||
this.autoLoadAttempts.clear();
|
||||
this.enumerator?.dispose();
|
||||
this.enumerator.dispose();
|
||||
|
||||
if (this.ownsPipeWatcher) {
|
||||
this.pipeWatcher.dispose();
|
||||
@@ -315,7 +289,7 @@ export class HookManager {
|
||||
|
||||
this.lastAccountProbeFailure = '';
|
||||
} catch (error) {
|
||||
const message = errMsg(error);
|
||||
const message = errorMessage(error);
|
||||
|
||||
if (this.lastAccountProbeFailure !== message) {
|
||||
this.lastAccountProbeFailure = message;
|
||||
@@ -573,10 +547,10 @@ export class HookManager {
|
||||
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
|
||||
session.pid,
|
||||
attempt,
|
||||
errMsg(err),
|
||||
errorMessage(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errMsg(err));
|
||||
this.log.warn('auto-load failed: PID=%d err=%s', session.pid, errorMessage(err));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -644,7 +618,7 @@ export class HookManager {
|
||||
try {
|
||||
this.onSessionsChangedRaw();
|
||||
} catch (err) {
|
||||
this.log.warn('onSessionsChanged threw: %s', errMsg(err));
|
||||
this.log.warn('onSessionsChanged threw: %s', errorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -659,10 +633,6 @@ function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
|
||||
function isTransientLibcMappingError(error: string): boolean {
|
||||
return /^target process does not map \S*\/libc\.so\.6 while resolving mmap$/.test(error);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { readFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
@@ -57,10 +58,6 @@ function isProcessGoneError(error: unknown): boolean {
|
||||
return code === 'ENOENT' || code === 'ESRCH';
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function ownRuntimeDir(platform: NodeJS.Platform, env: NodeJS.ProcessEnv, ownUid: number): string {
|
||||
const explicit = configuredDirectory(
|
||||
env.SNOWLUMA_HOOK_RUNTIME_DIR,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import {
|
||||
createLogger,
|
||||
runWithoutRequestContext,
|
||||
@@ -205,7 +206,9 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
await this.reconcilePipeUp();
|
||||
}).catch((err) => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}).catch((err) =>
|
||||
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
|
||||
);
|
||||
}
|
||||
|
||||
onPipeDown(): void {
|
||||
@@ -219,7 +222,9 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
this.reconcilePipeDown();
|
||||
}).catch((err) => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
|
||||
}).catch((err) =>
|
||||
this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errorMessage(err)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Called by the manager when the watcher reports the QQ.exe process is
|
||||
@@ -267,7 +272,7 @@ export class HookSession extends EventEmitter {
|
||||
this.log.trace(() => [
|
||||
'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
errorMessage(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
@@ -275,7 +280,7 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
});
|
||||
}).catch((err) =>
|
||||
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)),
|
||||
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errorMessage(err)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -347,7 +352,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
operation,
|
||||
`${operation}_threw`,
|
||||
errMsg(error),
|
||||
errorMessage(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
@@ -357,20 +362,12 @@ export class HookSession extends EventEmitter {
|
||||
}
|
||||
|
||||
private serialize<T>(op: () => Promise<T>): Promise<T> {
|
||||
const previous = this.opChain;
|
||||
let release!: () => void;
|
||||
const completion = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
this.opChain = previous.then(() => completion);
|
||||
return (async () => {
|
||||
try {
|
||||
await previous.catch(() => undefined);
|
||||
return await op();
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
})();
|
||||
const result = this.opChain.then(op);
|
||||
this.opChain = result.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─────────────── internal transitions ───────────────
|
||||
@@ -411,7 +408,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
this.applyStatus();
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this._error = errorMessage(error);
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
|
||||
// The module can already be listening even when this call returns
|
||||
@@ -467,7 +464,7 @@ export class HookSession extends EventEmitter {
|
||||
this.setStatus('available', '');
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this._error = errorMessage(error);
|
||||
this.setStatus('error', this._error);
|
||||
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
@@ -489,7 +486,7 @@ export class HookSession extends EventEmitter {
|
||||
this.reconcilePipeDown();
|
||||
}
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this._error = errorMessage(error);
|
||||
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
|
||||
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
|
||||
}
|
||||
@@ -581,7 +578,7 @@ export class HookSession extends EventEmitter {
|
||||
this.log.trace(() => [
|
||||
'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
errorMessage(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
@@ -650,7 +647,7 @@ export class HookSession extends EventEmitter {
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
} catch (error) {
|
||||
this._error = errMsg(error);
|
||||
this._error = errorMessage(error);
|
||||
// Drop the client so the next attempt builds a fresh socket pair.
|
||||
// A failed connect was never logged in → 'connecting' (or 'available').
|
||||
this.tearDownClient();
|
||||
@@ -670,7 +667,7 @@ export class HookSession extends EventEmitter {
|
||||
client.on('packet', (packet) => this.handlePacket(packet));
|
||||
client.on('loginState', (state) => this.handleLoginState(state));
|
||||
client.on('error', (error) => {
|
||||
const msg = errMsg(error);
|
||||
const msg = errorMessage(error);
|
||||
this._error = msg;
|
||||
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
|
||||
});
|
||||
@@ -696,7 +693,7 @@ export class HookSession extends EventEmitter {
|
||||
|
||||
this.reconcilePipeDown();
|
||||
}).catch((err) =>
|
||||
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)),
|
||||
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errorMessage(err)),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -788,7 +785,7 @@ export class HookSession extends EventEmitter {
|
||||
this.log.trace(() => [
|
||||
'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
|
||||
this.pid,
|
||||
errMsg(error),
|
||||
errorMessage(error),
|
||||
renderParamsVerbose(this.toInfo()),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
@@ -813,7 +810,7 @@ export class HookSession extends EventEmitter {
|
||||
() => void this.detectLoginOnce(),
|
||||
LOGIN_RECONCILE_INTERVAL_MS,
|
||||
);
|
||||
this.loginReconcileTimer.unref?.();
|
||||
this.loginReconcileTimer.unref();
|
||||
}
|
||||
|
||||
private stopLoginReconcile(): void {
|
||||
@@ -849,7 +846,7 @@ export class HookSession extends EventEmitter {
|
||||
try {
|
||||
uin = await this.detectLoginUin(this.pid);
|
||||
} catch (error) {
|
||||
const message = errMsg(error);
|
||||
const message = errorMessage(error);
|
||||
|
||||
if (this.lastDetectFailure !== message) {
|
||||
this.lastDetectFailure = message;
|
||||
@@ -924,7 +921,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
uin,
|
||||
attempt,
|
||||
errMsg(error),
|
||||
errorMessage(error),
|
||||
);
|
||||
this.nextLoginIdentityObservationAt =
|
||||
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
|
||||
@@ -936,7 +933,7 @@ export class HookSession extends EventEmitter {
|
||||
this.pid,
|
||||
uin,
|
||||
attempt,
|
||||
errMsg(error),
|
||||
errorMessage(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1077,9 +1074,9 @@ export class HookSession extends EventEmitter {
|
||||
silentForMs,
|
||||
);
|
||||
}, RECEIVE_STALE_CONFIRM_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
this.receiveWatchTimer.unref();
|
||||
}, RECEIVE_STALE_AFTER_MS);
|
||||
this.receiveWatchTimer.unref?.();
|
||||
this.receiveWatchTimer.unref();
|
||||
}
|
||||
|
||||
private shouldWatchReceive(): boolean {
|
||||
@@ -1134,7 +1131,3 @@ export class HookSession extends EventEmitter {
|
||||
this._receiveHealthy = true;
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { resolveRuntimeNativePath } from '@snowluma/common/native-path';
|
||||
|
||||
import { listSnowlumaPipePidsSync } from './qq-hook-client';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ManualMapHandle {
|
||||
base: bigint;
|
||||
entry: bigint;
|
||||
@@ -15,7 +12,7 @@ export interface ManualMapHandle {
|
||||
|
||||
interface NativeHookAddon {
|
||||
getRuntimeIntegrity?(): unknown;
|
||||
getAllMainProcess(): number[];
|
||||
getAllMainProcessAsync(): Promise<number[]>;
|
||||
probeDbLock?(dbPath: string): { pid: number; name: string }[];
|
||||
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>;
|
||||
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
|
||||
@@ -43,14 +40,6 @@ function loadNativeAddon(addonPath: string): NativeHookAddon {
|
||||
|
||||
type HookBinaryExt = 'node' | 'dll' | 'so';
|
||||
|
||||
function platformBinaryName(ext: HookBinaryExt): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') {
|
||||
return `snowluma-win32-x64.${ext}`;
|
||||
}
|
||||
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function platformInjectableExt(): 'dll' | 'so' {
|
||||
return process.platform === 'win32' ? 'dll' : 'so';
|
||||
}
|
||||
@@ -59,33 +48,8 @@ function defaultProcessName(): string {
|
||||
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
|
||||
}
|
||||
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
// Same offset works for `packages/bridge/dist/index.mjs` after build.
|
||||
// 3. cwd-based fallback when neither __dirname-relative path resolves.
|
||||
return [
|
||||
path.resolve(__dirname, 'native'),
|
||||
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(process.cwd(), 'dist', 'native'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
|
||||
const fileName = platformBinaryName(ext);
|
||||
|
||||
for (const dir of nativeSearchDirs()) {
|
||||
const fullPath = path.join(dir, fileName);
|
||||
|
||||
if (existsSync(fullPath)) {
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return resolveRuntimeNativePath(`snowluma-${process.platform}-${process.arch}.${ext}`);
|
||||
}
|
||||
|
||||
export function getNativeHookAddon(): NativeHookAddon | null {
|
||||
@@ -105,7 +69,7 @@ export function getNativeHookAddon(): NativeHookAddon | null {
|
||||
nativeLoadError = null;
|
||||
return nativeAddon;
|
||||
} catch (error) {
|
||||
nativeLoadError = error instanceof Error ? error.message : String(error);
|
||||
nativeLoadError = errorMessage(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -114,7 +78,7 @@ export function getNativeHookLoadError(): string | null {
|
||||
return nativeLoadError;
|
||||
}
|
||||
|
||||
export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
export async function listHookProcesses(): Promise<HookProcessBaseInfo[]> {
|
||||
// macOS: no native enumerate-QQ addon. The DYLD_INSERT injection model
|
||||
// means QQ ran with our dylib already mapped, so the dylib's listener
|
||||
// socket IS the discovery signal. Treat every `mojo.<pid>.control.sock`
|
||||
@@ -130,10 +94,16 @@ export function listHookProcesses(): HookProcessBaseInfo[] {
|
||||
const addon = getNativeHookAddon();
|
||||
|
||||
if (!addon) {
|
||||
return [];
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
|
||||
return [...new Set(addon.getAllMainProcess())]
|
||||
if (typeof addon.getAllMainProcessAsync !== 'function') {
|
||||
throw new Error(
|
||||
'Hook native addon lacks getAllMainProcessAsync; update the native artifacts',
|
||||
);
|
||||
}
|
||||
|
||||
return [...new Set(await addon.getAllMainProcessAsync())]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: defaultProcessName(), path: '' }));
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { EventEmitter } from 'events';
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
@@ -163,7 +164,7 @@ export class PipeWatcher extends EventEmitter {
|
||||
try {
|
||||
processes = await this.listProcesses();
|
||||
} catch (error) {
|
||||
this.log.warn('listProcesses failed: %s', errMsg(error));
|
||||
this.log.warn('listProcesses failed: %s', errorMessage(error));
|
||||
processes = null;
|
||||
}
|
||||
|
||||
@@ -183,7 +184,7 @@ export class PipeWatcher extends EventEmitter {
|
||||
try {
|
||||
livePipes = await this.listLivePipes(processes);
|
||||
} catch (error) {
|
||||
this.log.warn('listLivePipes failed: %s', errMsg(error));
|
||||
this.log.warn('listLivePipes failed: %s', errorMessage(error));
|
||||
livePipes = null;
|
||||
}
|
||||
|
||||
@@ -257,7 +258,3 @@ export class PipeWatcher extends EventEmitter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -1,291 +1,77 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import { Worker } from 'worker_threads';
|
||||
import type { HookProcessBaseInfo } from './injector';
|
||||
|
||||
/**
|
||||
* Isolated, timeout-bounded wrapper around the native `getAllMainProcess()`
|
||||
* enumeration.
|
||||
*
|
||||
* Why this exists (issue #158): the watcher polls QQ processes every ~1.5s by
|
||||
* calling the synchronous native enumerator, which walks `/proc` and reads each
|
||||
* candidate's `cmdline`/`maps`. Those reads go through the target's mm and
|
||||
* BLOCK while a process is mid-`exec()` — exactly what happens when QQ runs a
|
||||
* silent hot-update and the process table churns. A blocked synchronous native
|
||||
* call freezes the whole Node event loop: OneBot stops responding, the watcher
|
||||
* stops ticking, reconnect logic never runs. The process stays "alive" so the
|
||||
* supervisor never restarts it — the bot just goes silent.
|
||||
*
|
||||
* The only way to put a real timeout on a synchronous native call is to run it
|
||||
* off the main thread. We run it in a worker; the main thread races the result
|
||||
* against a deadline. On timeout the main loop keeps going (it returns the
|
||||
* UNKNOWN sentinel `null`, which the watcher treats as "no fresh data, keep
|
||||
* prior state" — crucially NOT "all processes gone"). The blocked worker is
|
||||
* abandoned (a fresh one is spawned next time); it exits on its own once the
|
||||
* native call finally returns.
|
||||
*
|
||||
* Graceful degradation: if the native addon can't be loaded in a worker (e.g.
|
||||
* it isn't context-aware) or there's no addon at all (macOS reads sockets, not
|
||||
* `/proc`), we fall back to calling `fallbackSync` on the main thread — i.e.
|
||||
* exactly today's behaviour, no worse.
|
||||
*/
|
||||
export interface ProcessEnumerator {
|
||||
/** Resolve to the process list, or `null` (UNKNOWN) when enumeration timed
|
||||
* out / failed and the caller should keep its prior state. */
|
||||
/** null means unknown: keep the previous process set. */
|
||||
enumerate(): Promise<HookProcessBaseInfo[] | null>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export interface NativeEnumeratorDeps {
|
||||
/** Resolved path to the hook `.node` addon, or null when there is none
|
||||
* (macOS / missing) — in which case we never spawn a worker. */
|
||||
addonPath: string | null;
|
||||
/** Synchronous lister used when worker isolation is unavailable. Returns
|
||||
* today's value (and may itself block — that's the no-worse-than-before
|
||||
* fallback). */
|
||||
fallbackSync: () => HookProcessBaseInfo[];
|
||||
/** Display name stamped on each returned process (e.g. 'qq' / 'QQ.exe'). */
|
||||
processName: string;
|
||||
/** Per-enumeration deadline. Default 4000ms — comfortably above a healthy
|
||||
* enumeration (single-digit ms) but well under a human "is it dead?". */
|
||||
interface ProcessEnumeratorDeps {
|
||||
listProcesses: () => Promise<HookProcessBaseInfo[]>;
|
||||
timeoutMs?: number;
|
||||
/** Cap on abandoned (blocked) workers before we stop spawning more and just
|
||||
* return UNKNOWN until they drain. Bounds thread growth across a long
|
||||
* hot-update window. Default 4. */
|
||||
maxOrphans?: number;
|
||||
log?: Logger;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4000;
|
||||
const DEFAULT_MAX_ORPHANS = 4;
|
||||
|
||||
// Worker body (CommonJS — eval workers default to CJS so `require` is available;
|
||||
// `process.dlopen` is a global and needs no module system). Loads the addon
|
||||
// handed in via workerData, then answers each 'enumerate' with the raw pid list
|
||||
// from the blocking native call. All the cheap post-processing stays on main.
|
||||
const WORKER_SOURCE = `
|
||||
const { parentPort, workerData } = require('node:worker_threads');
|
||||
let addon = null;
|
||||
try {
|
||||
const mod = { exports: {} };
|
||||
process.dlopen(mod, workerData.addonPath);
|
||||
addon = mod.exports;
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'fatal', error: String((e && e.message) || e) });
|
||||
}
|
||||
if (addon) {
|
||||
parentPort.on('message', (msg) => {
|
||||
if (!msg || msg.type !== 'enumerate') return;
|
||||
try {
|
||||
const pids = addon.getAllMainProcess();
|
||||
parentPort.postMessage({ type: 'result', id: msg.id, pids: Array.from(pids) });
|
||||
} catch (e) {
|
||||
parentPort.postMessage({ type: 'error', id: msg.id, error: String((e && e.message) || e) });
|
||||
}
|
||||
});
|
||||
parentPort.postMessage({ type: 'ready' });
|
||||
}
|
||||
`;
|
||||
|
||||
function mapPids(pids: number[], processName: string): HookProcessBaseInfo[] {
|
||||
return [...new Set(pids)]
|
||||
.filter((pid) => Number.isInteger(pid) && pid > 0)
|
||||
.sort((a, b) => a - b)
|
||||
.map((pid) => ({ pid, name: processName, path: '' }));
|
||||
}
|
||||
|
||||
export function createNativeProcessEnumerator(deps: NativeEnumeratorDeps): ProcessEnumerator {
|
||||
export function createProcessEnumerator(deps: ProcessEnumeratorDeps): ProcessEnumerator {
|
||||
const log = deps.log ?? createLogger('ProcessEnumerator');
|
||||
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const maxOrphans = deps.maxOrphans ?? DEFAULT_MAX_ORPHANS;
|
||||
|
||||
// No addon to isolate (macOS / missing) → never spawn a worker; the sync
|
||||
// fallback there is a cheap socket read, not a /proc walk.
|
||||
if (!deps.addonPath) {
|
||||
return {
|
||||
async enumerate() {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
},
|
||||
dispose() {
|
||||
/* nothing to tear down */
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const addonPath = deps.addonPath;
|
||||
let worker: Worker | null = null;
|
||||
/** Set once we learn the addon can't load in a worker — permanent fallback. */
|
||||
let isolationBroken = false;
|
||||
let orphans = 0;
|
||||
let seq = 0;
|
||||
const pending = new Map<number, { resolve: (pids: number[] | null) => void }>();
|
||||
const timeoutMs = deps.timeoutMs ?? 4000;
|
||||
let disposed = false;
|
||||
|
||||
const spawnWorker = (): void => {
|
||||
const w = new Worker(WORKER_SOURCE, { eval: true, workerData: { addonPath } });
|
||||
worker = w;
|
||||
w.on('message', (msg: { type: string; id?: number; pids?: number[]; error?: string }) => {
|
||||
if (msg.type === 'ready') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'fatal') {
|
||||
// The addon won't load off-thread — give up on isolation for good and
|
||||
// fall back to the synchronous path from here on. Resolve any in-flight
|
||||
// request now (UNKNOWN) so it doesn't sit waiting for the timeout.
|
||||
log.warn(
|
||||
'process enumeration cannot be isolated (addon load failed in worker): %s — falling back to in-loop enumeration',
|
||||
msg.error ?? '',
|
||||
);
|
||||
isolationBroken = true;
|
||||
|
||||
for (const { resolve } of pending.values()) {
|
||||
resolve(null);
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
teardownWorker();
|
||||
return;
|
||||
}
|
||||
|
||||
if ((msg.type === 'result' || msg.type === 'error') && typeof msg.id === 'number') {
|
||||
const entry = pending.get(msg.id);
|
||||
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
pending.delete(msg.id);
|
||||
entry.resolve(msg.type === 'result' ? (msg.pids ?? []) : null);
|
||||
}
|
||||
});
|
||||
w.on('error', (err) => {
|
||||
log.warn('enumeration worker error: %s', errMsg(err));
|
||||
|
||||
if (worker === w) {
|
||||
teardownWorker();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const teardownWorker = (): void => {
|
||||
const w = worker;
|
||||
worker = null;
|
||||
|
||||
if (!w) {
|
||||
return;
|
||||
}
|
||||
|
||||
// terminate() can't preempt a thread blocked in the native call; it takes
|
||||
// effect once the call returns. Track it as an orphan until it actually
|
||||
// exits so we can bound how many we let pile up.
|
||||
orphans += 1;
|
||||
w.once('exit', () => {
|
||||
orphans = Math.max(0, orphans - 1);
|
||||
});
|
||||
void w.terminate().catch(() => {
|
||||
/* already gone */
|
||||
});
|
||||
};
|
||||
|
||||
const syncFallback = (): HookProcessBaseInfo[] | null => {
|
||||
try {
|
||||
return deps.fallbackSync();
|
||||
} catch (err) {
|
||||
log.warn('enumerate sync fallback failed: %s', errMsg(err));
|
||||
return null;
|
||||
}
|
||||
};
|
||||
let pending: {
|
||||
promise: Promise<HookProcessBaseInfo[] | null>;
|
||||
settle: (result: HookProcessBaseInfo[] | null) => void;
|
||||
} | null = null;
|
||||
|
||||
return {
|
||||
async enumerate(): Promise<HookProcessBaseInfo[] | null> {
|
||||
if (disposed || isolationBroken) {
|
||||
return syncFallback();
|
||||
enumerate() {
|
||||
if (disposed) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
if (!worker) {
|
||||
if (orphans >= maxOrphans) {
|
||||
// Too many blocked workers already piling up (a sustained hang) —
|
||||
// don't spawn more; report UNKNOWN and let them drain.
|
||||
return null;
|
||||
}
|
||||
|
||||
spawnWorker();
|
||||
if (pending) {
|
||||
return pending.promise;
|
||||
}
|
||||
|
||||
const w = worker;
|
||||
|
||||
if (!w) {
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
const id = ++seq;
|
||||
const resultPromise = new Promise<number[] | null>((resolve) => {
|
||||
pending.set(id, { resolve });
|
||||
let resolve!: (result: HookProcessBaseInfo[] | null) => void;
|
||||
const promise = new Promise<HookProcessBaseInfo[] | null>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
|
||||
try {
|
||||
w.postMessage({ type: 'enumerate', id });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
log.warn('failed to post enumerate request: %s', errMsg(err));
|
||||
teardownWorker();
|
||||
return syncFallback();
|
||||
}
|
||||
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
||||
});
|
||||
const outcome = await Promise.race([resultPromise, timeout]);
|
||||
|
||||
if (timer) {
|
||||
const settle = (result: HookProcessBaseInfo[] | null) => {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
if (outcome === 'timeout') {
|
||||
pending.delete(id);
|
||||
const timer = setTimeout(() => {
|
||||
log.warn(
|
||||
'process enumeration timed out after %dms (worker abandoned) — keeping prior process set',
|
||||
'process enumeration timed out after %dms; keeping prior process set',
|
||||
timeoutMs,
|
||||
);
|
||||
teardownWorker();
|
||||
return null;
|
||||
}
|
||||
settle(null);
|
||||
}, timeoutMs);
|
||||
pending = { promise, settle };
|
||||
|
||||
if (outcome === null) {
|
||||
// Native call threw inside the worker — treat as a transient failure,
|
||||
// keep prior state rather than nuking every session.
|
||||
return null;
|
||||
}
|
||||
|
||||
return mapPids(outcome, deps.processName);
|
||||
// A timeout ends the wait, not the native call. Keep its slot until it
|
||||
// finishes so subsequent polls cannot accumulate blocked native work.
|
||||
void Promise.resolve()
|
||||
.then(() => (disposed ? null : deps.listProcesses()))
|
||||
.then(
|
||||
(processes) => {
|
||||
pending = null;
|
||||
settle(disposed ? null : processes);
|
||||
},
|
||||
(error) => {
|
||||
pending = null;
|
||||
log.warn('process enumeration failed: %s', errorMessage(error));
|
||||
settle(null);
|
||||
},
|
||||
);
|
||||
return promise;
|
||||
},
|
||||
|
||||
dispose() {
|
||||
disposed = true;
|
||||
|
||||
for (const { resolve } of pending.values()) {
|
||||
resolve(null);
|
||||
}
|
||||
|
||||
pending.clear();
|
||||
const w = worker;
|
||||
worker = null;
|
||||
|
||||
if (w) {
|
||||
void w.terminate().catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
}
|
||||
pending?.settle(null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function errMsg(value: unknown): string {
|
||||
return value instanceof Error ? value.message : String(value);
|
||||
}
|
||||
@@ -37,7 +37,7 @@ function makeManager(
|
||||
let pids = opts.processes ?? [];
|
||||
let live = new Set<number>(opts.livePipes ?? []);
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
@@ -72,7 +72,7 @@ function makeManager(
|
||||
unload: vi.fn(),
|
||||
},
|
||||
makeClient: clientFactory,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
detectAccounts: opts.detectAccounts ?? (async () => []),
|
||||
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
|
||||
onSessionsChanged,
|
||||
@@ -162,7 +162,7 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
it('is OPTIONAL — omitting it leaves the manager fully functional', async () => {
|
||||
const pids = [4242];
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(),
|
||||
intervalMs: 60_000,
|
||||
});
|
||||
@@ -193,7 +193,7 @@ describe('HookManager.onSessionsChanged', () => {
|
||||
|
||||
return c;
|
||||
}),
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
detectAccounts: async () => [],
|
||||
// onSessionsChanged deliberately omitted
|
||||
});
|
||||
|
||||
@@ -43,7 +43,7 @@ function makeManager(opts: {
|
||||
);
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
@@ -77,7 +77,7 @@ function makeManager(opts: {
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
onSessionsChanged: opts.onSessionsChanged,
|
||||
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
|
||||
// Detection reads QQ's own data directories; tests stay off the host.
|
||||
detectAccounts: opts.detectAccounts ?? (async () => []),
|
||||
});
|
||||
|
||||
@@ -43,7 +43,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
const clients: FakeClient[] = [];
|
||||
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listLivePipes: async () => new Set(liveSet),
|
||||
intervalMs: 60_000, // manual ticks only
|
||||
});
|
||||
@@ -70,7 +70,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
|
||||
return c as unknown as QqHookClient;
|
||||
},
|
||||
autoLoadOnDiscovery: true,
|
||||
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
listProcesses: async () => [{ pid: PID, name: 'qq', path: '' }],
|
||||
detectAccounts: async () => [],
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
// - at most one client is alive at any point
|
||||
// - every prior client's EventEmitter listener count drops to 0 after teardown
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { describe, it, expect, onTestFinished, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookSession } from '../src/hook-session';
|
||||
import type { ManualMapHandle } from '../src/injector';
|
||||
@@ -57,6 +57,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
detectLoginUin: async () => null,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
@@ -71,6 +72,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
onTestFinished(() => session.dispose());
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
@@ -99,6 +101,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
let pipeLive = true;
|
||||
const clients: FakeClient[] = [];
|
||||
const session = new HookSession(61, {
|
||||
detectLoginUin: async () => null,
|
||||
injector: {
|
||||
inject: vi.fn(() => ({
|
||||
method: 'loadModuleManual' as const,
|
||||
@@ -113,6 +116,7 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
|
||||
},
|
||||
pipeWatcher: { isPipeLive: () => pipeLive },
|
||||
});
|
||||
onTestFinished(() => session.dispose());
|
||||
|
||||
await session.load();
|
||||
session.onPipeUp();
|
||||
|
||||
@@ -20,7 +20,9 @@ vi.mock('../src/qq-hook-client', () => ({
|
||||
listSnowlumaPipePidsSync: listPidsMock,
|
||||
}));
|
||||
|
||||
const INJECTOR_DIR = path.dirname(fileURLToPath(new URL('../src/injector.ts', import.meta.url)));
|
||||
const NATIVE_PATH_DIR = path.dirname(
|
||||
fileURLToPath(new URL('../../common/src/native-path.ts', import.meta.url)),
|
||||
);
|
||||
const ORIGINAL_PLATFORM = process.platform;
|
||||
const ORIGINAL_ARCH = process.arch;
|
||||
|
||||
@@ -41,17 +43,15 @@ function restorePlatform(): void {
|
||||
Object.defineProperty(process, 'arch', { value: ORIGINAL_ARCH, configurable: true });
|
||||
}
|
||||
|
||||
function nativeSearchDirs(cwd = process.cwd()): string[] {
|
||||
function nativeSearchDirs(): string[] {
|
||||
return [
|
||||
path.resolve(INJECTOR_DIR, 'native'),
|
||||
path.resolve(INJECTOR_DIR, '..', '..', 'runtime', 'native'),
|
||||
path.resolve(cwd, 'dist', 'native'),
|
||||
path.resolve(cwd, 'packages', 'runtime', 'native'),
|
||||
path.resolve(NATIVE_PATH_DIR, 'native'),
|
||||
path.resolve(NATIVE_PATH_DIR, '..', '..', 'runtime', 'native'),
|
||||
];
|
||||
}
|
||||
|
||||
function nativeCandidate(fileName: string, dirIndex: number, cwd = process.cwd()): string {
|
||||
return path.join(nativeSearchDirs(cwd)[dirIndex]!, fileName);
|
||||
function nativeCandidate(fileName: string, dirIndex: number): string {
|
||||
return path.join(nativeSearchDirs()[dirIndex]!, fileName);
|
||||
}
|
||||
|
||||
function allowExisting(paths: readonly string[]): void {
|
||||
@@ -61,13 +61,13 @@ function allowExisting(paths: readonly string[]): void {
|
||||
|
||||
function fakeAddon(
|
||||
overrides: {
|
||||
getAllMainProcess?: number[];
|
||||
getAllMainProcessAsync?: number[];
|
||||
loadModuleManual?: (pid: number, dylibPath: string) => unknown;
|
||||
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void;
|
||||
} = {},
|
||||
) {
|
||||
return {
|
||||
getAllMainProcess: vi.fn(() => overrides.getAllMainProcess ?? []),
|
||||
getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []),
|
||||
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)),
|
||||
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)),
|
||||
};
|
||||
@@ -110,8 +110,6 @@ describe('resolveHookNativePath', () => {
|
||||
expect(probed).toEqual([
|
||||
nativeCandidate('snowluma-linux-x64.node', 0),
|
||||
nativeCandidate('snowluma-linux-x64.node', 1),
|
||||
nativeCandidate('snowluma-linux-x64.node', 2),
|
||||
nativeCandidate('snowluma-linux-x64.node', 3),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -132,7 +130,7 @@ describe('resolveHookNativePath', () => {
|
||||
|
||||
it('skips missing earlier directories for the injectable .so', async () => {
|
||||
setPlatform('linux', 'arm64');
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 2);
|
||||
const winner = nativeCandidate('snowluma-linux-arm64.so', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
@@ -141,7 +139,7 @@ describe('resolveHookNativePath', () => {
|
||||
|
||||
it('resolves snowluma-win32-x64.dll on win32 x64', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 3);
|
||||
const winner = nativeCandidate('snowluma-win32-x64.dll', 1);
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
@@ -157,7 +155,7 @@ describe('resolveHookNativePath', () => {
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
});
|
||||
|
||||
it('re-reads process.cwd() for the dist/native fallback', async () => {
|
||||
it('does not load an unrelated native addon from the working directory', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
vi.spyOn(process, 'cwd').mockReturnValue('/tmp/sl-injector-cwd');
|
||||
const winner = path.join(
|
||||
@@ -169,7 +167,7 @@ describe('resolveHookNativePath', () => {
|
||||
allowExisting([winner]);
|
||||
|
||||
const { resolveHookNativePath } = await loadInjector();
|
||||
expect(resolveHookNativePath('node')).toBe(winner);
|
||||
expect(resolveHookNativePath('node')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -248,14 +246,25 @@ describe('getNativeHookAddon / getNativeHookLoadError', () => {
|
||||
});
|
||||
|
||||
describe('listHookProcesses', () => {
|
||||
it('rejects an obsolete addon without calling its synchronous enumerator', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
const getAllMainProcess = vi.fn(() => [9]);
|
||||
installDlopen({ getAllMainProcess });
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
await expect(listHookProcesses()).rejects.toThrow('getAllMainProcessAsync');
|
||||
expect(getAllMainProcess).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('on darwin maps sorted pipe pids without opening the native addon', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
listPidsMock.mockReturnValue(new Set([42, 7, 15]));
|
||||
allowExisting([nativeCandidate('snowluma-darwin-arm64.node', 0)]);
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcess: [99] }));
|
||||
const dlopen = installDlopen(fakeAddon({ getAllMainProcessAsync: [99] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
expect(await listHookProcesses()).toEqual([
|
||||
{ pid: 7, name: 'qq', path: '' },
|
||||
{ pid: 15, name: 'qq', path: '' },
|
||||
{ pid: 42, name: 'qq', path: '' },
|
||||
@@ -269,14 +278,16 @@ describe('listHookProcesses', () => {
|
||||
listPidsMock.mockReturnValue(new Set());
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
expect(await listHookProcesses()).toEqual([]);
|
||||
});
|
||||
|
||||
it('on non-darwin returns [] when the addon cannot be loaded', async () => {
|
||||
it('reports a missing addon instead of an empty process set', async () => {
|
||||
setPlatform('linux', 'x64');
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([]);
|
||||
await expect(listHookProcesses()).rejects.toThrow(
|
||||
'No hook native addon found for linux-x64',
|
||||
);
|
||||
});
|
||||
|
||||
it('on linux dedupes, drops non-positive/non-integer pids, and sorts', async () => {
|
||||
@@ -285,12 +296,12 @@ describe('listHookProcesses', () => {
|
||||
allowExisting([nodePath]);
|
||||
installDlopen(
|
||||
fakeAddon({
|
||||
getAllMainProcess: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
getAllMainProcessAsync: [8, 0, 8, -1, 3.5, 2, Number.NaN, 2],
|
||||
}),
|
||||
);
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([
|
||||
expect(await listHookProcesses()).toEqual([
|
||||
{ pid: 2, name: 'qq', path: '' },
|
||||
{ pid: 8, name: 'qq', path: '' },
|
||||
]);
|
||||
@@ -299,10 +310,10 @@ describe('listHookProcesses', () => {
|
||||
it('on win32 names processes QQ.exe', async () => {
|
||||
setPlatform('win32', 'x64');
|
||||
allowExisting([nativeCandidate('snowluma-win32-x64.node', 0)]);
|
||||
installDlopen(fakeAddon({ getAllMainProcess: [9] }));
|
||||
installDlopen(fakeAddon({ getAllMainProcessAsync: [9] }));
|
||||
|
||||
const { listHookProcesses } = await loadInjector();
|
||||
expect(listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
|
||||
expect(await listHookProcesses()).toEqual([{ pid: 9, name: 'QQ.exe', path: '' }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -345,8 +356,8 @@ describe('injectHookProcess', () => {
|
||||
|
||||
it('accepts a synchronous loadModuleManual return value', async () => {
|
||||
setPlatform('darwin', 'arm64');
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 2);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 3);
|
||||
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 1);
|
||||
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 1);
|
||||
allowExisting([nodePath, soPath]);
|
||||
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
|
||||
installDlopen(addon);
|
||||
|
||||
@@ -1,57 +1,120 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { createNativeProcessEnumerator } from '../src/process-enumerator';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createProcessEnumerator } from '../src/process-enumerator';
|
||||
import type { HookProcessBaseInfo } from '../src/injector';
|
||||
|
||||
const QQ = (pid: number): HookProcessBaseInfo => ({ pid, name: 'qq', path: '' });
|
||||
|
||||
describe('createNativeProcessEnumerator', () => {
|
||||
describe('no addon (macOS / missing) → synchronous fallback, never a worker', () => {
|
||||
it('returns the sync lister result', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => [QQ(10), QQ(20)],
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toEqual([QQ(10), QQ(20)]);
|
||||
en.dispose();
|
||||
});
|
||||
function deferred() {
|
||||
let resolve!: (processes: HookProcessBaseInfo[]) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<HookProcessBaseInfo[]>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
it('maps a throwing sync lister to UNKNOWN (null), not an empty list', async () => {
|
||||
const en = createNativeProcessEnumerator({
|
||||
addonPath: null,
|
||||
fallbackSync: () => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
processName: 'qq',
|
||||
});
|
||||
expect(await en.enumerate()).toBeNull();
|
||||
en.dispose();
|
||||
});
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe('process enumeration', () => {
|
||||
it('shares one native request between concurrent callers', async () => {
|
||||
const request = deferred();
|
||||
const listProcesses = vi.fn(() => request.promise);
|
||||
const enumerator = createProcessEnumerator({ listProcesses });
|
||||
const first = enumerator.enumerate();
|
||||
expect(enumerator.enumerate()).toBe(first);
|
||||
request.resolve([QQ(1), QQ(2)]);
|
||||
expect(await first).toEqual([QQ(1), QQ(2)]);
|
||||
expect(listProcesses).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
enumerator.dispose();
|
||||
});
|
||||
|
||||
describe('worker isolation that cannot load the addon → permanent fallback', () => {
|
||||
it('falls back to the sync lister after the worker reports a fatal load error', async () => {
|
||||
const fallback = vi.fn(() => [QQ(7)]);
|
||||
const en = createNativeProcessEnumerator({
|
||||
// A path that exists nowhere → process.dlopen throws in the worker →
|
||||
// the worker posts 'fatal' → isolation is abandoned for good.
|
||||
addonPath: '/nonexistent/snowluma-test.node',
|
||||
fallbackSync: fallback,
|
||||
processName: 'qq',
|
||||
timeoutMs: 200,
|
||||
it('keeps timed-out native work in flight until it actually finishes', async () => {
|
||||
const request = deferred();
|
||||
const listProcesses = vi.fn(() => request.promise).mockResolvedValueOnce([QQ(1)]);
|
||||
const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
|
||||
expect(await enumerator.enumerate()).toEqual([QQ(1)]);
|
||||
const stalled = enumerator.enumerate();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(await stalled).toBeNull();
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
expect(await enumerator.enumerate()).toBeNull();
|
||||
}
|
||||
|
||||
expect(listProcesses).toHaveBeenCalledTimes(2);
|
||||
request.resolve([QQ(2)]);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
listProcesses.mockResolvedValueOnce([QQ(3)]);
|
||||
expect(await enumerator.enumerate()).toEqual([QQ(3)]);
|
||||
expect(await stalled).toBeNull();
|
||||
enumerator.dispose();
|
||||
});
|
||||
|
||||
it.each(['throw', 'reject'] as const)(
|
||||
'keeps a %s unknown and allows a fresh request',
|
||||
async (kind) => {
|
||||
const listProcesses = vi.fn<() => Promise<HookProcessBaseInfo[]>>(() => {
|
||||
if (kind === 'throw') {
|
||||
throw new Error('process table unavailable');
|
||||
}
|
||||
|
||||
return Promise.reject(new Error('process table unavailable'));
|
||||
});
|
||||
const enumerator = createProcessEnumerator({ listProcesses });
|
||||
expect(await enumerator.enumerate()).toBeNull();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
listProcesses.mockResolvedValueOnce([]);
|
||||
expect(await enumerator.enumerate()).toEqual([]);
|
||||
enumerator.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
// First call spawns the worker; the fatal message drains it to UNKNOWN.
|
||||
const first = await en.enumerate();
|
||||
expect(first).toBeNull();
|
||||
it('handles a rejection after timeout and recovers on the next poll', async () => {
|
||||
const request = deferred();
|
||||
const listProcesses = vi.fn(() => request.promise);
|
||||
const enumerator = createProcessEnumerator({ listProcesses, timeoutMs: 100 });
|
||||
const pending = enumerator.enumerate();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(await pending).toBeNull();
|
||||
request.reject(new Error('late failure'));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
listProcesses.mockResolvedValueOnce([QQ(4)]);
|
||||
expect(await enumerator.enumerate()).toEqual([QQ(4)]);
|
||||
enumerator.dispose();
|
||||
});
|
||||
|
||||
// Give the 'fatal' message a moment to flip isolationBroken if it hadn't
|
||||
// already, then subsequent calls take the synchronous fallback.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const second = await en.enumerate();
|
||||
expect(second).toEqual([QQ(7)]);
|
||||
expect(fallback).toHaveBeenCalled();
|
||||
en.dispose();
|
||||
});
|
||||
it('settles disposal immediately without accepting late native results', async () => {
|
||||
const request = deferred();
|
||||
const listProcesses = vi.fn(() => request.promise);
|
||||
const enumerator = createProcessEnumerator({ listProcesses });
|
||||
const pending = enumerator.enumerate();
|
||||
await Promise.resolve();
|
||||
enumerator.dispose();
|
||||
enumerator.dispose();
|
||||
expect(await pending).toBeNull();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
request.resolve([QQ(1)]);
|
||||
expect(await enumerator.enumerate()).toBeNull();
|
||||
expect(listProcesses).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('never calls the lister after disposal', async () => {
|
||||
const listProcesses = vi.fn(async () => [QQ(1)]);
|
||||
const enumerator = createProcessEnumerator({ listProcesses });
|
||||
enumerator.dispose();
|
||||
expect(await enumerator.enumerate()).toBeNull();
|
||||
expect(listProcesses).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not start queued native work when disposed in the same tick', async () => {
|
||||
const listProcesses = vi.fn(async () => [QQ(1)]);
|
||||
const enumerator = createProcessEnumerator({ listProcesses });
|
||||
const pending = enumerator.enumerate();
|
||||
enumerator.dispose();
|
||||
expect(await pending).toBeNull();
|
||||
expect(listProcesses).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,14 @@
|
||||
"types": "./src/version.ts",
|
||||
"default": "./src/version.ts"
|
||||
},
|
||||
"./native-path": {
|
||||
"types": "./src/native-path.ts",
|
||||
"default": "./src/native-path.ts"
|
||||
},
|
||||
"./errors": {
|
||||
"types": "./src/errors.ts",
|
||||
"default": "./src/errors.ts"
|
||||
},
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -1,26 +1,9 @@
|
||||
const HEX_CHARS = '0123456789abcdef';
|
||||
const HEX_CHARS_UPPER = '0123456789ABCDEF';
|
||||
|
||||
export function toHex(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS[b >> 4];
|
||||
h += HEX_CHARS[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString('hex');
|
||||
}
|
||||
|
||||
export function toHexUpper(data: Uint8Array | Buffer): string {
|
||||
let h = '';
|
||||
|
||||
for (const b of data) {
|
||||
h += HEX_CHARS_UPPER[b >> 4];
|
||||
h += HEX_CHARS_UPPER[b & 0xf];
|
||||
}
|
||||
|
||||
return h;
|
||||
return toHex(data).toUpperCase();
|
||||
}
|
||||
|
||||
export function hexPreview(data: Uint8Array | Buffer, maxBytes = 64): string {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from './errors';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
@@ -1237,7 +1238,3 @@ export async function _resetFileTransportForTesting(): Promise<void> {
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { existsSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export function resolveRuntimeNativePath(fileName: string): string | null {
|
||||
// Bundled releases and workspace sources each own their native inputs.
|
||||
for (const directory of [
|
||||
path.join(moduleDir, 'native'),
|
||||
path.resolve(moduleDir, '..', '..', 'runtime', 'native'),
|
||||
]) {
|
||||
const candidate = path.join(directory, fileName);
|
||||
|
||||
if (existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -2,6 +2,12 @@ import { describe, expect, it } from 'vitest';
|
||||
import { fromHex, hexPreview, toHex, toHexUpper } from '../src/hex';
|
||||
|
||||
describe('hex', () => {
|
||||
it('encodes only the selected byte view', () => {
|
||||
const bytes = Uint8Array.of(0xff, 0x01, 0xab, 0xff);
|
||||
expect(toHex(bytes.subarray(1, 3))).toBe('01ab');
|
||||
expect(toHexUpper(Buffer.from(bytes).subarray(1, 3))).toBe('01AB');
|
||||
});
|
||||
|
||||
it('toHex / toHexUpper render bytes as zero-padded hex', () => {
|
||||
const b = Uint8Array.from([0x00, 0x0f, 0xa0, 0xff]);
|
||||
expect(toHex(b)).toBe('000fa0ff');
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,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'
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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());
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -138,7 +138,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
manager.getBridge('10001')!.detachPid(101);
|
||||
expect(() => manager.onPidDisconnected(101)).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
|
||||
);
|
||||
@@ -239,7 +239,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(manager.getSession('0')).toBeNull();
|
||||
expect(manager.getBridge('0')).toBeNull();
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
@@ -295,20 +295,20 @@ describe('BridgeManager PID ownership', () => {
|
||||
const first = makeSender();
|
||||
const second = makeSender();
|
||||
const lifecycle: string[] = [];
|
||||
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
|
||||
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
|
||||
manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
|
||||
manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
|
||||
|
||||
manager.onHookLogin(101, '10001', first.client);
|
||||
const oldBridge = manager.getSession('10001')!.bridge;
|
||||
const oldBridge = manager.getBridge('10001')!;
|
||||
const dispose = vi.spyOn(oldBridge, 'dispose');
|
||||
|
||||
manager.onHookLogin(101, '20002', second.client);
|
||||
|
||||
expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
expect(manager.getBridge('10001')).toBeNull();
|
||||
expect(oldBridge.hasPid(101)).toBe(false);
|
||||
expect(dispose).toHaveBeenCalledOnce();
|
||||
expect(manager.getSession('20002')!.bridge.hasPid(101)).toBe(true);
|
||||
expect(manager.getBridge('20002')!.hasPid(101)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps a multi-PID UIN alive and falls back to the remaining sender', async () => {
|
||||
@@ -316,11 +316,11 @@ describe('BridgeManager PID ownership', () => {
|
||||
const first = makeSender();
|
||||
const second = makeSender();
|
||||
const closed = vi.fn();
|
||||
manager.addSessionClosedListener(closed);
|
||||
manager.subscribeSessions({ closed: closed });
|
||||
|
||||
manager.onHookLogin(101, '10001', first.client);
|
||||
manager.onHookLogin(202, '10001', second.client);
|
||||
const bridge = manager.getSession('10001')!.bridge;
|
||||
const bridge = manager.getBridge('10001')!;
|
||||
|
||||
expect(bridge.activePid).toBe(202);
|
||||
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
|
||||
@@ -329,7 +329,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
|
||||
manager.onPidDisconnected(202);
|
||||
|
||||
expect(manager.getSession('10001')!.bridge).toBe(bridge);
|
||||
expect(manager.getBridge('10001')!).toBe(bridge);
|
||||
expect(bridge.activePid).toBe(101);
|
||||
expect(closed).not.toHaveBeenCalled();
|
||||
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
|
||||
@@ -337,7 +337,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
expect(testSends(second.sendPacket)).toHaveLength(1);
|
||||
|
||||
manager.onPidDisconnected(101);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
expect(manager.getBridge('10001')).toBeNull();
|
||||
expect(closed).toHaveBeenCalledOnce();
|
||||
expect(closed).toHaveBeenCalledWith('10001', bridge, 101);
|
||||
await expect(
|
||||
@@ -363,7 +363,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
manager.onHookLogin(202, '10001', second.client);
|
||||
manager.onPacket(packet(202, '10001'));
|
||||
manager.onPidDisconnected(202);
|
||||
const bridge = manager.getSession('10001')!.bridge;
|
||||
const bridge = manager.getBridge('10001')!;
|
||||
manager.onPidDisconnected(101);
|
||||
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
|
||||
|
||||
@@ -393,7 +393,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
const manager = new BridgeManager();
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
manager.onHookLogin(202, '10001', makeSender().client);
|
||||
const bridge = manager.getSession('10001')!.bridge;
|
||||
const bridge = manager.getBridge('10001')!;
|
||||
|
||||
expect(bridge.receiveHealthy).toBe(true);
|
||||
|
||||
@@ -414,13 +414,13 @@ describe('BridgeManager PID ownership', () => {
|
||||
const third = makeSender();
|
||||
const reboundFirst = makeSender();
|
||||
const started = vi.fn();
|
||||
manager.addSessionStartedListener(started);
|
||||
manager.subscribeSessions({ started: started });
|
||||
|
||||
manager.onHookLogin(101, '10001', first.client);
|
||||
manager.onHookLogin(202, '10001', second.client);
|
||||
manager.onHookLogin(303, '10001', third.client);
|
||||
manager.onHookLogin(101, '10001', reboundFirst.client);
|
||||
const bridge = manager.getSession('10001')!.bridge;
|
||||
const bridge = manager.getBridge('10001')!;
|
||||
|
||||
expect(started).toHaveBeenCalledOnce();
|
||||
expect(bridge.activePid).toBe(101);
|
||||
@@ -442,15 +442,15 @@ describe('BridgeManager PID ownership', () => {
|
||||
const manager = new BridgeManager();
|
||||
const sender = makeSender();
|
||||
const lifecycle: string[] = [];
|
||||
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
|
||||
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
|
||||
manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
|
||||
manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
|
||||
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
manager.onPacket(packet(101, '20002'));
|
||||
|
||||
expect(lifecycle).toEqual(['started:10001', 'closed:10001', 'started:20002']);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
const replacement = manager.getSession('20002')!.bridge;
|
||||
expect(manager.getBridge('10001')).toBeNull();
|
||||
const replacement = manager.getBridge('20002')!;
|
||||
expect(replacement.hasPid(101)).toBe(true);
|
||||
await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1]));
|
||||
expect(testSends(sender.sendPacket)).toHaveLength(1);
|
||||
@@ -462,24 +462,24 @@ describe('BridgeManager PID ownership', () => {
|
||||
const moving = makeSender();
|
||||
const rebound = makeSender();
|
||||
const lifecycle: string[] = [];
|
||||
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
|
||||
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
|
||||
manager.subscribeSessions({ started: (uin) => lifecycle.push(`started:${uin}`) });
|
||||
manager.subscribeSessions({ closed: (uin) => lifecycle.push(`closed:${uin}`) });
|
||||
|
||||
manager.onHookLogin(101, '10001', fallback.client);
|
||||
manager.onHookLogin(202, '10001', moving.client);
|
||||
const oldBridge = manager.getSession('10001')!.bridge;
|
||||
const oldBridge = manager.getBridge('10001')!;
|
||||
expect(oldBridge.activePid).toBe(202);
|
||||
|
||||
manager.onHookLogin(202, '20002', rebound.client);
|
||||
|
||||
expect(lifecycle).toEqual(['started:10001', 'started:20002']);
|
||||
expect(manager.getSession('10001')!.bridge).toBe(oldBridge);
|
||||
expect(manager.getBridge('10001')!).toBe(oldBridge);
|
||||
expect(oldBridge.hasPid(202)).toBe(false);
|
||||
expect(oldBridge.activePid).toBe(101);
|
||||
await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1]));
|
||||
expect(testSends(fallback.sendPacket)).toHaveLength(1);
|
||||
|
||||
const newBridge = manager.getSession('20002')!.bridge;
|
||||
const newBridge = manager.getBridge('20002')!;
|
||||
expect(newBridge.activePid).toBe(202);
|
||||
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
|
||||
expect(testSends(rebound.sendPacket)).toHaveLength(1);
|
||||
@@ -502,20 +502,20 @@ describe('BridgeManager PID ownership', () => {
|
||||
const reboundFirst = makeSender();
|
||||
const started = vi.fn();
|
||||
const closed = vi.fn();
|
||||
manager.addSessionStartedListener(started);
|
||||
manager.addSessionClosedListener(closed);
|
||||
manager.subscribeSessions({ started: started });
|
||||
manager.subscribeSessions({ closed: closed });
|
||||
|
||||
manager.onHookLogin(101, '10001', first.client);
|
||||
manager.onHookLogin(202, '20002', second.client);
|
||||
const targetBridge = manager.getSession('20002')!.bridge;
|
||||
const targetBridge = manager.getBridge('20002')!;
|
||||
|
||||
manager.onHookLogin(101, '20002', reboundFirst.client);
|
||||
|
||||
expect(started).toHaveBeenCalledTimes(2);
|
||||
expect(closed).toHaveBeenCalledOnce();
|
||||
expect(closed).toHaveBeenCalledWith('10001', expect.anything(), 101);
|
||||
expect(manager.getSession('10001')).toBeNull();
|
||||
expect(manager.getSession('20002')!.bridge).toBe(targetBridge);
|
||||
expect(manager.getBridge('10001')).toBeNull();
|
||||
expect(manager.getBridge('20002')!).toBe(targetBridge);
|
||||
expect(targetBridge.activePid).toBe(101);
|
||||
|
||||
manager.onPidDisconnected(101);
|
||||
@@ -533,8 +533,8 @@ describe('BridgeManager PID ownership', () => {
|
||||
const sender = makeSender();
|
||||
const started = vi.fn();
|
||||
const closed = vi.fn();
|
||||
manager.addSessionStartedListener(started);
|
||||
manager.addSessionClosedListener(closed);
|
||||
manager.subscribeSessions({ started: started });
|
||||
manager.subscribeSessions({ closed: closed });
|
||||
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
@@ -563,7 +563,7 @@ describe('BridgeManager PID ownership', () => {
|
||||
manager.onHookLogin(101, '10001', sender.client);
|
||||
|
||||
// Remove the connection without updating the manager's ownership index.
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
manager.getBridge('10001')!.detachPid(101);
|
||||
|
||||
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session',
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { BridgeManager } from '../src/bridge/manager';
|
||||
|
||||
describe('BridgeManager subscriptions', () => {
|
||||
let manager: BridgeManager;
|
||||
const sender = { sendPacket: vi.fn() } as never;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(IdentityService, 'openForUin').mockImplementation((uin) =>
|
||||
IdentityService.memory(uin),
|
||||
);
|
||||
manager = new BridgeManager();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await manager.dispose();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('unsubscribes both session edges without removing another observer', () => {
|
||||
const started = vi.fn();
|
||||
const closed = vi.fn();
|
||||
const peer = { started: vi.fn(), closed: vi.fn() };
|
||||
const unsubscribe = manager.subscribeSessions({ started, closed });
|
||||
manager.subscribeSessions(peer);
|
||||
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
unsubscribe();
|
||||
manager.onPidDisconnected(101);
|
||||
manager.onHookLogin(202, '20002', sender);
|
||||
|
||||
expect(started).toHaveBeenCalledOnce();
|
||||
expect(closed).not.toHaveBeenCalled();
|
||||
expect(peer.started).toHaveBeenCalledTimes(2);
|
||||
expect(peer.closed).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('keeps subscription handles independent when an observer is reused', () => {
|
||||
const listener = { started: vi.fn() };
|
||||
const unsubscribeFirst = manager.subscribeSessions(listener);
|
||||
const unsubscribeSecond = manager.subscribeSessions(listener);
|
||||
unsubscribeFirst();
|
||||
unsubscribeFirst();
|
||||
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
expect(listener.started).toHaveBeenCalledOnce();
|
||||
unsubscribeSecond();
|
||||
manager.onHookLogin(202, '20002', sender);
|
||||
expect(listener.started).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('applies listener changes to the next event while preserving dispatch order', () => {
|
||||
const seen: string[] = [];
|
||||
let unsubscribeSecond: () => void;
|
||||
manager.subscribeSessions({
|
||||
started: () => {
|
||||
seen.push('first');
|
||||
unsubscribeSecond();
|
||||
manager.subscribeSessions({ started: () => seen.push('later') });
|
||||
},
|
||||
});
|
||||
unsubscribeSecond = manager.subscribeSessions({ started: () => seen.push('second') });
|
||||
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
expect(seen).toEqual(['first', 'second']);
|
||||
seen.length = 0;
|
||||
manager.onHookLogin(202, '20002', sender);
|
||||
expect(seen).toEqual(['first', 'later']);
|
||||
});
|
||||
|
||||
it('releases its observers when disposed', async () => {
|
||||
const started = vi.fn();
|
||||
manager.subscribeSessions({ started });
|
||||
await manager.dispose();
|
||||
|
||||
manager.onHookLogin(101, '10001', sender);
|
||||
expect(started).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -6,10 +6,10 @@ describe('BridgeManager session subscriptions', () => {
|
||||
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);
|
||||
const offStarted = manager.subscribeSessions({ started });
|
||||
manager.subscribeSessions({ started });
|
||||
const offClosed = manager.subscribeSessions({ closed });
|
||||
manager.subscribeSessions({ closed });
|
||||
offStarted();
|
||||
offStarted();
|
||||
offClosed();
|
||||
@@ -25,8 +25,8 @@ describe('BridgeManager session subscriptions', () => {
|
||||
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.subscribeSessions({ started: () => offPeer() });
|
||||
const offPeer = manager.subscribeSessions({ started: peer });
|
||||
|
||||
manager.onHookLogin(4002, '12345', {} as never);
|
||||
manager.onHookLogin(4003, '23456', {} as never);
|
||||
|
||||
@@ -63,6 +63,28 @@ describe('notification lifecycle PID', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('detaches from session events when disposed and cannot be rebound afterward', () => {
|
||||
const online = vi.spyOn(notifications, 'handleOnline');
|
||||
const offline = vi.spyOn(notifications, 'handleOffline');
|
||||
notifications.dispose();
|
||||
notifications.bind(bridges);
|
||||
|
||||
bridges.onHookLogin(1001, '12345', sender);
|
||||
bridges.onPidDisconnected(1001);
|
||||
|
||||
expect(online).not.toHaveBeenCalled();
|
||||
expect(offline).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('replaces its existing binding instead of delivering each event twice', () => {
|
||||
const online = vi.spyOn(notifications, 'handleOnline');
|
||||
notifications.bind(bridges);
|
||||
|
||||
bridges.onHookLogin(1001, '12345', sender);
|
||||
|
||||
expect(online).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('retains the final detached PID through debounce and uses the new PID on recovery', async () => {
|
||||
bridges.onHookLogin(1001, '12345', sender);
|
||||
bridges.onHookLogin(2002, '12345', sender);
|
||||
@@ -71,7 +93,7 @@ describe('notification lifecycle PID', () => {
|
||||
expect(posts).toEqual([]);
|
||||
|
||||
bridges.onPidDisconnected(2002);
|
||||
expect(bridges.getSession('12345')).toBeNull();
|
||||
expect(bridges.getBridge('12345')).toBeNull();
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(resolveProcess).toHaveBeenNthCalledWith(1, '12345', 2002);
|
||||
|
||||
|
||||
@@ -7,6 +7,20 @@ import { comparableConnectionSnapshot } from '../src/webui/connection-snapshot';
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
describe('startConnectionDiffLoop', () => {
|
||||
it('treats an undefined snapshot as an established baseline', () => {
|
||||
vi.useFakeTimers();
|
||||
const bus = new StateBus();
|
||||
const publish = vi.spyOn(bus, 'publish');
|
||||
let snapshot: unknown = undefined;
|
||||
const handle = startConnectionDiffLoop({ bus, getSnapshot: () => snapshot });
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(publish).not.toHaveBeenCalled();
|
||||
snapshot = null;
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
@@ -19,6 +19,50 @@ describe('bindStateStream', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('joins concurrent initial snapshots for the same resource', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
let resolve!: (data: unknown) => void;
|
||||
const slow = new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
const snapshot = vi.fn((resource: StateResource) =>
|
||||
resource === 'processes' ? slow : resource,
|
||||
);
|
||||
const handle = bindStateStream({ bus, snapshot, send: (frame) => sent.push(frame) });
|
||||
const first = handle.sendAllInitial();
|
||||
const second = handle.sendAllInitial();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(snapshot).toHaveBeenCalledTimes(3);
|
||||
resolve('processes');
|
||||
await Promise.all([first, second]);
|
||||
expect(sent).toHaveLength(3);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('absorbs a scheduled publish into an initial snapshot without starting another request', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
let resolve!: (data: unknown) => void;
|
||||
const slow = new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
const snapshot = vi.fn((resource: StateResource) =>
|
||||
resource === 'processes' ? slow : resource,
|
||||
);
|
||||
const handle = bindStateStream({ bus, snapshot, send: (frame) => sent.push(frame) });
|
||||
bus.publish('processes');
|
||||
const initial = handle.sendAllInitial();
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
expect(snapshot).toHaveBeenCalledTimes(3);
|
||||
resolve('fresh');
|
||||
await initial;
|
||||
expect(sent.filter((frame) => frame.resource === 'processes')).toEqual([
|
||||
{ resource: 'processes', data: 'fresh' },
|
||||
]);
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('sendAllInitial emits one frame per resource with the snapshot data', async () => {
|
||||
const bus = new StateBus();
|
||||
const sent: CapturedFrame[] = [];
|
||||
|
||||
@@ -4,15 +4,15 @@ 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();
|
||||
it('keeps a replacement wiring independent of its disposed predecessor', async () => {
|
||||
const old = new BridgeManager();
|
||||
const current = new BridgeManager();
|
||||
const listener = vi.fn();
|
||||
const previousWiring = createStateWiring(old);
|
||||
previousWiring.bus.subscribe(listener);
|
||||
previousWiring.dispose();
|
||||
const wiring = createStateWiring(current);
|
||||
wiring.bus.subscribe(listener);
|
||||
wiring.bindBridgeManager(old);
|
||||
wiring.bindBridgeManager(current);
|
||||
wiring.bindBridgeManager(current);
|
||||
|
||||
old.onHookLogin(4100, '12345', {} as never);
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
@@ -24,15 +24,13 @@ describe('createStateWiring', () => {
|
||||
await current.dispose();
|
||||
});
|
||||
|
||||
it('unsubscribes on disposal and does not bind again', async () => {
|
||||
const wiring = createStateWiring();
|
||||
it('unsubscribes on disposal before another account starts', async () => {
|
||||
const bm = new BridgeManager();
|
||||
const subscribe = vi.spyOn(bm, 'addSessionStartedListener');
|
||||
const subscribe = vi.spyOn(bm, 'subscribeSessions');
|
||||
const wiring = createStateWiring(bm);
|
||||
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();
|
||||
@@ -40,8 +38,19 @@ describe('createStateWiring', () => {
|
||||
await bm.dispose();
|
||||
});
|
||||
|
||||
it('releases its session subscription when disposed', () => {
|
||||
const unsubscribe = vi.fn();
|
||||
const source = { subscribeSessions: vi.fn(() => unsubscribe) };
|
||||
const wiring = createStateWiring(source);
|
||||
|
||||
wiring.dispose();
|
||||
|
||||
expect(source.subscribeSessions).toHaveBeenCalledOnce();
|
||||
expect(unsubscribe).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('provides a fresh StateBus and an onSessionsChanged that publishes "processes"', () => {
|
||||
const wiring = createStateWiring();
|
||||
const wiring = createStateWiring(new BridgeManager());
|
||||
expect(wiring.bus).toBeInstanceOf(StateBus);
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
@@ -50,9 +59,8 @@ describe('createStateWiring', () => {
|
||||
});
|
||||
|
||||
it('binds a BridgeManager so session-started publishes both "qq-list" and "connections"', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
const wiring = createStateWiring(bm);
|
||||
const seen: string[] = [];
|
||||
wiring.bus.subscribe((r) => seen.push(r));
|
||||
|
||||
@@ -63,9 +71,8 @@ describe('createStateWiring', () => {
|
||||
});
|
||||
|
||||
it('publishes "qq-list" + "connections" on session-closed', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
const wiring = createStateWiring(bm);
|
||||
bm.onHookLogin(4242, '12345', {} as never);
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
@@ -80,9 +87,8 @@ describe('createStateWiring', () => {
|
||||
});
|
||||
|
||||
it('dispose() latches so later Hook/Bridge edges publish nothing', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
const wiring = createStateWiring(bm);
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
|
||||
@@ -98,15 +104,14 @@ describe('createStateWiring', () => {
|
||||
});
|
||||
|
||||
it('survives a BridgeManager listener throw — the OTHER listeners on the same BridgeManager keep working', () => {
|
||||
const wiring = createStateWiring();
|
||||
const bm = new BridgeManager();
|
||||
wiring.bindBridgeManager(bm);
|
||||
const wiring = createStateWiring(bm);
|
||||
|
||||
// A peer subscriber (e.g. OneBotManager) added AFTER state-wiring throws.
|
||||
const peer = vi.fn(() => {
|
||||
throw new Error('peer down');
|
||||
});
|
||||
bm.addSessionStartedListener(peer);
|
||||
bm.subscribeSessions({ started: peer });
|
||||
|
||||
const sub = vi.fn();
|
||||
wiring.bus.subscribe(sub);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"allowImportingTsExtensions": true,
|
||||
// Tests live outside src/ so we don't pin rootDir; tsc --noEmit doesn't write output anyway.
|
||||
"types": ["node", "vitest/globals"],
|
||||
"paths": {
|
||||
|
||||
@@ -53,8 +53,7 @@ function lite(a: CatalogAction) {
|
||||
const DOCS_TOOLS: Tool[] = [
|
||||
{
|
||||
name: 'list_actions',
|
||||
description:
|
||||
'列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读/是否为 Stream Action)。',
|
||||
description: '列出 OneBot action,支持按分类过滤。返回名称、摘要、别名及执行类型。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -66,8 +65,7 @@ const DOCS_TOOLS: Tool[] = [
|
||||
},
|
||||
{
|
||||
name: 'get_action',
|
||||
description:
|
||||
'获取某个 OneBot action 的完整文档:摘要、参数表、跨字段约束、返回、是否只读,以及可直接用于构造调用的参数 JSON Schema(inputSchema)。',
|
||||
description: '获取 action 文档、参数 JSON Schema、约束和返回类型。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string', description: 'action 名(接受别名)' } },
|
||||
@@ -78,7 +76,7 @@ const DOCS_TOOLS: Tool[] = [
|
||||
},
|
||||
{
|
||||
name: 'search_actions',
|
||||
description: '按关键字模糊搜索 action(匹配名称 / 摘要 / 别名)。返回轻量索引。',
|
||||
description: '按名称、摘要或别名搜索 action。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { query: { type: 'string', description: '关键字' } },
|
||||
@@ -291,10 +289,6 @@ async function execute(
|
||||
return asError('execution.input_file 仅可用于 upload_file_stream。');
|
||||
}
|
||||
|
||||
if (inputFile && !cat.stream) {
|
||||
return asError(`${action} 不是 Stream Action,不能使用 execution.input_file。`);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = cat.stream
|
||||
? await ctx.client.callStream(action, params, {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { fromHex, toHex } from '@snowluma/common/hex';
|
||||
import { mapWithConcurrency } from '@snowluma/common/concurrency';
|
||||
import { positiveIntEnv } from '@snowluma/common/env';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
@@ -3275,7 +3276,7 @@ export const actions = [
|
||||
);
|
||||
}
|
||||
|
||||
const body = hexToBytes(p.data);
|
||||
const body = fromHex(p.data);
|
||||
const result = await ctx.bridge.sendRawPacket(p.cmd, body);
|
||||
|
||||
if (!result.success) {
|
||||
@@ -3286,7 +3287,7 @@ export const actions = [
|
||||
return okResponse(null);
|
||||
}
|
||||
|
||||
const respHex = result.responseData ? bytesToHex(result.responseData) : '';
|
||||
const respHex = result.responseData ? toHex(result.responseData) : '';
|
||||
return okResponse(respHex);
|
||||
},
|
||||
}),
|
||||
@@ -3577,21 +3578,6 @@ async function fetchFilteredGroupRequests(ctx: ApiActionContext) {
|
||||
return ctx.bridge.apis.contacts.fetchGroupRequests(true);
|
||||
}
|
||||
|
||||
function hexToBytes(hex: string): Uint8Array {
|
||||
const out = new Uint8Array(hex.length / 2);
|
||||
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
function bytesToHex(buf: Buffer | Uint8Array): string {
|
||||
const arr = buf instanceof Buffer ? buf : Buffer.from(buf);
|
||||
return arr.toString('hex');
|
||||
}
|
||||
|
||||
function parseDownloadHeaders(headers: unknown): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
// Stream API file actions (#163) — NapCat-compatible chunked file transfer.
|
||||
//
|
||||
// upload_file_stream: a client (possibly on another machine) pushes a file to
|
||||
@@ -531,7 +532,3 @@ export const __test = {
|
||||
MAX_CONCURRENT_STREAMS,
|
||||
MAX_CHUNKS,
|
||||
};
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -287,7 +287,7 @@ export class GroupRequestPoller {
|
||||
this.timer = null;
|
||||
this.scheduledTask = this.runScheduledPoll();
|
||||
}, this.intervalMs);
|
||||
this.timer.unref?.();
|
||||
this.timer.unref();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,7 +534,7 @@ function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
timer.unref?.();
|
||||
timer.unref();
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -8,9 +8,6 @@ const log = createLogger('OneBot');
|
||||
|
||||
interface CachedRKey {
|
||||
value: string;
|
||||
type: number;
|
||||
createTime: number;
|
||||
ttlSeconds: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
@@ -61,72 +58,50 @@ export class RKeyCache {
|
||||
);
|
||||
}
|
||||
|
||||
async resolveImageUrl(
|
||||
resolveImageUrl(
|
||||
bridge: BridgeInterface,
|
||||
element: MessageElement,
|
||||
isGroup: boolean,
|
||||
): Promise<string> {
|
||||
const url = element.imageUrl ?? '';
|
||||
|
||||
if (!urlNeedsRKey(url)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
// The rkey scene must follow the IMAGE's own upload context, not the
|
||||
// message currently carrying it. A c2c image forwarded into a group
|
||||
// keeps its original c2c fileid/appid (1406); signing it with the
|
||||
// group rkey just because the forward node looks like a group message
|
||||
// yields `invalid rkey` on download. So derive the scene from the
|
||||
// appid baked into the URL, and only fall back to `isGroup` when the
|
||||
// URL carries no recognised appid (legacy gchat / unknown shapes).
|
||||
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
|
||||
// 1407 → group).
|
||||
const primaryType =
|
||||
// Forwarded images retain their upload scene, encoded by appid in the URL.
|
||||
const type =
|
||||
imageRKeyTypeFromUrl(url) ??
|
||||
(isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
|
||||
if (!rkey) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
return this.resolveUrl(bridge, url, type);
|
||||
}
|
||||
|
||||
async resolveMediaUrl(
|
||||
resolveMediaUrl(
|
||||
bridge: BridgeInterface,
|
||||
element: MessageElement,
|
||||
isGroup: boolean,
|
||||
): Promise<string> {
|
||||
const url = element.url ?? '';
|
||||
let type: number;
|
||||
|
||||
if (!url || !urlNeedsRKey(url)) {
|
||||
if (element.type === 'video') {
|
||||
type = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
|
||||
} else if (element.type === 'record') {
|
||||
type = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
|
||||
} else {
|
||||
type = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
}
|
||||
|
||||
return this.resolveUrl(bridge, element.url ?? '', type);
|
||||
}
|
||||
|
||||
private async resolveUrl(bridge: BridgeInterface, url: string, type: number): Promise<string> {
|
||||
if (!urlNeedsRKey(url)) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const mediaType = element.type;
|
||||
let primaryType: number;
|
||||
|
||||
if (mediaType === 'video') {
|
||||
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
|
||||
} else if (mediaType === 'record') {
|
||||
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
|
||||
} else {
|
||||
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
|
||||
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
}
|
||||
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
const rkey = await this.findRKeyForType(bridge, type);
|
||||
|
||||
if (!rkey) {
|
||||
return url;
|
||||
}
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
|
||||
return url + separator + encodeURIComponent(cleanRKey);
|
||||
return url + separator + encodeURIComponent(stripRKeyPrefix(rkey));
|
||||
}
|
||||
|
||||
private updateCache(rkeys: DownloadRKeyInfo[]): void {
|
||||
@@ -141,9 +116,6 @@ export class RKeyCache {
|
||||
const ttl = rk.ttlSeconds || 3600;
|
||||
this.cache.set(rk.type, {
|
||||
value: rk.rkey,
|
||||
type: rk.type,
|
||||
createTime: rk.createTime,
|
||||
ttlSeconds: rk.ttlSeconds,
|
||||
expiresAt: baseTime + ttl,
|
||||
});
|
||||
}
|
||||
@@ -224,10 +196,6 @@ export class RKeyCache {
|
||||
|
||||
const inflight = this.refreshInflight;
|
||||
|
||||
if (!inflight) {
|
||||
return;
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS);
|
||||
@@ -236,9 +204,7 @@ export class RKeyCache {
|
||||
try {
|
||||
await Promise.race([inflight, timeout]);
|
||||
} finally {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,7 +261,7 @@ export class RKeyCache {
|
||||
}
|
||||
|
||||
private setFallbackRkey(type: number, value: string, expiresAt: number): void {
|
||||
this.cache.set(type, { value, type, createTime: 0, ttlSeconds: 0, expiresAt });
|
||||
this.cache.set(type, { value, expiresAt });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -855,7 +855,7 @@ export class OneBotInstance {
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
this.dispatchEvent(this.makeHeartbeatEvent());
|
||||
}, OneBotInstance.HEARTBEAT_INTERVAL);
|
||||
this.heartbeatTimer.unref?.();
|
||||
this.heartbeatTimer.unref();
|
||||
}
|
||||
|
||||
private makeHeartbeatEvent(): JsonObject {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import type { BridgeInterface, BridgeSessionSource } from '@snowluma/core/bridge-interface';
|
||||
import { loadOneBotConfig, OneBotConfigValidationError } from './config';
|
||||
import { loadGlobalSettings } from './global-config';
|
||||
import { OneBotInstance } from './instance';
|
||||
@@ -134,10 +133,7 @@ export class OneBotManager {
|
||||
instances?: Set<OneBotInstance>;
|
||||
}> = [];
|
||||
|
||||
private readonly pendingStarts = new Map<
|
||||
string,
|
||||
{ bridge: BridgeInterface; cancelled: boolean }
|
||||
>();
|
||||
private readonly pendingStarts = new Map<string, { bridge: BridgeInterface }>();
|
||||
|
||||
private readonly databaseMigrations = new Map<
|
||||
string,
|
||||
@@ -145,8 +141,6 @@ export class OneBotManager {
|
||||
bridge: BridgeInterface;
|
||||
task: DatabaseMigrationTask;
|
||||
state: AccountDatabaseMigration;
|
||||
ready: boolean;
|
||||
cancelled: boolean;
|
||||
rowsPerSecond: number | null;
|
||||
retryTimer: NodeJS.Timeout | null;
|
||||
}
|
||||
@@ -157,6 +151,7 @@ export class OneBotManager {
|
||||
|
||||
private disposePromise: Promise<void> | null = null;
|
||||
private disposed = false;
|
||||
private unsubscribeSessions: (() => void) | null = null;
|
||||
private readonly sessionReleaseDeadlineMs: number;
|
||||
|
||||
constructor(options: OneBotManagerOptions = {}) {
|
||||
@@ -187,13 +182,17 @@ export class OneBotManager {
|
||||
new OneBotInstance(uin, bridge, config, globalSettings));
|
||||
}
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => {
|
||||
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge));
|
||||
});
|
||||
bind(bridgeManager: BridgeSessionSource): void {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
bridgeManager.addSessionClosedListener((uin) => {
|
||||
this.onSessionClosed(uin);
|
||||
this.unsubscribeSessions?.();
|
||||
this.unsubscribeSessions = bridgeManager.subscribeSessions({
|
||||
started: (uin, bridge) => {
|
||||
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge));
|
||||
},
|
||||
closed: (uin) => this.onSessionClosed(uin),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -208,22 +207,16 @@ export class OneBotManager {
|
||||
/** Live OneBot adapter status for active accounts plus failed retiring
|
||||
* generations. A zombie that still owns a port must remain observable. */
|
||||
getConnectionStatuses(): AccountConnections[] {
|
||||
const visible = [...this.instances.values()];
|
||||
|
||||
for (const instance of this.retiringInstances) {
|
||||
if (!visible.includes(instance)) {
|
||||
visible.push(instance);
|
||||
}
|
||||
}
|
||||
|
||||
const connections = visible.map((instance) => ({
|
||||
uin: instance.uin,
|
||||
nickname: instance.nickname,
|
||||
adapters: instance.getConnectionStatuses(),
|
||||
...(this.databaseMigrations.get(instance.uin)?.state
|
||||
? { databaseMigration: this.databaseMigrations.get(instance.uin)?.state }
|
||||
: {}),
|
||||
}));
|
||||
const visible = new Set([...this.instances.values(), ...this.retiringInstances]);
|
||||
const connections = [...visible].map((instance) => {
|
||||
const migration = this.databaseMigrations.get(instance.uin);
|
||||
return {
|
||||
uin: instance.uin,
|
||||
nickname: instance.nickname,
|
||||
adapters: instance.getConnectionStatuses(),
|
||||
...(migration ? { databaseMigration: migration.state } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
const activeUins = new Set(this.instances.keys());
|
||||
|
||||
@@ -288,10 +281,13 @@ export class OneBotManager {
|
||||
}
|
||||
|
||||
this.disposed = true;
|
||||
this.unsubscribeSessions?.();
|
||||
this.unsubscribeSessions = null;
|
||||
|
||||
for (const migration of this.databaseMigrations.values()) {
|
||||
migration.cancelled = true;
|
||||
const migrations = [...this.databaseMigrations.values()];
|
||||
this.databaseMigrations.clear();
|
||||
|
||||
for (const migration of migrations) {
|
||||
if (migration.retryTimer) {
|
||||
clearTimeout(migration.retryTimer);
|
||||
}
|
||||
@@ -299,8 +295,6 @@ export class OneBotManager {
|
||||
migration.task.cancel();
|
||||
}
|
||||
|
||||
this.databaseMigrations.clear();
|
||||
|
||||
for (const instance of this.instances.values()) {
|
||||
this.retiringInstances.add(instance);
|
||||
}
|
||||
@@ -389,7 +383,7 @@ export class OneBotManager {
|
||||
const retiring = [...this.retiringInstances].filter((instance) => instance.uin === uin);
|
||||
|
||||
if (retiring.length > 0) {
|
||||
const pending = { bridge, cancelled: false };
|
||||
const pending = { bridge };
|
||||
this.pendingStarts.set(uin, pending);
|
||||
this.trackLifecycle(
|
||||
`session handoff UIN=${uin}`,
|
||||
@@ -410,16 +404,21 @@ export class OneBotManager {
|
||||
bridge,
|
||||
task: this.createDatabaseMigrationTask(uin),
|
||||
state: preparingMigrationState(),
|
||||
ready: false,
|
||||
cancelled: false,
|
||||
rowsPerSecond: null as number | null,
|
||||
retryTimer: null as NodeJS.Timeout | null,
|
||||
};
|
||||
this.databaseMigrations.set(uin, migration);
|
||||
|
||||
const startTask = (): void => {
|
||||
const task = migration.task;
|
||||
const isCurrent = () =>
|
||||
this.databaseMigrations.get(uin) === migration &&
|
||||
migration.task === task &&
|
||||
migration.state.phase !== 'failed' &&
|
||||
migration.state.phase !== 'complete';
|
||||
|
||||
const handleFailure = (error: unknown, stage = 'database migration'): void => {
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -429,7 +428,6 @@ export class OneBotManager {
|
||||
migration.state = {
|
||||
...migration.state,
|
||||
phase: 'failed',
|
||||
usable: migration.ready,
|
||||
estimatedRemainingSeconds: null,
|
||||
error: `${label}:${detail}${retryable ? ';将自动重试' : ';请修正配置后重启'}`,
|
||||
};
|
||||
@@ -441,7 +439,7 @@ export class OneBotManager {
|
||||
error instanceof Error ? (error.stack ?? error.message) : String(error),
|
||||
);
|
||||
|
||||
migration.task.cancel();
|
||||
task.cancel();
|
||||
|
||||
if (!retryable || migration.retryTimer) {
|
||||
return;
|
||||
@@ -450,23 +448,23 @@ export class OneBotManager {
|
||||
migration.retryTimer = setTimeout(() => {
|
||||
migration.retryTimer = null;
|
||||
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
|
||||
if (this.databaseMigrations.get(uin) !== migration) {
|
||||
return;
|
||||
}
|
||||
|
||||
migration.task = this.createDatabaseMigrationTask(uin);
|
||||
migration.state = migration.ready
|
||||
migration.state = migration.state.usable
|
||||
? { ...migration.state, phase: 'migrating', usable: true, error: undefined }
|
||||
: preparingMigrationState();
|
||||
startTask();
|
||||
}, 5_000);
|
||||
migration.retryTimer.unref?.();
|
||||
migration.retryTimer.unref();
|
||||
};
|
||||
|
||||
try {
|
||||
migration.task.start({
|
||||
task.start({
|
||||
onReady: () => {
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -477,7 +475,6 @@ export class OneBotManager {
|
||||
return;
|
||||
}
|
||||
|
||||
migration.ready = true;
|
||||
migration.state = {
|
||||
...migration.state,
|
||||
phase: 'migrating',
|
||||
@@ -486,14 +483,14 @@ export class OneBotManager {
|
||||
};
|
||||
|
||||
try {
|
||||
migration.task.beginMigration();
|
||||
task.beginMigration();
|
||||
} catch (error) {
|
||||
handleFailure(error);
|
||||
}
|
||||
},
|
||||
|
||||
onProgress: (status, elapsedMs) => {
|
||||
if (migration.cancelled || this.databaseMigrations.get(uin) !== migration) {
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -511,7 +508,7 @@ export class OneBotManager {
|
||||
migration.state = migrationPublicState(status, migration.rowsPerSecond);
|
||||
|
||||
if (status.phase === 'complete') {
|
||||
migration.task.cancel();
|
||||
task.cancel();
|
||||
}
|
||||
},
|
||||
|
||||
@@ -628,26 +625,19 @@ export class OneBotManager {
|
||||
const migration = this.databaseMigrations.get(uin);
|
||||
|
||||
if (migration) {
|
||||
migration.cancelled = true;
|
||||
this.databaseMigrations.delete(uin);
|
||||
|
||||
if (migration.retryTimer) {
|
||||
clearTimeout(migration.retryTimer);
|
||||
}
|
||||
|
||||
migration.task.cancel();
|
||||
this.databaseMigrations.delete(uin);
|
||||
}
|
||||
|
||||
const instance = this.instances.get(uin);
|
||||
|
||||
if (!instance) {
|
||||
const pending = this.pendingStarts.get(uin);
|
||||
|
||||
if (pending) {
|
||||
pending.cancelled = true;
|
||||
this.pendingStarts.delete(uin);
|
||||
}
|
||||
|
||||
this.pendingStarts.delete(uin);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -678,13 +668,13 @@ export class OneBotManager {
|
||||
|
||||
private async releaseRetiringInstance(
|
||||
uin: string,
|
||||
pending: { bridge: BridgeInterface; cancelled: boolean },
|
||||
pending: { bridge: BridgeInterface },
|
||||
instance: OneBotInstance,
|
||||
): Promise<void> {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<'timeout'>((resolve) => {
|
||||
timer = setTimeout(() => resolve('timeout'), this.sessionReleaseDeadlineMs);
|
||||
timer.unref?.();
|
||||
timer.unref();
|
||||
});
|
||||
|
||||
// Map rejection here so a dispose() that fails after the deadline still
|
||||
@@ -704,7 +694,7 @@ export class OneBotManager {
|
||||
);
|
||||
|
||||
try {
|
||||
instance.forceRelease?.();
|
||||
instance.forceRelease();
|
||||
} catch (error) {
|
||||
log.error(
|
||||
'forced session release failed: UIN=%s: %s',
|
||||
@@ -734,7 +724,7 @@ export class OneBotManager {
|
||||
|
||||
private async finishRetiringBeforeStart(
|
||||
uin: string,
|
||||
pending: { bridge: BridgeInterface; cancelled: boolean },
|
||||
pending: { bridge: BridgeInterface },
|
||||
retiring: OneBotInstance[],
|
||||
): Promise<void> {
|
||||
for (const instance of retiring) {
|
||||
@@ -748,7 +738,7 @@ export class OneBotManager {
|
||||
|
||||
this.pendingStarts.delete(uin);
|
||||
|
||||
if (pending.cancelled || this.disposed) {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ export function waitPttTransText(key: string, timeoutMs: number): Promise<string
|
||||
|
||||
reject(new Error('语音转文字超时(未收到结果推送)'));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
timer.unref();
|
||||
pending.set(key, { resolve, reject, timer });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { ApiHandler } from '../api-handler';
|
||||
import {
|
||||
@@ -220,7 +221,3 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
this.onConfigReplaced(next);
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { assertValidOneBotConfig } from '../config';
|
||||
import { buildDispatchPayload } from '../event-filter';
|
||||
import type {
|
||||
@@ -67,11 +68,9 @@ export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, ManagedAdapter>();
|
||||
private readonly factory: NetworkAdapterFactory | null;
|
||||
private operationTail: Promise<void> = Promise.resolve();
|
||||
private acceptingReconciles = true;
|
||||
private acceptingEvents = true;
|
||||
private accepting = true;
|
||||
private readonly inFlightEmits = new Set<Promise<void>>();
|
||||
private shutdownPromise: Promise<NetworkShutdownResult> | null = null;
|
||||
private shutdownResult: NetworkShutdownResult | null = null;
|
||||
|
||||
/** Debug-stream taps — notified for every emitted event regardless of adapter
|
||||
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
|
||||
@@ -92,7 +91,7 @@ export class OneBotNetworkManager {
|
||||
/** Test/embedding seam for pre-built adapters. Production topology changes
|
||||
* go through reconcile(), which refuses duplicate names. */
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
if (!this.acceptingReconciles) {
|
||||
if (!this.accepting) {
|
||||
throw new Error('network manager is shutting down');
|
||||
}
|
||||
|
||||
@@ -163,17 +162,16 @@ export class OneBotNetworkManager {
|
||||
reconcile(config: OneBotConfig): Promise<NetworkReconcileResult> {
|
||||
const desired = this.compileDesiredPlan(config);
|
||||
|
||||
if (!this.acceptingReconciles) {
|
||||
if (!this.accepting) {
|
||||
return Promise.reject(new Error('network manager is shutting down'));
|
||||
}
|
||||
|
||||
return this.enqueue(() => this.reconcileNow(desired));
|
||||
}
|
||||
|
||||
/** Compatibility seam for tests/pre-built adapters. Opens sequentially and
|
||||
* reports each failure instead of hiding it in a detached Promise. */
|
||||
/** Open registered adapters in order and report each failure. */
|
||||
openAll(): Promise<NetworkReconcileResult> {
|
||||
if (!this.acceptingReconciles) {
|
||||
if (!this.accepting) {
|
||||
return Promise.reject(new Error('network manager is shutting down'));
|
||||
}
|
||||
|
||||
@@ -195,7 +193,7 @@ export class OneBotNetworkManager {
|
||||
}
|
||||
|
||||
closeOne(name: string): Promise<void> {
|
||||
if (!this.acceptingReconciles) {
|
||||
if (!this.accepting) {
|
||||
return Promise.reject(new Error('network manager is shutting down'));
|
||||
}
|
||||
|
||||
@@ -214,16 +212,11 @@ export class OneBotNetworkManager {
|
||||
/** Ordered, idempotent shutdown. Reconcile calls made before shutdown finish
|
||||
* first; calls made after shutdown is requested fail immediately. */
|
||||
shutdown(): Promise<NetworkShutdownResult> {
|
||||
if (this.shutdownResult?.closed) {
|
||||
return Promise.resolve(this.shutdownResult);
|
||||
}
|
||||
|
||||
if (this.shutdownPromise) {
|
||||
return this.shutdownPromise;
|
||||
}
|
||||
|
||||
this.acceptingReconciles = false;
|
||||
this.acceptingEvents = false;
|
||||
this.accepting = false;
|
||||
const attempt = this.enqueue(async () => {
|
||||
const errors: NetworkApplyError[] = [];
|
||||
const dispatches = await Promise.allSettled([...this.inFlightEmits]);
|
||||
@@ -232,7 +225,7 @@ export class OneBotNetworkManager {
|
||||
if (dispatch.status === 'rejected') {
|
||||
log.error(
|
||||
'in-flight event dispatch failed during shutdown: %s',
|
||||
errMessage(dispatch.reason),
|
||||
errorMessage(dispatch.reason),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -255,8 +248,9 @@ export class OneBotNetworkManager {
|
||||
this.shutdownPromise = attempt;
|
||||
void attempt.then(
|
||||
(result) => {
|
||||
this.shutdownResult = result.closed ? result : null;
|
||||
this.shutdownPromise = null;
|
||||
if (!result.closed) {
|
||||
this.shutdownPromise = null;
|
||||
}
|
||||
},
|
||||
() => {
|
||||
this.shutdownPromise = null;
|
||||
@@ -265,27 +259,22 @@ export class OneBotNetworkManager {
|
||||
return attempt;
|
||||
}
|
||||
|
||||
closeAll(): Promise<NetworkShutdownResult> {
|
||||
return this.shutdown();
|
||||
}
|
||||
|
||||
/** Best-effort immediate release. Does not wait for the operation queue,
|
||||
* in-flight dispatches, or peer close handshakes. */
|
||||
forceRelease(): void {
|
||||
this.acceptingReconciles = false;
|
||||
this.acceptingEvents = false;
|
||||
this.accepting = false;
|
||||
|
||||
for (const { adapter } of this.adapters.values()) {
|
||||
try {
|
||||
adapter.forceClose();
|
||||
} catch (error) {
|
||||
log.error('forced adapter release failed: %s', errMessage(error));
|
||||
log.error('forced adapter release failed: %s', errorMessage(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emitEvent(event: JsonObject): Promise<void> {
|
||||
if (!this.acceptingEvents) {
|
||||
if (!this.accepting) {
|
||||
return Promise.reject(
|
||||
new Error('network manager is shutting down; event dispatch rejected'),
|
||||
);
|
||||
@@ -313,7 +302,7 @@ export class OneBotNetworkManager {
|
||||
try {
|
||||
cb(event);
|
||||
} catch (error) {
|
||||
log.warn('debug subscriber error: %s', errMessage(error));
|
||||
log.warn('debug subscriber error: %s', errorMessage(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -337,7 +326,7 @@ export class OneBotNetworkManager {
|
||||
Promise.resolve()
|
||||
.then(() => adapter.onEvent(event, payload))
|
||||
.catch((error) => {
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error));
|
||||
log.warn('adapter [%s] onEvent error: %s', adapter.name, errorMessage(error));
|
||||
log.trace(() => [
|
||||
'report_target_failed target=%s error=%s',
|
||||
adapter.name,
|
||||
@@ -549,7 +538,7 @@ export class OneBotNetworkManager {
|
||||
name,
|
||||
kind,
|
||||
phase,
|
||||
message: errMessage(error),
|
||||
message: errorMessage(error),
|
||||
at: Date.now(),
|
||||
...(restored === undefined ? {} : { restored }),
|
||||
};
|
||||
@@ -575,7 +564,3 @@ export class OneBotNetworkManager {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function errMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -46,11 +46,7 @@ export function rawDataToString(
|
||||
return Buffer.from(new Uint8Array(raw)).toString('utf8');
|
||||
}
|
||||
|
||||
if (ArrayBuffer.isView(raw)) {
|
||||
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
|
||||
}
|
||||
|
||||
return '';
|
||||
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
|
||||
}
|
||||
|
||||
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
|
||||
@@ -156,7 +152,7 @@ export function startHeartbeat(
|
||||
onDead();
|
||||
}
|
||||
}, opts.intervalMs);
|
||||
timer.unref?.();
|
||||
timer.unref();
|
||||
|
||||
function stop(): void {
|
||||
if (stopped) {
|
||||
@@ -165,8 +161,8 @@ export function startHeartbeat(
|
||||
|
||||
stopped = true;
|
||||
clearInterval(timer);
|
||||
socket.off?.('pong', onActivity);
|
||||
socket.off?.('message', onActivity);
|
||||
socket.off('pong', onActivity);
|
||||
socket.off('message', onActivity);
|
||||
}
|
||||
|
||||
return stop;
|
||||
|
||||
@@ -26,8 +26,6 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
// Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it
|
||||
// immediately instead of waiting for the deferred 'close' event. The per-socket
|
||||
@@ -42,37 +40,23 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) {
|
||||
if (this.isEnabled || !this.willEnable(this.config)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.config.enabled === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.config.url) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.explicitlyClosed = false;
|
||||
this.isEnabled = true;
|
||||
|
||||
try {
|
||||
this.connect();
|
||||
this.acceptingActions = true;
|
||||
this.clearApplyFailure();
|
||||
} catch (error) {
|
||||
this.isEnabled = false;
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.recordTransportFailure(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
override forceClose(): void {
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
@@ -91,8 +75,6 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
@@ -156,7 +138,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
|
||||
private connect(): void {
|
||||
if (this.explicitlyClosed) {
|
||||
if (!this.isEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -200,7 +182,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
socket,
|
||||
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
|
||||
() => {
|
||||
if (this.explicitlyClosed || !this.isEnabled) {
|
||||
if (!this.isEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -265,7 +247,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
this.socket = null;
|
||||
this.connected = false;
|
||||
|
||||
if (this.explicitlyClosed || !this.isEnabled) {
|
||||
if (!this.isEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -287,7 +269,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.explicitlyClosed) {
|
||||
if (!this.isEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -298,13 +280,13 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
const timer = setTimeout(() => {
|
||||
this.reconnectTimer = null;
|
||||
|
||||
if (this.explicitlyClosed || !this.isEnabled) {
|
||||
if (!this.isEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.connect();
|
||||
}, interval);
|
||||
timer.unref?.();
|
||||
timer.unref();
|
||||
this.reconnectTimer = timer;
|
||||
}
|
||||
|
||||
@@ -338,7 +320,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): void {
|
||||
if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) {
|
||||
if (!this.isEnabled || this.ctx.api.isAcceptingActions === false) {
|
||||
this.log.warn('[%s] rejected inbound action while adapter is closing', this.name);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
@@ -254,10 +255,6 @@ function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT';
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function assertManagedDirectory(directory: string, stat: fs.Stats): void {
|
||||
if (stat.isSymbolicLink()) {
|
||||
throw new Error(`managed stream directory must not be a symbolic link: ${directory}`);
|
||||
|
||||
@@ -199,6 +199,44 @@ describe('RKeyCache.resolveImageUrl', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('RKeyCache.resolveMediaUrl', () => {
|
||||
it.each([
|
||||
['video', false, 12],
|
||||
['video', true, 22],
|
||||
['record', false, 14],
|
||||
['record', true, 24],
|
||||
['file', false, 10],
|
||||
['file', true, 20],
|
||||
] as const)('signs %s media (group=%s) with rkey type %s', async (type, isGroup, expected) => {
|
||||
const { bridge } = makeBridge(async () =>
|
||||
[10, 20, 12, 22, 14, 24].map((type) => ({
|
||||
rkey: `?rkey=key/${type}`,
|
||||
type,
|
||||
ttlSeconds: 3600,
|
||||
createTime: nowSec(),
|
||||
})),
|
||||
);
|
||||
const cache = new RKeyCache();
|
||||
const url = 'https://multimedia.nt.qq.com.cn/download?fileid=MEDIA';
|
||||
expect(await cache.resolveMediaUrl(bridge as never, { type, url }, isGroup)).toBe(
|
||||
`${url}&rkey=key%2F${expected}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves signed, unrelated, and absent URLs without fetching', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
for (const url of ['', 'https://example.com/video', `${NT_IMAGE_URL}&rkey=existing`]) {
|
||||
expect(await cache.resolveMediaUrl(bridge as never, { type: 'video', url }, true)).toBe(
|
||||
url,
|
||||
);
|
||||
}
|
||||
|
||||
expect(fetchDownloadRKeys).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RKeyCache remote fallback (#156)', () => {
|
||||
const SERVER = 'https://rkey.example/r';
|
||||
|
||||
|
||||
@@ -76,6 +76,70 @@ describe('database migration estimates', () => {
|
||||
});
|
||||
|
||||
describe('OneBotManager database preparation', () => {
|
||||
it('releases its session subscription before shutdown and cannot bind after disposal', async () => {
|
||||
const first = vi.fn();
|
||||
const second = vi.fn();
|
||||
const source = {
|
||||
subscribeSessions: vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second),
|
||||
};
|
||||
const manager = new OneBotManager();
|
||||
manager.bind(source);
|
||||
manager.bind(source);
|
||||
expect(first).toHaveBeenCalledOnce();
|
||||
expect(second).not.toHaveBeenCalled();
|
||||
|
||||
const disposed = manager.dispose();
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
await disposed;
|
||||
await manager.dispose();
|
||||
manager.bind(source);
|
||||
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
expect(source.subscribeSessions).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each(['logout', 'dispose'] as const)(
|
||||
'invalidates migration callbacks before cancelling the task on %s',
|
||||
async (reason) => {
|
||||
vi.useFakeTimers();
|
||||
let callbacks!: DatabaseMigrationCallbacks;
|
||||
const cancel = vi.fn(() => {
|
||||
callbacks.onFailed(new Error('cancelled task'));
|
||||
callbacks.onProgress({ phase: 'complete', processed: 1, total: 1 }, 100);
|
||||
});
|
||||
const createTask = vi.fn(() => ({
|
||||
start: (next: DatabaseMigrationCallbacks) => {
|
||||
callbacks = next;
|
||||
},
|
||||
beginMigration: vi.fn(),
|
||||
cancel,
|
||||
}));
|
||||
const manager = new OneBotManager({ createDatabaseMigrationTask: createTask });
|
||||
const lifecycle = manager as unknown as {
|
||||
onSessionStarted(uin: string, bridge: never): void;
|
||||
onSessionClosed(uin: string): void;
|
||||
};
|
||||
|
||||
try {
|
||||
lifecycle.onSessionStarted('10001', fakeBridge() as never);
|
||||
|
||||
if (reason === 'logout') {
|
||||
lifecycle.onSessionClosed('10001');
|
||||
} else {
|
||||
await manager.dispose();
|
||||
}
|
||||
|
||||
expect(manager.getConnectionStatuses()).toEqual([]);
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
vi.advanceTimersByTime(10_000);
|
||||
expect(createTask).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
await manager.dispose();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('detaches migration and network startup from the login operation', () => {
|
||||
let callbacks!: DatabaseMigrationCallbacks;
|
||||
const observedRequestIds: Array<number | undefined> = [];
|
||||
@@ -104,11 +168,11 @@ describe('OneBotManager database preparation', () => {
|
||||
});
|
||||
let startListener!: (uin: string, bridge: never) => void;
|
||||
manager.bind({
|
||||
addSessionStartedListener: (listener) => {
|
||||
startListener = listener;
|
||||
subscribeSessions: (listener) => {
|
||||
startListener = listener.started!;
|
||||
return vi.fn();
|
||||
},
|
||||
addSessionClosedListener: vi.fn(),
|
||||
} as never);
|
||||
});
|
||||
const bridge = fakeBridge(new Promise(() => undefined));
|
||||
|
||||
runWithRequestId(5201, () => startListener('10001', bridge as never));
|
||||
@@ -449,10 +513,20 @@ describe('OneBotManager database preparation', () => {
|
||||
usable: false,
|
||||
error: '数据库迁移失败:private detail;将自动重试',
|
||||
});
|
||||
const failed = manager.getConnectionStatuses()[0].databaseMigration;
|
||||
callbacks[0].onProgress({ phase: 'complete', processed: 10, total: 10 }, 100);
|
||||
callbacks[0].onFailed(new Error('duplicate failure'));
|
||||
expect(manager.getConnectionStatuses()[0].databaseMigration).toBe(failed);
|
||||
expect(tasks[0].cancel).toHaveBeenCalledOnce();
|
||||
|
||||
vi.advanceTimersByTime(5_000);
|
||||
expect(tasks).toHaveLength(2);
|
||||
expect(tasks[1].start).toHaveBeenCalledOnce();
|
||||
const preparing = manager.getConnectionStatuses()[0].databaseMigration;
|
||||
callbacks[0].onProgress({ phase: 'complete', processed: 10, total: 10 }, 100);
|
||||
callbacks[0].onFailed(new Error('obsolete task failure'));
|
||||
expect(manager.getConnectionStatuses()[0].databaseMigration).toBe(preparing);
|
||||
expect(tasks[1].cancel).not.toHaveBeenCalled();
|
||||
|
||||
internals.onSessionClosed('10001');
|
||||
callbacks[1].onFailed(new Error('late failure'));
|
||||
|
||||
@@ -240,7 +240,7 @@ describe('OneBotNetworkManager', () => {
|
||||
expect(mgr.hasActiveAdapters()).toBe(true);
|
||||
});
|
||||
|
||||
it('closeAll clears every adapter', async () => {
|
||||
it('shutdown clears every adapter', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
const a = makeAdapter('a');
|
||||
const b = makeAdapter('b');
|
||||
@@ -248,7 +248,7 @@ describe('OneBotNetworkManager', () => {
|
||||
mgr.register(b);
|
||||
await mgr.openAll();
|
||||
|
||||
await mgr.closeAll();
|
||||
await mgr.shutdown();
|
||||
expect(mgr.list()).toHaveLength(0);
|
||||
expect(a.closes).toBe(1);
|
||||
expect(b.closes).toBe(1);
|
||||
@@ -262,11 +262,11 @@ describe('OneBotNetworkManager', () => {
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
await mgr.openAll();
|
||||
expect(mgr.hasActiveAdapters()).toBe(true);
|
||||
await mgr.closeAll();
|
||||
await mgr.shutdown();
|
||||
expect(mgr.hasActiveAdapters()).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects compatibility registration after shutdown', async () => {
|
||||
it('rejects new registration after shutdown', async () => {
|
||||
const mgr = new OneBotNetworkManager();
|
||||
await mgr.shutdown();
|
||||
|
||||
@@ -288,6 +288,7 @@ describe('OneBotNetworkManager', () => {
|
||||
|
||||
const emitting = mgr.emitEvent(SAMPLE_EVENT);
|
||||
const closing = mgr.shutdown();
|
||||
expect(mgr.shutdown()).toBe(closing);
|
||||
await expect(mgr.emitEvent(SAMPLE_EVENT)).rejects.toThrow(/shutting down/);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
@@ -296,6 +297,7 @@ describe('OneBotNetworkManager', () => {
|
||||
release();
|
||||
await emitting;
|
||||
await closing;
|
||||
expect(mgr.shutdown()).toBe(closing);
|
||||
expect(adapter.closes).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { resolveRuntimeNativePath } from '@snowluma/common/native-path';
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const log = createLogger('Highway.Audio');
|
||||
|
||||
export interface FFmpegVideoInfo {
|
||||
@@ -42,46 +42,10 @@ interface FFmpegNativeAddon {
|
||||
let cachedAddon: FFmpegNativeAddon | null = null;
|
||||
let cachedLoadError: string | null = null;
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function addonFileName(): string {
|
||||
return `ffmpegAddon.${process.platform}.${process.arch}.node`;
|
||||
}
|
||||
|
||||
function addonSearchDirs(): string[] {
|
||||
// Mirrors the hook injector's resolution strategy so the addon is found
|
||||
// regardless of whether we're running from:
|
||||
// 1. A released zip (dist/native/ffmpeg/<file>.node), where __dirname is
|
||||
// the dist root.
|
||||
// 2. The bundled build (repoRoot/dist/native/ffmpeg/<file>.node).
|
||||
// 3. `tsx` dev mode (packages/runtime/native/ffmpeg/<file>.node), where
|
||||
// __dirname is `packages/core/src/bridge/highway` — four levels deep
|
||||
// under `packages/`. Note: the hook injector lives at
|
||||
// `packages/core/src/hook` so it only needs 3 `..`; we need 4.
|
||||
return [
|
||||
path.resolve(__dirname, 'native', 'ffmpeg'),
|
||||
path.resolve(__dirname, '..', '..', '..', '..', 'runtime', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'dist', 'native', 'ffmpeg'),
|
||||
path.resolve(process.cwd(), 'packages', 'runtime', 'native', 'ffmpeg'),
|
||||
];
|
||||
}
|
||||
|
||||
function resolveAddonPath(): string | null {
|
||||
const fileName = addonFileName();
|
||||
|
||||
for (const dir of addonSearchDirs()) {
|
||||
const full = path.join(dir, fileName);
|
||||
|
||||
if (fs.existsSync(full)) {
|
||||
return full;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the ffmpegAddon once and return a cached instance.
|
||||
* Throws on first-use failure; subsequent calls replay the same error message
|
||||
@@ -96,7 +60,7 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
throw new Error(cachedLoadError);
|
||||
}
|
||||
|
||||
const addonPath = resolveAddonPath();
|
||||
const addonPath = resolveRuntimeNativePath(path.join('ffmpeg', addonFileName()));
|
||||
|
||||
if (!addonPath) {
|
||||
cachedLoadError = `ffmpegAddon not found for ${process.platform}-${process.arch} (looked for ${addonFileName()})`;
|
||||
@@ -121,19 +85,14 @@ export function getFFmpegAddon(): FFmpegNativeAddon {
|
||||
* a ready-to-upload silk file.
|
||||
*/
|
||||
export function isSilkFile(filePath: string): boolean {
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
|
||||
try {
|
||||
const buf = Buffer.alloc(10);
|
||||
fs.readSync(fd, buf, 0, 10, 0);
|
||||
const header = buf.toString();
|
||||
return header.includes('#!SILK') || header.includes('\x02#!SILK');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
try {
|
||||
const buf = Buffer.alloc(10);
|
||||
fs.readSync(fd, buf, 0, 10, 0);
|
||||
return buf.toString().includes('#!SILK');
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,33 +112,34 @@ export interface EncodeSilkResult {
|
||||
*/
|
||||
export async function encodeSilk(inputFile: string, tempDir: string): Promise<EncodeSilkResult> {
|
||||
const addon = getFFmpegAddon();
|
||||
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
|
||||
// Already silk — trust the file, just measure duration via the addon.
|
||||
if (isSilkFile(inputFile)) {
|
||||
let duration = 1;
|
||||
|
||||
try {
|
||||
duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
} catch {
|
||||
// getDuration on a silk file occasionally fails on certain encodings;
|
||||
// the upload path only needs a rough, non-zero value, so fall back
|
||||
// to the size-based heuristic used by NapCat's audio.ts.
|
||||
const stat = fs.statSync(inputFile);
|
||||
duration = Math.max(1, Math.floor(stat.size / 1024 / 3));
|
||||
}
|
||||
|
||||
return { path: inputFile, duration, converted: false };
|
||||
}
|
||||
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
const outPath = path.join(tempDir, crypto.randomUUID());
|
||||
await addon.convertToNTSilkTct(inputFile, outPath);
|
||||
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('convertToNTSilkTct produced no output file');
|
||||
try {
|
||||
await addon.convertToNTSilkTct(inputFile, outPath);
|
||||
|
||||
if (!fs.existsSync(outPath)) {
|
||||
throw new Error('convertToNTSilkTct produced no output file');
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
await fs.promises.rm(outPath, { force: true });
|
||||
} catch (cleanupError) {
|
||||
throw new AggregateError(
|
||||
[error, cleanupError],
|
||||
`SILK conversion failed: ${errorMessage(error)}; temporary file cleanup failed: ${errorMessage(cleanupError)}`,
|
||||
);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
const duration = Math.max(1, Math.round(await addon.getDuration(inputFile)));
|
||||
return { path: outPath, duration, converted: true };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { errorMessage } from '@snowluma/common/errors';
|
||||
import { createLogger, renderTraceBytes, runWithTraceRequest } from '@snowluma/common/logger';
|
||||
import type {
|
||||
EncodableMediaMsgInfo,
|
||||
@@ -136,10 +137,6 @@ function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
|
||||
.join(';')}]`;
|
||||
}
|
||||
|
||||
function mediaErrorText(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
// ─────────────── main entrypoint ───────────────
|
||||
|
||||
/**
|
||||
@@ -191,7 +188,7 @@ export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespB
|
||||
label,
|
||||
failureReason,
|
||||
params.uploads.length,
|
||||
mediaErrorText(error),
|
||||
errorMessage(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
|
||||
@@ -1766,7 +1766,7 @@ export class IdentityService {
|
||||
this.recordPersistenceFailure('retry', error),
|
||||
);
|
||||
}, delay);
|
||||
this.retryTimer_.unref?.();
|
||||
this.retryTimer_.unref();
|
||||
}
|
||||
|
||||
private flushPendingWrites(scheduleRetry = true): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/common/native-path', () => ({
|
||||
resolveRuntimeNativePath: () => '/test/ffmpeg.node',
|
||||
}));
|
||||
|
||||
const addon = {
|
||||
getDuration: vi.fn<(file: string) => Promise<number>>(),
|
||||
convertToNTSilkTct: vi.fn<(input: string, output: string) => Promise<void>>(),
|
||||
};
|
||||
let root: string;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
addon.getDuration.mockReset().mockResolvedValue(2.5);
|
||||
addon.convertToNTSilkTct.mockReset().mockImplementation(async (_input, output) => {
|
||||
await fs.promises.writeFile(output, '\x02#!SILK_V3payload');
|
||||
});
|
||||
vi.spyOn(process, 'dlopen').mockImplementation((module) => {
|
||||
(module as { exports: object }).exports = addon;
|
||||
});
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-encode-silk-'));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('SILK encoding', () => {
|
||||
it('rejects unreadable files instead of treating them as a different audio format', async () => {
|
||||
const { isSilkFile } = await import('../../src/highway/ffmpeg-addon');
|
||||
expect(() => isSilkFile(path.join(root, 'missing'))).toThrow(/ENOENT/);
|
||||
});
|
||||
|
||||
it('keeps native duration failures visible instead of guessing from SILK file size', async () => {
|
||||
const input = path.join(root, 'invalid.silk');
|
||||
fs.writeFileSync(input, '#!SILK_V3truncated');
|
||||
const failure = new Error('truncated SILK packet');
|
||||
addon.getDuration.mockRejectedValue(failure);
|
||||
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
|
||||
await expect(encodeSilk(input, root)).rejects.toBe(failure);
|
||||
expect(addon.convertToNTSilkTct).not.toHaveBeenCalled();
|
||||
expect(fs.readdirSync(root)).toEqual(['invalid.silk']);
|
||||
});
|
||||
|
||||
it('reuses a valid SILK input without creating a temporary file', async () => {
|
||||
const input = path.join(root, 'voice.silk');
|
||||
fs.writeFileSync(input, '\x02#!SILK_V3payload');
|
||||
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
|
||||
await expect(encodeSilk(input, root)).resolves.toEqual({
|
||||
path: input,
|
||||
duration: 3,
|
||||
converted: false,
|
||||
});
|
||||
expect(addon.convertToNTSilkTct).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns the converted file for caller-owned cleanup', async () => {
|
||||
const input = path.join(root, 'voice.wav');
|
||||
fs.writeFileSync(input, 'RIFF');
|
||||
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
|
||||
const result = await encodeSilk(input, root);
|
||||
expect(result.converted).toBe(true);
|
||||
expect(result.duration).toBe(3);
|
||||
expect(fs.readFileSync(result.path, 'utf8')).toBe('\x02#!SILK_V3payload');
|
||||
expect(addon.convertToNTSilkTct).toHaveBeenCalledWith(input, result.path);
|
||||
});
|
||||
|
||||
it('removes partial output when native conversion fails, preserving the source and error', async () => {
|
||||
const input = path.join(root, 'voice.wav');
|
||||
fs.writeFileSync(input, 'RIFF');
|
||||
const failure = new Error('conversion interrupted');
|
||||
addon.convertToNTSilkTct.mockImplementation(async (_input, output) => {
|
||||
await fs.promises.writeFile(output, 'partial');
|
||||
throw failure;
|
||||
});
|
||||
const { encodeSilk } = await import('../../src/highway/ffmpeg-addon');
|
||||
await expect(encodeSilk(input, root)).rejects.toBe(failure);
|
||||
expect(fs.readdirSync(root)).toEqual(['voice.wav']);
|
||||
expect(fs.readFileSync(input, 'utf8')).toBe('RIFF');
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
import { convertAudioBytes, encodeSilk } from '@snowluma/protocol/highway/ffmpeg-addon';
|
||||
|
||||
interface NativeAudioAddon {
|
||||
convertToNTSilkTct(inputFile: string, outputFile: string): Promise<void>;
|
||||
@@ -111,9 +111,20 @@ describeBundledAddon('bundled native ffmpeg addon', () => {
|
||||
);
|
||||
|
||||
await expect(addon.getDuration(recordPath)).rejects.toThrow(/Invalid data/);
|
||||
await expect(encodeSilk(recordPath, tmpDir)).rejects.toThrow(/Invalid data/);
|
||||
});
|
||||
});
|
||||
|
||||
it('encodes a WAV with the runtime addon when started from the protocol package', async () => {
|
||||
const wavPath = path.join(tmpDir, 'runtime-input.wav');
|
||||
writeFileSync(wavPath, makeMonoWav());
|
||||
const result = await encodeSilk(wavPath, tmpDir);
|
||||
expect(result.converted).toBe(true);
|
||||
expect(result.duration).toBe(1);
|
||||
expect(readFileSync(result.path).subarray(1, 10).toString('ascii')).toBe('#!SILK_V3');
|
||||
expect(await loadBundledAddon().getDuration(result.path)).toBeCloseTo(1, 6);
|
||||
});
|
||||
|
||||
it('converts a mono QQ-style SILK record to a decodable MP3 through the public transcode seam', async () => {
|
||||
const addon = loadBundledAddon();
|
||||
const wavPath = path.join(tmpDir, 'mono-input.wav');
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -64,11 +64,7 @@ export function rawToString(value: unknown): string {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value instanceof ArrayBuffer) {
|
||||
return new TextDecoder().decode(value);
|
||||
}
|
||||
|
||||
if (ArrayBuffer.isView(value)) {
|
||||
if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
||||
return new TextDecoder().decode(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,12 +12,19 @@ export function createRequestAbortState(
|
||||
externalSignal?: AbortSignal,
|
||||
): RequestAbortState {
|
||||
const controller = new AbortController();
|
||||
let timedOut = false;
|
||||
let externallyAborted = false;
|
||||
let abortedBy: 'timeout' | 'external' | null = null;
|
||||
|
||||
const abort = (source: 'timeout' | 'external', reason?: unknown): void => {
|
||||
if (abortedBy !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
abortedBy = source;
|
||||
controller.abort(reason);
|
||||
};
|
||||
|
||||
const onExternalAbort = (): void => {
|
||||
externallyAborted = true;
|
||||
controller.abort(externalSignal?.reason);
|
||||
abort('external', externalSignal?.reason);
|
||||
};
|
||||
|
||||
if (externalSignal?.aborted) {
|
||||
@@ -29,8 +36,7 @@ export function createRequestAbortState(
|
||||
const timer =
|
||||
timeoutMs > 0
|
||||
? setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
abort('timeout');
|
||||
}, timeoutMs)
|
||||
: null;
|
||||
|
||||
@@ -44,10 +50,10 @@ export function createRequestAbortState(
|
||||
externalSignal?.removeEventListener('abort', onExternalAbort);
|
||||
},
|
||||
isTimedOut() {
|
||||
return timedOut;
|
||||
return abortedBy === 'timeout';
|
||||
},
|
||||
isExternallyAborted() {
|
||||
return externallyAborted || externalSignal?.aborted === true;
|
||||
return abortedBy === 'external';
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -63,7 +69,7 @@ export function isAbortError(error: unknown): boolean {
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'name' in error &&
|
||||
(error as { name?: unknown }).name === 'AbortError'
|
||||
error.name === 'AbortError'
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRequestAbortState } from '../src/internal/abort';
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe('request cancellation', () => {
|
||||
it('keeps caller cancellation as the cause when the timeout expires later', () => {
|
||||
vi.useFakeTimers();
|
||||
const caller = new AbortController();
|
||||
const request = createRequestAbortState(100, caller.signal);
|
||||
caller.abort('caller canceled');
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(request.signal.reason).toBe('caller canceled');
|
||||
expect(request.isExternallyAborted()).toBe(true);
|
||||
expect(request.isTimedOut()).toBe(false);
|
||||
request.cleanup();
|
||||
});
|
||||
|
||||
it('keeps the timeout as the cause when the caller cancels later', () => {
|
||||
vi.useFakeTimers();
|
||||
const caller = new AbortController();
|
||||
const request = createRequestAbortState(100, caller.signal);
|
||||
vi.advanceTimersByTime(100);
|
||||
caller.abort();
|
||||
expect(request.isTimedOut()).toBe(true);
|
||||
expect(request.isExternallyAborted()).toBe(false);
|
||||
request.cleanup();
|
||||
});
|
||||
|
||||
it('stops observing timeouts and caller cancellation after cleanup', () => {
|
||||
vi.useFakeTimers();
|
||||
const caller = new AbortController();
|
||||
const request = createRequestAbortState(100, caller.signal);
|
||||
request.cleanup();
|
||||
caller.abort();
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(request.signal.aborted).toBe(false);
|
||||
expect(request.isTimedOut()).toBe(false);
|
||||
expect(request.isExternallyAborted()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,3 @@
|
||||
// Settings → 全局配置 tab. Deployment-wide SnowLuma knobs (config/snowluma.json):
|
||||
// rkey fallback servers + the music-card signing URL. Same UX as the other
|
||||
// settings panels — debounced auto-save, no explicit save button. Unlike the
|
||||
// channel editor these are typed inline, so the server's normalized result is
|
||||
// NOT written back onto the inputs while editing (that would erase a half-typed
|
||||
// URL); the store reconciles on the next load. Invalid entries are flagged
|
||||
// client-side and simply dropped by the server on save.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { AlertTriangle, KeyRound, Music, Plus, RefreshCw, Trash2 } from 'lucide-react';
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
@@ -33,20 +26,17 @@ export function GlobalConfigPanel() {
|
||||
const { runAction } = useActionFeedback();
|
||||
const [config, setConfig] = useState<GlobalSettings | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const { msg, flash } = useFlashMessage();
|
||||
const saveTimer = useRef<number | null>(null);
|
||||
const saveGen = useRef(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setLoadFailed(false);
|
||||
|
||||
try {
|
||||
setConfig(await api.globalConfig.get());
|
||||
} catch (error) {
|
||||
console.error('load global config failed', error);
|
||||
setLoadFailed(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -65,9 +55,7 @@ export function GlobalConfigPanel() {
|
||||
[],
|
||||
);
|
||||
|
||||
/** Apply locally + debounced auto-save. Deliberately does NOT reconcile the
|
||||
* inputs from the server's normalized response (it would wipe a half-typed
|
||||
* URL); a generation guard just confirms the latest save. */
|
||||
// Keep partially typed URLs in the draft until the next load.
|
||||
const commit = (
|
||||
next: GlobalSettings,
|
||||
feedback: false | { title: string; successTitle: string } = {
|
||||
@@ -83,6 +71,7 @@ export function GlobalConfigPanel() {
|
||||
}
|
||||
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
saveTimer.current = null;
|
||||
const dropped =
|
||||
next.rkey.fallbackServers.some((s) => s.trim() && !isHttpUrl(s.trim())) ||
|
||||
(next.musicSignUrl.trim().length > 0 && !isHttpUrl(next.musicSignUrl.trim()));
|
||||
@@ -92,7 +81,6 @@ export function GlobalConfigPanel() {
|
||||
: runAction(
|
||||
{
|
||||
title: feedback.title,
|
||||
detail: '正在同步 config/snowluma.json',
|
||||
successTitle: feedback.successTitle,
|
||||
successDetail: dropped ? '已保存,无效项已忽略' : '配置已同步',
|
||||
errorTitle: '全局配置更新失败',
|
||||
@@ -105,8 +93,6 @@ export function GlobalConfigPanel() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The server drops invalid (non-http) entries; say so rather than a
|
||||
// bare "已保存" next to a still-visible rejected value.
|
||||
flash('ok', dropped ? '已保存(无效项已忽略)' : '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
@@ -130,7 +116,7 @@ export function GlobalConfigPanel() {
|
||||
label="全局配置"
|
||||
className={!loading ? 'skeleton-swap-fluid min-h-[156px]' : ''}
|
||||
>
|
||||
{!loading && (loadFailed || !config) ? (
|
||||
{!loading ? (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16 text-muted-foreground">
|
||||
<AlertTriangle className="size-8 opacity-40" strokeWidth={1.5} />
|
||||
<p className="text-sm">加载全局配置失败</p>
|
||||
@@ -162,13 +148,8 @@ export function GlobalConfigPanel() {
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
<KeyRound className="mt-0.5 size-3.5 shrink-0" />
|
||||
<p>
|
||||
图片 / 文件下载链接需要服务器签发的{' '}
|
||||
<code className="font-mono">rkey</code>。SnowLuma 默认走内核获取;
|
||||
当内核在你的环境下持续取不到时,会按顺序向这里配置的 HTTP 端点回退。
|
||||
<strong className="font-medium text-foreground/80">
|
||||
默认留空=关闭
|
||||
</strong>
|
||||
,不配置就不会联系任何第三方。 建议填你自建的端点。
|
||||
内核无法获取 <code className="font-mono">rkey</code>{' '}
|
||||
时,依次请求下列服务器。留空关闭,建议使用自建服务。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -186,7 +167,7 @@ export function GlobalConfigPanel() {
|
||||
|
||||
{servers.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
|
||||
未配置回退服务器(rkey 回退已关闭)
|
||||
回退服务器未启用
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
@@ -235,7 +216,7 @@ export function GlobalConfigPanel() {
|
||||
<code className="font-mono">
|
||||
{'{ group_rkey, private_rkey, expired_time }'}
|
||||
</code>
|
||||
(兼容 NapCat rkey 服务格式)。非 http(s) 链接会被忽略。
|
||||
,仅支持 HTTP(S)。
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -268,9 +249,6 @@ export function GlobalConfigPanel() {
|
||||
)}
|
||||
onChange={(e) => commit({ ...config, musicSignUrl: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
内置默认:<code className="font-mono">{MUSIC_SIGN_DEFAULT}</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
// Settings → 通知 tab. Mirrors the node-config UX: the first screen is
|
||||
// info-only cards (name / url / template + an inline enable toggle); creating
|
||||
// and editing always go through a dialog. All changes auto-save (debounced),
|
||||
// like the per-account config page — no explicit save button.
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { DEFAULT_WEBHOOK_BODY } from '@snowluma/common/notification-templates';
|
||||
@@ -61,6 +57,7 @@ export function NotificationsPanel() {
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setMsg(null);
|
||||
|
||||
try {
|
||||
setConfig(await api.notifications.getConfig());
|
||||
@@ -102,6 +99,7 @@ export function NotificationsPanel() {
|
||||
}
|
||||
|
||||
saveTimer.current = window.setTimeout(() => {
|
||||
saveTimer.current = null;
|
||||
void runAction(
|
||||
{
|
||||
title: copy.title,
|
||||
@@ -123,6 +121,10 @@ export function NotificationsPanel() {
|
||||
flash('ok', '已保存');
|
||||
})
|
||||
.catch((error) => {
|
||||
if (saveGen.current !== gen) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('save notifications config failed', error);
|
||||
flash('err', '保存失败,请检查服务器日志');
|
||||
});
|
||||
|
||||
@@ -1,35 +1,11 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||
import type { UpdateInfo } from '@/types';
|
||||
import type { AppResourceData, AppResources } from '@/lib/app-resources';
|
||||
import type { HookProcessOps } from '@/hooks/use-hook-process-ops';
|
||||
|
||||
export interface ResourceLoadState {
|
||||
ready: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface AppResourceState {
|
||||
qqList: ResourceLoadState;
|
||||
processList: ResourceLoadState;
|
||||
systemInfo: ResourceLoadState;
|
||||
connections: ResourceLoadState;
|
||||
updateInfo: ResourceLoadState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live mutable state owned by AppLayout and shared with the child route
|
||||
* components rendered inside its `<Outlet />`. Pages used to receive these
|
||||
* via prop drilling — now they pull from context so adding a new page does
|
||||
* not touch AppLayout.
|
||||
*/
|
||||
export interface AppStateValue {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
/** Advisory update-availability info; null until the first check resolves. */
|
||||
updateInfo: UpdateInfo | null;
|
||||
export interface AppStateValue extends AppResourceData {
|
||||
/** Distinguishes an empty result from an unresolved or failed initial read. */
|
||||
resources: AppResourceState;
|
||||
resources: AppResources;
|
||||
selectedUin: string | null;
|
||||
setSelectedUin: (uin: string | null) => void;
|
||||
processOps: HookProcessOps;
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { createContext, useContext, type ReactNode } from 'react';
|
||||
|
||||
/**
|
||||
* Auth-level state surfaced into the router subtree. `AuthBoundary` mints
|
||||
* this and `AppLayout` consumes it — used to drive the status badge and to
|
||||
* complete logout after page-local state has been cleared.
|
||||
*/
|
||||
/** Session state shared by the authentication boundary and routed pages. */
|
||||
export interface SessionValue {
|
||||
status: string;
|
||||
/** Invoked by AppLayout's logout handler after it has scrubbed its own state. */
|
||||
/** Ends the session and unmounts its page state. */
|
||||
onLogoutComplete: () => void;
|
||||
/** Replays the first-run wizard without changing persisted account state. */
|
||||
restartOnboarding: () => void;
|
||||
|
||||
@@ -228,7 +228,6 @@ export const DEFAULT_APPEARANCE: UiAppearance = {
|
||||
export const FONT_CUSTOM_ID = 'custom';
|
||||
|
||||
const LS_CACHE = 'snowluma_ui_appearance';
|
||||
const LS_MIGRATED = 'snowluma_ui_migrated';
|
||||
const TOKEN_KEY = 'snowluma_token';
|
||||
|
||||
// ─── Colour helpers (custom hex accent → readable foreground) ──────────────
|
||||
@@ -1012,61 +1011,6 @@ async function persistAppearance(appearance: UiAppearance): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Migration of the pre-server-config localStorage theme ─────────────────
|
||||
|
||||
function readLegacyOverlay(): Partial<UiAppearance> | null {
|
||||
try {
|
||||
const out: Partial<UiAppearance> = {};
|
||||
const mode = localStorage.getItem('snowluma_theme');
|
||||
|
||||
if (mode === 'light' || mode === 'dark' || mode === 'system') {
|
||||
out.mode = mode;
|
||||
}
|
||||
|
||||
const accent = localStorage.getItem('snowluma_accent');
|
||||
|
||||
if (accent && ACCENTS.some((a) => a.id === accent)) {
|
||||
out.accentMode = 'preset';
|
||||
out.accentPreset = accent;
|
||||
}
|
||||
|
||||
const radius = Number(localStorage.getItem('snowluma_radius'));
|
||||
|
||||
if (Number.isFinite(radius) && radius > 0 && radius <= 2) {
|
||||
out.radius = radius;
|
||||
}
|
||||
|
||||
const density = localStorage.getItem('snowluma_density');
|
||||
|
||||
if (density === 'cozy' || density === 'compact') {
|
||||
out.density = density;
|
||||
}
|
||||
|
||||
const poll = Number(localStorage.getItem('snowluma_poll_interval'));
|
||||
|
||||
if (Number.isFinite(poll) && poll >= 0 && poll <= 60_000) {
|
||||
out.pollInterval = poll;
|
||||
}
|
||||
|
||||
return Object.keys(out).length > 0 ? out : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isPristine(a: UiAppearance): boolean {
|
||||
const d = DEFAULT_APPEARANCE;
|
||||
return (
|
||||
a.mode === d.mode &&
|
||||
a.accentMode === d.accentMode &&
|
||||
a.accentPreset === d.accentPreset &&
|
||||
a.radius === d.radius &&
|
||||
a.density === d.density &&
|
||||
a.pollInterval === d.pollInterval &&
|
||||
a.background.type === 'none'
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Light/dark reveal (View Transitions API) ──────────────────────────────
|
||||
// Where the user last clicked, so the theme reveal emanates from there.
|
||||
let lastPointer: { x: number; y: number } | null = null;
|
||||
@@ -1149,7 +1093,7 @@ interface ThemeContextValue {
|
||||
/** Re-fetch appearance from the server (e.g. after login, so the authed
|
||||
* `customCss` loads). */
|
||||
reloadAppearance: () => Promise<void>;
|
||||
// ── back-compat conveniences ──
|
||||
// Common appearance controls.
|
||||
mode: ThemeMode;
|
||||
setMode: (m: ThemeMode) => void;
|
||||
pollInterval: number;
|
||||
@@ -1190,7 +1134,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
return () => mq.removeEventListener('change', handler);
|
||||
}, []);
|
||||
|
||||
// Initial server load (+ one-time legacy migration). Runs once.
|
||||
// Load the server appearance, retaining the cache if it is unavailable.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
@@ -1201,34 +1145,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
return;
|
||||
}
|
||||
|
||||
let next = server ?? readCache();
|
||||
|
||||
let migrated = true;
|
||||
|
||||
try {
|
||||
migrated = Boolean(localStorage.getItem(LS_MIGRATED));
|
||||
} catch {
|
||||
/* storage unavailable: skip migration */
|
||||
}
|
||||
|
||||
if (!migrated) {
|
||||
try {
|
||||
localStorage.setItem(LS_MIGRATED, '1');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
const legacy = readLegacyOverlay();
|
||||
|
||||
// Only migrate when the server has never been customized, so we don't
|
||||
// clobber a look already set from another device.
|
||||
if (legacy && server && isPristine(server)) {
|
||||
next = { ...server, ...legacy, background: server.background };
|
||||
void persistAppearance(next).catch((error) => {
|
||||
console.error('appearance migration save failed', error);
|
||||
});
|
||||
}
|
||||
}
|
||||
const next = server ?? readCache();
|
||||
|
||||
setAppearanceState(next);
|
||||
writeCache(next);
|
||||
@@ -1256,8 +1173,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
applyBackgroundLayer(appearance);
|
||||
}, [appearance]);
|
||||
|
||||
// Flush a pending debounced save on unmount (defensive — the provider lives
|
||||
// at the app root and normally never unmounts).
|
||||
// Cancel a pending save when the provider unmounts.
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (saveTimer.current) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { createAppResources } from '@/lib/app-resources';
|
||||
import { startPolling } from '@/lib/polling';
|
||||
|
||||
export function useAppResources(pollInterval: number) {
|
||||
const api = useApi();
|
||||
const store = useMemo(() => createAppResources(api), [api]);
|
||||
const resources = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
||||
|
||||
useEffect(() => {
|
||||
const dispose = api.stateStream({ onEvent: store.onEvent });
|
||||
|
||||
return () => {
|
||||
dispose();
|
||||
store.invalidate();
|
||||
};
|
||||
}, [api, store]);
|
||||
|
||||
// Reconcile SSE resources periodically; system metrics keep the faster cadence.
|
||||
useEffect(
|
||||
() =>
|
||||
startPolling(
|
||||
store.reconcile,
|
||||
pollInterval > 0 ? Math.max(pollInterval * 10, 10_000) : 0,
|
||||
),
|
||||
[pollInterval, store],
|
||||
);
|
||||
useEffect(() => startPolling(store.refreshSystem, pollInterval), [pollInterval, store]);
|
||||
useEffect(() => startPolling(store.refreshUpdate, 6 * 60 * 60 * 1000, false), [store]);
|
||||
|
||||
return {
|
||||
qqList: resources.qqList.data,
|
||||
processList: resources.processList.data,
|
||||
systemInfo: resources.systemInfo.data,
|
||||
connections: resources.connections.data,
|
||||
updateInfo: resources.updateInfo.data,
|
||||
resources,
|
||||
refreshQqList: store.refreshQqList,
|
||||
refreshProcesses: store.refreshProcesses,
|
||||
refreshSystem: store.refreshSystem,
|
||||
refreshConnections: store.refreshConnections,
|
||||
refreshUpdate: store.refreshUpdate,
|
||||
};
|
||||
}
|
||||
@@ -1,237 +1,33 @@
|
||||
// Debug contacts data layer — lazy-loads friend / group / member lists for the
|
||||
// debug console's pickers via the read-only OneBot actions, with a shared
|
||||
// module-level cache persisted to localStorage (version-stamped) and a short
|
||||
// TTL. Every loader degrades gracefully: on error the hook returns the error so
|
||||
// the Picker can fall back to raw input. One cache is shared across every
|
||||
// picker instance (tester form, message builder, etc.).
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useSyncExternalStore } from 'react';
|
||||
import { useApi } from '@/lib/api';
|
||||
import type { PickerOption } from '@/components/ui/picker';
|
||||
import { createContactList, type ContactKind } from '@/lib/debug-contacts';
|
||||
|
||||
const CACHE_VERSION = 1; // bump to invalidate all persisted entries
|
||||
const TTL_MS = 5 * 60_000;
|
||||
const LS_KEY = `snowluma.debug.contacts.v${CACHE_VERSION}`;
|
||||
export { userAvatar, groupAvatar } from '@/lib/debug-contacts';
|
||||
|
||||
export function userAvatar(uin: string | number): string {
|
||||
return `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=100`;
|
||||
}
|
||||
|
||||
export function groupAvatar(gid: string | number): string {
|
||||
return `https://p.qlogo.cn/gh/${gid}/${gid}/100`;
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
at: number;
|
||||
items: PickerOption[];
|
||||
}
|
||||
|
||||
// Avatars are derivable from the id + the list kind (encoded in the cache-key
|
||||
// prefix), so they're stripped before persisting (a big member list × long
|
||||
// avatar URLs would otherwise blow the ~5MB localStorage quota and silently
|
||||
// kill persistence for ALL entries) and regenerated on hydrate.
|
||||
function avatarFor(key: string, value: string): string | undefined {
|
||||
if (key.startsWith('groups:')) {
|
||||
return groupAvatar(value);
|
||||
}
|
||||
|
||||
if (key.startsWith('friends:') || key.startsWith('members:')) {
|
||||
return userAvatar(value);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ── shared cache (module-level, hydrated from localStorage once) ──
|
||||
const mem = new Map<string, Entry>();
|
||||
let hydrated = false;
|
||||
|
||||
function hydrate(): void {
|
||||
if (hydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
hydrated = true;
|
||||
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_KEY);
|
||||
|
||||
if (raw) {
|
||||
const obj = JSON.parse(raw) as Record<string, Entry>;
|
||||
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
if (v && Array.isArray(v.items)) {
|
||||
mem.set(k, {
|
||||
at: v.at,
|
||||
items: v.items.map((it) => ({
|
||||
...it,
|
||||
avatar: it.avatar ?? avatarFor(k, it.value),
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* corrupt / unavailable — start empty */
|
||||
}
|
||||
}
|
||||
|
||||
function persist(): void {
|
||||
try {
|
||||
const obj: Record<string, Entry> = {};
|
||||
|
||||
// Strip the derivable avatar to keep the serialized blob small.
|
||||
for (const [k, v] of mem) {
|
||||
obj[k] = {
|
||||
at: v.at,
|
||||
items: v.items.map((it) => ({ value: it.value, label: it.label, sub: it.sub })),
|
||||
};
|
||||
}
|
||||
|
||||
localStorage.setItem(LS_KEY, JSON.stringify(obj));
|
||||
} catch {
|
||||
/* quota / unavailable — memory cache still works */
|
||||
}
|
||||
}
|
||||
|
||||
type ParseRow = (row: Record<string, unknown>) => PickerOption | null;
|
||||
|
||||
interface ListState {
|
||||
items: PickerOption[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => void;
|
||||
}
|
||||
|
||||
function useContactList(
|
||||
cacheKey: string | null,
|
||||
action: string,
|
||||
uin: string,
|
||||
params: Record<string, unknown>,
|
||||
parse: ParseRow,
|
||||
): ListState {
|
||||
function useContactList(kind: ContactKind, uin: string, groupId = '') {
|
||||
const api = useApi();
|
||||
hydrate();
|
||||
const [items, setItems] = useState<PickerOption[]>(
|
||||
() => (cacheKey && mem.get(cacheKey)?.items) || [],
|
||||
);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const reqId = useRef(0);
|
||||
|
||||
const load = useCallback(
|
||||
async (force: boolean) => {
|
||||
if (!cacheKey || !uin) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cached = mem.get(cacheKey);
|
||||
|
||||
if (!force && cached && Date.now() - cached.at < TTL_MS) {
|
||||
setItems(cached.items);
|
||||
return;
|
||||
}
|
||||
|
||||
const myId = ++reqId.current;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await api.debug.invoke(uin, action, params);
|
||||
|
||||
if (myId !== reqId.current) {
|
||||
return;
|
||||
} // superseded
|
||||
|
||||
if (res.status !== 'ok') {
|
||||
throw new Error(res.message || res.wording || '加载失败');
|
||||
}
|
||||
|
||||
const arr = Array.isArray(res.data) ? (res.data as Record<string, unknown>[]) : [];
|
||||
const mapped = arr.map(parse).filter((x): x is PickerOption => x !== null);
|
||||
mem.set(cacheKey, { at: Date.now(), items: mapped });
|
||||
persist();
|
||||
setItems(mapped);
|
||||
} catch (e) {
|
||||
if (myId !== reqId.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
setError(e instanceof Error ? e.message : '加载失败');
|
||||
// keep any stale items visible as a fallback
|
||||
} finally {
|
||||
if (myId === reqId.current) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
// params + parse are stable per call-site (their identity is captured by
|
||||
// cacheKey, which already varies on uin/group), so excluding them is
|
||||
// deliberate — including the fresh object/closure would reload every render.
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[api, cacheKey, uin, action],
|
||||
const store = useMemo(
|
||||
() => createContactList(api.debug.invoke, kind, uin, groupId),
|
||||
[api, kind, uin, groupId],
|
||||
);
|
||||
const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
||||
|
||||
useEffect(() => {
|
||||
if (!cacheKey || !uin) {
|
||||
setItems([]);
|
||||
return;
|
||||
}
|
||||
void store.refresh(false);
|
||||
return store.invalidate;
|
||||
}, [store]);
|
||||
|
||||
const cached = mem.get(cacheKey);
|
||||
// Clear stale items when switching to an uncached key — otherwise the picker
|
||||
// would show the previous account/group's contacts as valid until the fetch
|
||||
// returns (a member-selection hazard).
|
||||
setItems(cached ? cached.items : []);
|
||||
void load(false);
|
||||
}, [cacheKey, uin, load]);
|
||||
|
||||
return { items, loading, error, refresh: () => void load(true) };
|
||||
return { ...state, refresh: () => void store.refresh() };
|
||||
}
|
||||
|
||||
export function useFriends(uin: string): ListState {
|
||||
return useContactList(uin ? `friends:${uin}` : null, 'get_friend_list', uin, {}, (r) => {
|
||||
const id = r.user_id;
|
||||
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = String(id);
|
||||
const nick = (r.remark as string) || (r.nickname as string) || v;
|
||||
return { value: v, label: nick, sub: v, avatar: userAvatar(v) };
|
||||
});
|
||||
export function useFriends(uin: string) {
|
||||
return useContactList('friends', uin);
|
||||
}
|
||||
|
||||
export function useGroups(uin: string): ListState {
|
||||
return useContactList(uin ? `groups:${uin}` : null, 'get_group_list', uin, {}, (r) => {
|
||||
const id = r.group_id;
|
||||
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = String(id);
|
||||
return { value: v, label: (r.group_name as string) || v, sub: v, avatar: groupAvatar(v) };
|
||||
});
|
||||
export function useGroups(uin: string) {
|
||||
return useContactList('groups', uin);
|
||||
}
|
||||
|
||||
export function useGroupMembers(uin: string, groupId: string): ListState {
|
||||
const gid = groupId.trim();
|
||||
return useContactList(
|
||||
uin && gid ? `members:${uin}:${gid}` : null,
|
||||
'get_group_member_list',
|
||||
uin,
|
||||
{ group_id: gid },
|
||||
(r) => {
|
||||
const id = r.user_id;
|
||||
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const v = String(id);
|
||||
const name = (r.card as string) || (r.nickname as string) || v;
|
||||
return { value: v, label: name, sub: v, avatar: userAvatar(v) };
|
||||
},
|
||||
);
|
||||
export function useGroupMembers(uin: string, groupId: string) {
|
||||
return useContactList('members', uin, groupId.trim());
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
export type FlashKind = 'ok' | 'err';
|
||||
export interface FlashMessage {
|
||||
@@ -6,45 +6,38 @@ export interface FlashMessage {
|
||||
text: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transient status-banner state for a settings panel.
|
||||
*
|
||||
* - `flash(kind, text)` shows a message that auto-clears after `durationMs`,
|
||||
* cancelling any prior auto-clear timer first.
|
||||
* - `setMsg` sets/clears the message directly (a persistent one that stays
|
||||
* until the next action — e.g. a load-failure banner).
|
||||
* - The pending timer is cleared on unmount.
|
||||
*
|
||||
* Replaces the per-panel hand-rolled `msg` state + `msgTimer` ref + `flash` +
|
||||
* unmount cleanup, which had drifted (one panel omitted the ref, the
|
||||
* prior-timer cancel, and the unmount cleanup entirely — leaking a timer that
|
||||
* could fire a stale `setMsg` after unmount).
|
||||
*/
|
||||
/** `flash` expires automatically; `setMsg` replaces it with a persistent message. */
|
||||
export function useFlashMessage(durationMs = 2400): {
|
||||
msg: FlashMessage | null;
|
||||
flash: (kind: FlashKind, text: string) => void;
|
||||
setMsg: (msg: FlashMessage | null) => void;
|
||||
} {
|
||||
const [msg, setMsg] = useState<FlashMessage | null>(null);
|
||||
const [msg, setMessage] = useState<FlashMessage | null>(null);
|
||||
const timer = useRef<number | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (timer.current) {
|
||||
clearTimeout(timer.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const flash = (kind: FlashKind, text: string) => {
|
||||
setMsg({ kind, text });
|
||||
|
||||
if (timer.current) {
|
||||
const cancelTimer = useCallback(() => {
|
||||
if (timer.current !== null) {
|
||||
clearTimeout(timer.current);
|
||||
}
|
||||
|
||||
timer.current = window.setTimeout(() => setMsg(null), durationMs);
|
||||
};
|
||||
|
||||
timer.current = null;
|
||||
}, []);
|
||||
useEffect(() => cancelTimer, [cancelTimer]);
|
||||
const setMsg = useCallback(
|
||||
(next: FlashMessage | null) => {
|
||||
cancelTimer();
|
||||
setMessage(next);
|
||||
},
|
||||
[cancelTimer],
|
||||
);
|
||||
const flash = useCallback(
|
||||
(kind: FlashKind, text: string) => {
|
||||
setMsg({ kind, text });
|
||||
timer.current = window.setTimeout(() => {
|
||||
timer.current = null;
|
||||
setMessage(null);
|
||||
}, durationMs);
|
||||
},
|
||||
[durationMs, setMsg],
|
||||
);
|
||||
return { msg, flash, setMsg };
|
||||
}
|
||||
@@ -3,12 +3,7 @@ import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
|
||||
import type { OneBotConfig, QQInfo } from '@/types';
|
||||
import { useApi } from '@/lib/api';
|
||||
|
||||
/**
|
||||
* Per-UIN OneBotInstance configuration editor. Owns the full lifecycle:
|
||||
* selection, load, in-memory edit (with dirty tracking), save (with refetch),
|
||||
* and a "switch UIN while dirty" guard that surfaces a pending switch the
|
||||
* view can confirm or cancel.
|
||||
*/
|
||||
/** Account-scoped editing, persistence, and unsaved-change confirmation. */
|
||||
export interface UseOneBotInstanceConfig {
|
||||
selectedUin: string | null;
|
||||
/** Loaded config for the current UIN. Null while loading or before a selection. */
|
||||
@@ -19,11 +14,7 @@ export interface UseOneBotInstanceConfig {
|
||||
setConfig: (next: OneBotConfig) => void;
|
||||
/** True if the in-memory config diverges from the last server-confirmed snapshot. */
|
||||
dirty: boolean;
|
||||
/**
|
||||
* Request a UIN switch. If currently dirty, the switch is parked as
|
||||
* `pendingSwitchUin` and must be confirmed or cancelled. Otherwise it
|
||||
* applies immediately.
|
||||
*/
|
||||
/** Dirty edits require confirmation before switching accounts. */
|
||||
requestSwitchUin: (uin: string) => void;
|
||||
/** Non-null while a switch is parked waiting for confirmation. */
|
||||
pendingSwitchUin: string | null;
|
||||
@@ -40,6 +31,14 @@ export interface UseOneBotInstanceConfig {
|
||||
saveStatusTone: 'idle' | 'saving' | 'success' | 'warning' | 'error';
|
||||
}
|
||||
|
||||
type ConfigState =
|
||||
| { status: 'idle'; uin: null }
|
||||
| { status: 'loading'; uin: string }
|
||||
| { status: 'error'; uin: string; error: string }
|
||||
| { status: 'ready'; uin: string; config: OneBotConfig; savedSnapshot: string };
|
||||
|
||||
type SaveFeedback = { text: string; tone: UseOneBotInstanceConfig['saveStatusTone'] };
|
||||
const IDLE_FEEDBACK: SaveFeedback = { text: '', tone: 'idle' };
|
||||
const CLEAR_SAVE_STATUS_MS = 3000;
|
||||
|
||||
export interface UseOneBotInstanceConfigOptions {
|
||||
@@ -56,19 +55,11 @@ export function useOneBotInstanceConfig(
|
||||
const api = useApi();
|
||||
const { runAction } = useActionFeedback();
|
||||
const { onSelectedUinChange } = options;
|
||||
// Start the first config request in the same render that receives the account
|
||||
// list; publishing the selection upward remains an effect, but no longer adds
|
||||
// an otherwise unnecessary render before the network request can begin.
|
||||
// Load the first account without waiting for selection to propagate upward.
|
||||
const selectedUin = options.selectedUin ?? accounts[0]?.uin ?? null;
|
||||
const [config, setConfigState] = useState<OneBotConfig | null>(null);
|
||||
const [loadedUin, setLoadedUin] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [state, setState] = useState<ConfigState>({ status: 'idle', uin: null });
|
||||
const [reloadGeneration, setReloadGeneration] = useState(0);
|
||||
const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
|
||||
const [saveStatus, setSaveStatus] = useState('');
|
||||
const [saveStatusTone, setSaveStatusTone] =
|
||||
useState<UseOneBotInstanceConfig['saveStatusTone']>('idle');
|
||||
const [saveFeedback, setSaveFeedback] = useState<SaveFeedback>(IDLE_FEEDBACK);
|
||||
const [pendingSwitchUin, setPendingSwitchUin] = useState<string | null>(null);
|
||||
const clearTimerRef = useRef<number | null>(null);
|
||||
const editRevisionRef = useRef(0);
|
||||
@@ -93,23 +84,15 @@ export function useOneBotInstanceConfig(
|
||||
clearTimerRef.current = null;
|
||||
}
|
||||
|
||||
setSaveStatus('');
|
||||
setSaveStatusTone('idle');
|
||||
setSaveFeedback(IDLE_FEEDBACK);
|
||||
setPendingSwitchUin(null);
|
||||
|
||||
if (!selectedUin) {
|
||||
setLoading(false);
|
||||
setLoadError(null);
|
||||
setConfigState(null);
|
||||
setLoadedUin(null);
|
||||
setSavedSnapshot(null);
|
||||
setState({ status: 'idle', uin: null });
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setLoadError(null);
|
||||
setConfigState(null);
|
||||
setLoadedUin(null);
|
||||
setSavedSnapshot(null);
|
||||
setState({ status: 'loading', uin: selectedUin });
|
||||
let cancelled = false;
|
||||
|
||||
(async () => {
|
||||
@@ -121,24 +104,28 @@ export function useOneBotInstanceConfig(
|
||||
}
|
||||
|
||||
editRevisionRef.current += 1;
|
||||
setConfigState(loaded);
|
||||
setLoadedUin(selectedUin);
|
||||
setSavedSnapshot(JSON.stringify(loaded));
|
||||
setState({
|
||||
status: 'ready',
|
||||
uin: selectedUin,
|
||||
config: loaded,
|
||||
savedSnapshot: JSON.stringify(loaded),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('load-config', e);
|
||||
|
||||
if (!cancelled) {
|
||||
setLoadError(e instanceof Error ? e.message : '加载账号配置失败');
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setLoading(false);
|
||||
setState({
|
||||
status: 'error',
|
||||
uin: selectedUin,
|
||||
error: e instanceof Error ? e.message : '加载账号配置失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
saveGenerationRef.current += 1;
|
||||
};
|
||||
}, [selectedUin, api, reloadGeneration]);
|
||||
|
||||
@@ -151,9 +138,11 @@ export function useOneBotInstanceConfig(
|
||||
[],
|
||||
);
|
||||
|
||||
const currentConfig = loadedUin === selectedUin ? config : null;
|
||||
const currentLoading =
|
||||
selectedUin !== null && (loading || (loadError === null && currentConfig === null));
|
||||
const current = state.uin === selectedUin ? state : null;
|
||||
const currentConfig = current?.status === 'ready' ? current.config : null;
|
||||
const savedSnapshot = current?.status === 'ready' ? current.savedSnapshot : null;
|
||||
const loading = selectedUin !== null && (!current || current.status === 'loading');
|
||||
const loadError = current?.status === 'error' ? current.error : null;
|
||||
|
||||
const dirty = useMemo(() => {
|
||||
if (currentConfig == null || savedSnapshot == null) {
|
||||
@@ -163,10 +152,17 @@ export function useOneBotInstanceConfig(
|
||||
return JSON.stringify(currentConfig) !== savedSnapshot;
|
||||
}, [currentConfig, savedSnapshot]);
|
||||
|
||||
const setConfig = useCallback((next: OneBotConfig) => {
|
||||
editRevisionRef.current += 1;
|
||||
setConfigState(next);
|
||||
}, []);
|
||||
const setConfig = useCallback(
|
||||
(next: OneBotConfig) => {
|
||||
editRevisionRef.current += 1;
|
||||
setState((previous) =>
|
||||
previous.status === 'ready' && previous.uin === selectedUin
|
||||
? { ...previous, config: next }
|
||||
: previous,
|
||||
);
|
||||
},
|
||||
[selectedUin],
|
||||
);
|
||||
const reload = useCallback(() => setReloadGeneration((generation) => generation + 1), []);
|
||||
|
||||
const requestSwitchUin = useCallback(
|
||||
@@ -207,8 +203,7 @@ export function useOneBotInstanceConfig(
|
||||
return;
|
||||
}
|
||||
|
||||
setSaveStatus('');
|
||||
setSaveStatusTone('idle');
|
||||
setSaveFeedback(IDLE_FEEDBACK);
|
||||
}, CLEAR_SAVE_STATUS_MS);
|
||||
}, []);
|
||||
|
||||
@@ -223,8 +218,7 @@ export function useOneBotInstanceConfig(
|
||||
const uin = selectedUin;
|
||||
const editRevision = editRevisionRef.current;
|
||||
const generation = ++saveGenerationRef.current;
|
||||
setSaveStatus('保存中...');
|
||||
setSaveStatusTone('saving');
|
||||
setSaveFeedback({ text: '保存中…', tone: 'saving' });
|
||||
|
||||
try {
|
||||
const result = await runAction(
|
||||
@@ -259,39 +253,49 @@ export function useOneBotInstanceConfig(
|
||||
}
|
||||
|
||||
if (!result.saved) {
|
||||
setSaveStatus(`保存失败:${result.message || '服务器未确认配置已保存'}`);
|
||||
setSaveStatusTone('error');
|
||||
setSaveFeedback({
|
||||
text: `保存失败:${result.message || '服务器未确认配置已保存'}`,
|
||||
tone: 'error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setSavedSnapshot(JSON.stringify(result.config));
|
||||
const unchanged = editRevisionRef.current === editRevision;
|
||||
setState((previous) =>
|
||||
previous.status === 'ready' && previous.uin === uin
|
||||
? {
|
||||
...previous,
|
||||
config: unchanged ? result.config : previous.config,
|
||||
savedSnapshot: JSON.stringify(result.config),
|
||||
}
|
||||
: previous,
|
||||
);
|
||||
|
||||
if (editRevisionRef.current === editRevision) {
|
||||
setConfigState(result.config);
|
||||
} else {
|
||||
setSaveStatus('上一版本已保存,当前修改仍待保存');
|
||||
setSaveStatusTone('warning');
|
||||
if (!unchanged) {
|
||||
setSaveFeedback({ text: '上一版本已保存,当前修改待保存', tone: 'warning' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!result.online) {
|
||||
setSaveStatus('保存成功;当前离线,将在下次连接时应用');
|
||||
setSaveStatusTone('warning');
|
||||
setSaveFeedback({ text: '已保存,下次连接时应用', tone: 'warning' });
|
||||
} else if (result.applied) {
|
||||
setSaveStatus('保存成功,热重载完成');
|
||||
setSaveStatusTone('success');
|
||||
setSaveFeedback({ text: '已保存并应用', tone: 'success' });
|
||||
} else {
|
||||
const first = result.errors[0]?.message;
|
||||
setSaveStatus(`保存成功,但热重载失败${first ? `:${first}` : ''}`);
|
||||
setSaveStatusTone('warning');
|
||||
setSaveFeedback({
|
||||
text: `已保存,但热重载失败${first ? `:${first}` : ''}`,
|
||||
tone: 'warning',
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`);
|
||||
setSaveStatusTone('error');
|
||||
setSaveFeedback({
|
||||
text: `保存失败:${e instanceof Error ? e.message : '未知错误'}`,
|
||||
tone: 'error',
|
||||
});
|
||||
} finally {
|
||||
if (selectedUinRef.current === uin && saveGenerationRef.current === generation) {
|
||||
scheduleStatusClear(uin, generation);
|
||||
@@ -304,7 +308,7 @@ export function useOneBotInstanceConfig(
|
||||
return {
|
||||
selectedUin,
|
||||
config: currentConfig,
|
||||
loading: currentLoading,
|
||||
loading,
|
||||
loadError,
|
||||
reload,
|
||||
setConfig,
|
||||
@@ -314,7 +318,7 @@ export function useOneBotInstanceConfig(
|
||||
confirmSwitch,
|
||||
cancelSwitch,
|
||||
save,
|
||||
saveStatus,
|
||||
saveStatusTone,
|
||||
saveStatus: saveFeedback.text,
|
||||
saveStatusTone: saveFeedback.tone,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import type { ApiClient, StateStreamEvent } from '@/lib/api/types';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||
|
||||
export interface AppResourceData {
|
||||
qqList: QQInfo[];
|
||||
processList: HookProcessInfo[];
|
||||
systemInfo: SystemInfo | null;
|
||||
connections: AccountConnections[];
|
||||
updateInfo: UpdateInfo | null;
|
||||
}
|
||||
|
||||
export type AppResources = {
|
||||
[K in keyof AppResourceData]: {
|
||||
data: AppResourceData[K];
|
||||
ready: boolean;
|
||||
error: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
type ResourceKey = keyof AppResourceData;
|
||||
|
||||
const LOAD_ERRORS: Record<ResourceKey, string> = {
|
||||
qqList: '加载账号列表失败',
|
||||
processList: '加载进程列表失败',
|
||||
systemInfo: '加载系统信息失败',
|
||||
connections: '加载连接状态失败',
|
||||
updateInfo: '检查更新失败',
|
||||
};
|
||||
|
||||
export function createAppResources(api: ApiClient) {
|
||||
let snapshot: AppResources = {
|
||||
qqList: { data: [], ready: false, error: null },
|
||||
processList: { data: [], ready: false, error: null },
|
||||
systemInfo: { data: null, ready: false, error: null },
|
||||
connections: { data: [], ready: false, error: null },
|
||||
updateInfo: { data: null, ready: false, error: null },
|
||||
};
|
||||
const revisions: Record<ResourceKey, number> = {
|
||||
qqList: 0,
|
||||
processList: 0,
|
||||
systemInfo: 0,
|
||||
connections: 0,
|
||||
updateInfo: 0,
|
||||
};
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function settle<K extends ResourceKey>(
|
||||
key: K,
|
||||
data: AppResourceData[K],
|
||||
error: string | null = null,
|
||||
) {
|
||||
snapshot = { ...snapshot, [key]: { data, ready: true, error } };
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
async function refresh<K extends ResourceKey>(
|
||||
key: K,
|
||||
load: () => Promise<AppResourceData[K]>,
|
||||
throwOnError = false,
|
||||
): Promise<AppResourceData[K] | null> {
|
||||
const revision = ++revisions[key];
|
||||
|
||||
try {
|
||||
const data = await load();
|
||||
|
||||
if (revisions[key] !== revision) {
|
||||
return null;
|
||||
}
|
||||
|
||||
settle(key, data);
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (revisions[key] !== revision) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const message =
|
||||
error instanceof Error && error.message ? error.message : LOAD_ERRORS[key];
|
||||
settle(key, snapshot[key].data, message);
|
||||
|
||||
if (throwOnError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function publish<K extends ResourceKey>(key: K, data: AppResourceData[K]) {
|
||||
// A pushed snapshot supersedes any pending REST response for this resource.
|
||||
revisions[key] += 1;
|
||||
settle(key, data);
|
||||
}
|
||||
|
||||
const refreshQqList = async () => {
|
||||
await refresh('qqList', () => api.qqList());
|
||||
};
|
||||
|
||||
const refreshProcesses = async () => {
|
||||
await refresh('processList', () => api.processes.list());
|
||||
};
|
||||
|
||||
const refreshSystem = async () => {
|
||||
await refresh('systemInfo', () => api.system());
|
||||
};
|
||||
|
||||
const refreshConnections = async () => {
|
||||
await refresh('connections', () => api.connections());
|
||||
};
|
||||
|
||||
const refreshUpdate = (force = false) =>
|
||||
refresh('updateInfo', () => api.update.check(force), force);
|
||||
|
||||
const reconcile = async () => {
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
|
||||
};
|
||||
|
||||
return {
|
||||
getSnapshot: () => snapshot,
|
||||
subscribe: (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
invalidate: () => {
|
||||
for (const key of Object.keys(revisions) as ResourceKey[]) {
|
||||
revisions[key] += 1;
|
||||
}
|
||||
},
|
||||
onEvent: (event: StateStreamEvent) => {
|
||||
if ('resource' in event) {
|
||||
switch (event.resource) {
|
||||
case 'qq-list':
|
||||
publish('qqList', event.data);
|
||||
break;
|
||||
case 'processes':
|
||||
publish('processList', event.data);
|
||||
break;
|
||||
case 'connections':
|
||||
publish('connections', event.data);
|
||||
break;
|
||||
}
|
||||
} else if (event.kind === 'dropped') {
|
||||
void reconcile();
|
||||
}
|
||||
},
|
||||
reconcile,
|
||||
refreshQqList,
|
||||
refreshProcesses,
|
||||
refreshSystem,
|
||||
refreshConnections,
|
||||
refreshUpdate,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import type { ApiClient } from '@/lib/api/types';
|
||||
import type { PickerOption } from '@/components/ui/picker';
|
||||
|
||||
const TTL_MS = 5 * 60_000;
|
||||
const LS_KEY = 'snowluma.debug.contacts.v1';
|
||||
|
||||
export function userAvatar(uin: string | number): string {
|
||||
return `https://q1.qlogo.cn/g?b=qq&nk=${uin}&s=100`;
|
||||
}
|
||||
|
||||
export function groupAvatar(gid: string | number): string {
|
||||
return `https://p.qlogo.cn/gh/${gid}/${gid}/100`;
|
||||
}
|
||||
|
||||
interface Entry {
|
||||
at: number;
|
||||
items: PickerOption[];
|
||||
}
|
||||
|
||||
// Rebuild avatar URLs rather than storing them for every member.
|
||||
function avatarFor(key: string, value: string): string | undefined {
|
||||
if (key.startsWith('groups:')) {
|
||||
return groupAvatar(value);
|
||||
}
|
||||
|
||||
if (key.startsWith('friends:') || key.startsWith('members:')) {
|
||||
return userAvatar(value);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const mem = new Map<string, Entry>();
|
||||
let hydrated = false;
|
||||
|
||||
function hydrate(): void {
|
||||
if (hydrated) {
|
||||
return;
|
||||
}
|
||||
|
||||
hydrated = true;
|
||||
|
||||
try {
|
||||
const raw = localStorage.getItem(LS_KEY);
|
||||
|
||||
if (raw) {
|
||||
const obj = JSON.parse(raw) as Record<string, Entry>;
|
||||
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
if (v && Array.isArray(v.items)) {
|
||||
mem.set(k, {
|
||||
at: v.at,
|
||||
items: v.items.map((it) => ({
|
||||
...it,
|
||||
avatar: avatarFor(k, it.value),
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* corrupt / unavailable — start empty */
|
||||
}
|
||||
}
|
||||
|
||||
function persist(): void {
|
||||
try {
|
||||
const obj: Record<string, Entry> = {};
|
||||
|
||||
// Strip the derivable avatar to keep the serialized blob small.
|
||||
for (const [k, v] of mem) {
|
||||
obj[k] = {
|
||||
at: v.at,
|
||||
items: v.items.map((it) => ({ value: it.value, label: it.label, sub: it.sub })),
|
||||
};
|
||||
}
|
||||
|
||||
localStorage.setItem(LS_KEY, JSON.stringify(obj));
|
||||
} catch {
|
||||
/* quota / unavailable — memory cache still works */
|
||||
}
|
||||
}
|
||||
|
||||
export type ContactKind = 'friends' | 'groups' | 'members';
|
||||
|
||||
export interface ContactListState {
|
||||
items: PickerOption[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
const ACTIONS: Record<ContactKind, string> = {
|
||||
friends: 'get_friend_list',
|
||||
groups: 'get_group_list',
|
||||
members: 'get_group_member_list',
|
||||
};
|
||||
|
||||
function parseContact(kind: ContactKind, row: unknown): PickerOption | null {
|
||||
if (!row || typeof row !== 'object' || Array.isArray(row)) {
|
||||
throw new Error('联系人列表格式无效');
|
||||
}
|
||||
|
||||
const fields = row as Record<string, unknown>;
|
||||
const id = kind === 'groups' ? fields.group_id : fields.user_id;
|
||||
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof id !== 'string' && typeof id !== 'number') {
|
||||
throw new Error('联系人 ID 格式无效');
|
||||
}
|
||||
|
||||
const value = String(id);
|
||||
const names =
|
||||
kind === 'groups'
|
||||
? [fields.group_name]
|
||||
: kind === 'friends'
|
||||
? [fields.remark, fields.nickname]
|
||||
: [fields.card, fields.nickname];
|
||||
const label =
|
||||
names.find((name): name is string => typeof name === 'string' && name !== '') ?? value;
|
||||
return {
|
||||
value,
|
||||
label,
|
||||
sub: value,
|
||||
avatar: kind === 'groups' ? groupAvatar(value) : userAvatar(value),
|
||||
};
|
||||
}
|
||||
|
||||
export function createContactList(
|
||||
invoke: ApiClient['debug']['invoke'],
|
||||
kind: ContactKind,
|
||||
uin: string,
|
||||
groupId = '',
|
||||
) {
|
||||
hydrate();
|
||||
const key =
|
||||
uin && (kind !== 'members' || groupId)
|
||||
? `${kind}:${uin}${kind === 'members' ? `:${groupId}` : ''}`
|
||||
: null;
|
||||
const cached = key ? mem.get(key) : undefined;
|
||||
let state: ContactListState = { items: cached?.items ?? [], loading: false, error: null };
|
||||
let revision = 0;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function publish(next: ContactListState) {
|
||||
state = next;
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
async function refresh(force = true): Promise<void> {
|
||||
const request = ++revision;
|
||||
|
||||
if (!key) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hit = mem.get(key);
|
||||
|
||||
if (!force && hit && Date.now() - hit.at < TTL_MS) {
|
||||
publish({ items: hit.items, loading: false, error: null });
|
||||
return;
|
||||
}
|
||||
|
||||
publish({ ...state, loading: true, error: null });
|
||||
|
||||
try {
|
||||
const result = await invoke(
|
||||
uin,
|
||||
ACTIONS[kind],
|
||||
kind === 'members' ? { group_id: groupId } : {},
|
||||
);
|
||||
|
||||
if (request !== revision) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status !== 'ok') {
|
||||
throw new Error(result.message || result.wording || '加载失败');
|
||||
}
|
||||
|
||||
if (!Array.isArray(result.data)) {
|
||||
throw new Error('联系人列表格式无效');
|
||||
}
|
||||
|
||||
const items = result.data
|
||||
.map((row) => parseContact(kind, row))
|
||||
.filter((item) => item !== null);
|
||||
mem.set(key, { at: Date.now(), items });
|
||||
persist();
|
||||
publish({ items, loading: false, error: null });
|
||||
} catch (error) {
|
||||
if (request === revision) {
|
||||
publish({
|
||||
...state,
|
||||
loading: false,
|
||||
error: error instanceof Error ? error.message : '加载失败',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getSnapshot: () => state,
|
||||
subscribe: (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
},
|
||||
refresh,
|
||||
invalidate: () => {
|
||||
revision += 1;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Run immediately, then at the requested cadence without overlapping requests. */
|
||||
export function startPolling(
|
||||
refresh: () => Promise<unknown>,
|
||||
intervalMs: number,
|
||||
pauseWhenHidden = true,
|
||||
): () => void {
|
||||
let running = false;
|
||||
|
||||
const tick = async () => {
|
||||
if (running || (pauseWhenHidden && document.hidden)) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await refresh();
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
void tick();
|
||||
const interval = intervalMs > 0 ? setInterval(tick, intervalMs) : null;
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
|
||||
if (pauseWhenHidden) {
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (interval !== null) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
if (pauseWhenHidden) {
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -8,43 +8,12 @@ import { NAV_ITEMS } from '@/components/layout/sidebar';
|
||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||
import { LowIntegrityWarning } from '@/components/low-integrity-warning';
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
import { AppStateProvider, type AppResourceState } from '@/contexts/AppStateContext';
|
||||
import { AppStateProvider } from '@/contexts/AppStateContext';
|
||||
import { useAppResources } from '@/hooks/use-app-resources';
|
||||
import { KioskProvider } from '@/contexts/KioskContext';
|
||||
import { LayoutProvider, useLayout } from '@/contexts/LayoutContext';
|
||||
import { useSession } from '@/contexts/SessionContext';
|
||||
import type { AppPath } from '@/router';
|
||||
import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo, UpdateInfo } from '@/types';
|
||||
|
||||
function createInitialResources(): AppResourceState {
|
||||
return {
|
||||
qqList: { ready: false, error: null },
|
||||
processList: { ready: false, error: null },
|
||||
systemInfo: { ready: false, error: null },
|
||||
connections: { ready: false, error: null },
|
||||
updateInfo: { ready: false, error: null },
|
||||
};
|
||||
}
|
||||
|
||||
type AppResourceKey = keyof AppResourceState;
|
||||
|
||||
function createResourceCounters(): Record<AppResourceKey, number> {
|
||||
return {
|
||||
qqList: 0,
|
||||
processList: 0,
|
||||
systemInfo: 0,
|
||||
connections: 0,
|
||||
updateInfo: 0,
|
||||
};
|
||||
}
|
||||
|
||||
interface ResourceRequestTicket {
|
||||
generation: number;
|
||||
streamRevision: number;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return error instanceof Error && error.message ? error.message : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to the operator's configured landing page once (after the layout
|
||||
@@ -79,12 +48,6 @@ function DefaultRouteRedirect() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The layout route. Owns the live state shared across the four pages
|
||||
* (polling lists, processOps, selectedUin) and renders `<Outlet />` inside
|
||||
* the chrome. The unload-failed alert sits here so it survives navigation
|
||||
* away from the overview page.
|
||||
*/
|
||||
export function AppLayout() {
|
||||
const api = useApi();
|
||||
const { pollInterval, reloadAppearance } = useTheme();
|
||||
@@ -96,171 +59,9 @@ export function AppLayout() {
|
||||
void reloadAppearance();
|
||||
}, [reloadAppearance]);
|
||||
|
||||
const [qqList, setQqList] = useState<QQInfo[]>([]);
|
||||
const [processList, setProcessList] = useState<HookProcessInfo[]>([]);
|
||||
const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);
|
||||
const [connections, setConnections] = useState<AccountConnections[]>([]);
|
||||
const [updateInfo, setUpdateInfo] = useState<UpdateInfo | null>(null);
|
||||
const [resources, setResources] = useState<AppResourceState>(createInitialResources);
|
||||
const data = useAppResources(pollInterval);
|
||||
const { connections, refreshProcesses, systemInfo } = data;
|
||||
const [selectedUin, setSelectedUin] = useState<string | null>(null);
|
||||
const requestGenerationRef = useRef(createResourceCounters());
|
||||
const streamRevisionRef = useRef(createResourceCounters());
|
||||
|
||||
const settleResource = useCallback((resource: AppResourceKey, error: string | null) => {
|
||||
setResources((current) => ({
|
||||
...current,
|
||||
[resource]: { ready: true, error },
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const beginResourceRequest = useCallback(
|
||||
(resource: AppResourceKey): ResourceRequestTicket => ({
|
||||
generation: ++requestGenerationRef.current[resource],
|
||||
streamRevision: streamRevisionRef.current[resource],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const isCurrentResourceRequest = useCallback(
|
||||
(resource: AppResourceKey, ticket: ResourceRequestTicket): boolean =>
|
||||
requestGenerationRef.current[resource] === ticket.generation &&
|
||||
streamRevisionRef.current[resource] === ticket.streamRevision,
|
||||
[],
|
||||
);
|
||||
|
||||
const settleStreamResource = useCallback(
|
||||
(resource: AppResourceKey) => {
|
||||
streamRevisionRef.current[resource] += 1;
|
||||
settleResource(resource, null);
|
||||
},
|
||||
[settleResource],
|
||||
);
|
||||
|
||||
const refreshQqList = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('qqList');
|
||||
|
||||
try {
|
||||
const next = await api.qqList();
|
||||
|
||||
if (!isCurrentResourceRequest('qqList', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setQqList(next);
|
||||
settleResource('qqList', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('qqList', ticket)) {
|
||||
console.warn('ignored stale qq-list request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('qq-list', e);
|
||||
settleResource('qqList', errorMessage(e, '加载账号列表失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshProcesses = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('processList');
|
||||
|
||||
try {
|
||||
const next = await api.processes.list();
|
||||
|
||||
if (!isCurrentResourceRequest('processList', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setProcessList(next);
|
||||
settleResource('processList', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('processList', ticket)) {
|
||||
console.warn('ignored stale process-list request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('processes', e);
|
||||
settleResource('processList', errorMessage(e, '加载进程列表失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshSystem = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('systemInfo');
|
||||
|
||||
try {
|
||||
const next = await api.system();
|
||||
|
||||
if (!isCurrentResourceRequest('systemInfo', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSystemInfo(next);
|
||||
settleResource('systemInfo', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('systemInfo', ticket)) {
|
||||
console.warn('ignored stale system-info request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('system', e);
|
||||
settleResource('systemInfo', errorMessage(e, '加载系统信息失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshConnections = useCallback(async () => {
|
||||
const ticket = beginResourceRequest('connections');
|
||||
|
||||
try {
|
||||
const next = await api.connections();
|
||||
|
||||
if (!isCurrentResourceRequest('connections', ticket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setConnections(next);
|
||||
settleResource('connections', null);
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('connections', ticket)) {
|
||||
console.warn('ignored stale connections request failure', e);
|
||||
return;
|
||||
}
|
||||
|
||||
console.error('connections', e);
|
||||
settleResource('connections', errorMessage(e, '加载连接状态失败'));
|
||||
}
|
||||
}, [api, beginResourceRequest, isCurrentResourceRequest, settleResource]);
|
||||
|
||||
const refreshUpdate = useCallback(
|
||||
async (force = false) => {
|
||||
const ticket = beginResourceRequest('updateInfo');
|
||||
|
||||
try {
|
||||
const next = await api.update.check(force);
|
||||
|
||||
if (!isCurrentResourceRequest('updateInfo', ticket)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
setUpdateInfo(next);
|
||||
settleResource('updateInfo', null);
|
||||
return next;
|
||||
} catch (e) {
|
||||
if (!isCurrentResourceRequest('updateInfo', ticket)) {
|
||||
console.warn('ignored stale update-check request failure', e);
|
||||
return null;
|
||||
}
|
||||
|
||||
console.error('update-check', e);
|
||||
settleResource('updateInfo', errorMessage(e, '检查更新失败'));
|
||||
|
||||
if (force) {
|
||||
throw e;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[api, beginResourceRequest, isCurrentResourceRequest, settleResource],
|
||||
);
|
||||
|
||||
const {
|
||||
ops: processOps,
|
||||
unloadFailedAlert,
|
||||
@@ -269,182 +70,8 @@ export function AppLayout() {
|
||||
onAfterOp: refreshProcesses,
|
||||
});
|
||||
|
||||
// Primary live-state path: subscribe to /api/state/stream and apply
|
||||
// pushed snapshots directly. Initial frames on connect prime
|
||||
// processes/qqList/connections without a polling tick.
|
||||
//
|
||||
// On `{kind:'dropped'}` (backpressure made the server skip some frames),
|
||||
// a per-resource SSE auto-recovery is NOT guaranteed: the next delivered
|
||||
// frame is whatever resource next changes, not necessarily the one whose
|
||||
// update we lost. So on dropped, kick a one-shot REST reconcile to
|
||||
// recover immediately instead of waiting up to 30s for the fallback.
|
||||
useEffect(() => {
|
||||
const dispose = api.stateStream({
|
||||
onEvent: (event) => {
|
||||
if ('resource' in event) {
|
||||
if (event.resource === 'processes') {
|
||||
setProcessList(event.data);
|
||||
settleStreamResource('processList');
|
||||
} else if (event.resource === 'qq-list') {
|
||||
setQqList(event.data);
|
||||
settleStreamResource('qqList');
|
||||
} else if (event.resource === 'connections') {
|
||||
setConnections(event.data);
|
||||
settleStreamResource('connections');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ('kind' in event && event.kind === 'dropped') {
|
||||
// Fire-and-forget; each refresh has its own try/catch.
|
||||
void refreshQqList();
|
||||
void refreshProcesses();
|
||||
void refreshConnections();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
return () => {
|
||||
dispose();
|
||||
};
|
||||
}, [api, refreshQqList, refreshProcesses, refreshConnections, settleStreamResource]);
|
||||
|
||||
// Slow reconcile fallback for the SSE-covered resources. SSE drops can
|
||||
// be silent (proxy rewrites text/event-stream, tab thrashing). One REST
|
||||
// tick per (pollInterval × 10, min 10s) recovers from those without
|
||||
// hammering the server.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let running = false;
|
||||
const reconcileMs = Math.max(pollInterval * 10, 10_000);
|
||||
|
||||
const tick = async () => {
|
||||
// Skip while the tab is hidden — SSE already carries live updates, and a
|
||||
// backgrounded tab has no UI to refresh. Re-tick on becoming visible.
|
||||
// `running` drops a tick while the previous refresh is still in flight,
|
||||
// so a slow backend can't stack overlapping requests.
|
||||
if (cancelled || document.hidden || running) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Initial tick primes the lists before the SSE handshake completes
|
||||
// (avoids a flash of empty state in the chrome).
|
||||
tick();
|
||||
const interval = pollInterval > 0 ? setInterval(tick, reconcileMs) : null;
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
if (interval !== null) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [pollInterval, refreshQqList, refreshProcesses, refreshConnections]);
|
||||
|
||||
// systemInfo has its OWN fast cadence — it carries live values (uptime,
|
||||
// cpu loadAvg, memory.usagePercent, runtime.heapUsed) that the overview
|
||||
// widget visibly animates. It isn't on the SSE feed, so a 30s reconcile
|
||||
// would visibly lag the dashboard. Keep the user's configured
|
||||
// pollInterval (default 3s) here.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let running = false;
|
||||
|
||||
const tick = async () => {
|
||||
if (cancelled || document.hidden || running) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await refreshSystem();
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const interval = pollInterval > 0 ? setInterval(tick, pollInterval) : null;
|
||||
|
||||
const onVisible = () => {
|
||||
if (!document.hidden) {
|
||||
void tick();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
|
||||
if (interval !== null) {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [pollInterval, refreshSystem]);
|
||||
|
||||
// Update check runs on its own slow cadence (6h), independent of the fast
|
||||
// list-polling above — GitHub's API is rate-limited, the result rarely
|
||||
// changes, and the server caches it anyway, so this is cheap.
|
||||
useEffect(() => {
|
||||
let running = false;
|
||||
|
||||
const tick = async () => {
|
||||
if (running) {
|
||||
return;
|
||||
}
|
||||
|
||||
running = true;
|
||||
|
||||
try {
|
||||
await refreshUpdate();
|
||||
} finally {
|
||||
running = false;
|
||||
}
|
||||
};
|
||||
|
||||
tick();
|
||||
const id = setInterval(tick, 6 * 60 * 60 * 1000);
|
||||
return () => clearInterval(id);
|
||||
}, [refreshUpdate]);
|
||||
|
||||
const handleLogout = useCallback(async () => {
|
||||
for (const resource of Object.keys(requestGenerationRef.current) as AppResourceKey[]) {
|
||||
requestGenerationRef.current[resource] += 1;
|
||||
streamRevisionRef.current[resource] += 1;
|
||||
}
|
||||
|
||||
await api.logout();
|
||||
setQqList([]);
|
||||
setProcessList([]);
|
||||
setSystemInfo(null);
|
||||
setConnections([]);
|
||||
setUpdateInfo(null);
|
||||
setResources(createInitialResources());
|
||||
setSelectedUin(null);
|
||||
session.onLogoutComplete();
|
||||
}, [api, session]);
|
||||
|
||||
@@ -486,7 +113,7 @@ export function AppLayout() {
|
||||
className="border-b border-warning/25 bg-warning/10 px-4 py-2.5 text-sm text-warning-foreground sm:px-6 lg:px-8"
|
||||
>
|
||||
<span className="font-medium">账号数据库状态:</span>
|
||||
{parts.join(';')}。请查看概览详情。
|
||||
{parts.join(';')}
|
||||
</div>
|
||||
);
|
||||
}, [connections]);
|
||||
@@ -494,20 +121,10 @@ export function AppLayout() {
|
||||
return (
|
||||
<AppStateProvider
|
||||
value={{
|
||||
qqList,
|
||||
processList,
|
||||
systemInfo,
|
||||
connections,
|
||||
updateInfo,
|
||||
resources,
|
||||
...data,
|
||||
selectedUin,
|
||||
setSelectedUin,
|
||||
processOps,
|
||||
refreshQqList,
|
||||
refreshProcesses,
|
||||
refreshSystem,
|
||||
refreshConnections,
|
||||
refreshUpdate,
|
||||
onLogout: handleLogout,
|
||||
}}
|
||||
>
|
||||
@@ -541,7 +158,7 @@ export function AppLayout() {
|
||||
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
|
||||
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
|
||||
如需彻底卸载,请重启 QQ。
|
||||
</p>
|
||||
</>
|
||||
) : null
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { createApiClient } from '../src/lib/api/client';
|
||||
import { createAppResources } from '../src/lib/app-resources';
|
||||
import type { QQInfo } from '../src/types';
|
||||
|
||||
function setup() {
|
||||
const api = createApiClient({ tokenStore: { load: () => null, save: () => undefined } });
|
||||
vi.spyOn(api, 'qqList').mockResolvedValue([]);
|
||||
vi.spyOn(api.processes, 'list').mockResolvedValue([]);
|
||||
vi.spyOn(api, 'connections').mockResolvedValue([]);
|
||||
return { api, store: createAppResources(api) };
|
||||
}
|
||||
|
||||
const accounts: QQInfo[] = [{ uin: '12345', nickname: '当前账号' }];
|
||||
|
||||
describe('app resources', () => {
|
||||
it('publishes data and load status together, distinguishing an empty result from an initial load', async () => {
|
||||
const { store } = setup();
|
||||
const initial = store.getSnapshot();
|
||||
expect(initial.qqList).toEqual({ data: [], ready: false, error: null });
|
||||
const listener = vi.fn(() => {
|
||||
expect(store.getSnapshot().qqList).toEqual({ data: [], ready: true, error: null });
|
||||
});
|
||||
const unsubscribe = store.subscribe(listener);
|
||||
await store.refreshQqList();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
expect(initial.qqList.ready).toBe(false);
|
||||
unsubscribe();
|
||||
await store.refreshQqList();
|
||||
expect(listener).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('keeps the latest request when an older request completes later', async () => {
|
||||
const { api, store } = setup();
|
||||
const old = Promise.withResolvers<QQInfo[]>();
|
||||
vi.mocked(api.qqList).mockReturnValueOnce(old.promise).mockResolvedValueOnce(accounts);
|
||||
const first = store.refreshQqList();
|
||||
await store.refreshQqList();
|
||||
old.resolve([]);
|
||||
await first;
|
||||
expect(store.getSnapshot().qqList.data).toEqual(accounts);
|
||||
});
|
||||
|
||||
it.each(['success', 'failure'])(
|
||||
'keeps a pushed snapshot after a stale REST %s',
|
||||
async (outcome) => {
|
||||
const { api, store } = setup();
|
||||
const request = Promise.withResolvers<QQInfo[]>();
|
||||
vi.mocked(api.qqList).mockReturnValueOnce(request.promise);
|
||||
const pending = store.refreshQqList();
|
||||
store.onEvent({ resource: 'qq-list', data: accounts });
|
||||
const snapshot = store.getSnapshot();
|
||||
|
||||
if (outcome === 'success') {
|
||||
request.resolve([]);
|
||||
} else {
|
||||
request.reject(new Error('过期请求失败'));
|
||||
}
|
||||
|
||||
await pending;
|
||||
expect(store.getSnapshot()).toBe(snapshot);
|
||||
expect(snapshot.qqList).toEqual({ data: accounts, ready: true, error: null });
|
||||
},
|
||||
);
|
||||
|
||||
it('does not invalidate a different resource when receiving a push', async () => {
|
||||
const { api, store } = setup();
|
||||
vi.mocked(api.qqList).mockResolvedValueOnce(accounts);
|
||||
const pending = store.refreshQqList();
|
||||
store.onEvent({ resource: 'connections', data: [] });
|
||||
await pending;
|
||||
expect(store.getSnapshot().qqList.data).toEqual(accounts);
|
||||
expect(store.getSnapshot().connections.ready).toBe(true);
|
||||
});
|
||||
|
||||
it('retains the last data on failure and clears the error on recovery', async () => {
|
||||
const { api, store } = setup();
|
||||
store.onEvent({ resource: 'qq-list', data: accounts });
|
||||
vi.mocked(api.qqList).mockRejectedValueOnce(new Error('连接中断'));
|
||||
await store.refreshQqList();
|
||||
expect(store.getSnapshot().qqList).toEqual({
|
||||
data: accounts,
|
||||
ready: true,
|
||||
error: '连接中断',
|
||||
});
|
||||
await store.refreshQqList();
|
||||
expect(store.getSnapshot().qqList).toEqual({ data: [], ready: true, error: null });
|
||||
});
|
||||
|
||||
it('invalidates pending work on cleanup and allows a new subscription cycle', async () => {
|
||||
const { api, store } = setup();
|
||||
const request = Promise.withResolvers<QQInfo[]>();
|
||||
vi.mocked(api.qqList).mockReturnValueOnce(request.promise);
|
||||
const pending = store.refreshQqList();
|
||||
const initial = store.getSnapshot();
|
||||
store.invalidate();
|
||||
request.resolve(accounts);
|
||||
await pending;
|
||||
expect(store.getSnapshot()).toBe(initial);
|
||||
await store.refreshQqList();
|
||||
expect(store.getSnapshot().qqList.ready).toBe(true);
|
||||
});
|
||||
|
||||
it('reconciles all stream resources when frames are dropped', async () => {
|
||||
const { api, store } = setup();
|
||||
store.onEvent({ kind: 'ready' });
|
||||
expect(api.qqList).not.toHaveBeenCalled();
|
||||
store.onEvent({ kind: 'dropped', count: 3 });
|
||||
await vi.waitFor(() => expect(store.getSnapshot().connections.ready).toBe(true));
|
||||
expect(api.qqList).toHaveBeenCalledOnce();
|
||||
expect(api.processes.list).toHaveBeenCalledOnce();
|
||||
expect(api.connections).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('reports background update failures but rejects an explicit forced check', async () => {
|
||||
const { api, store } = setup();
|
||||
vi.spyOn(api.update, 'check').mockRejectedValue(new Error('检查失败'));
|
||||
await expect(store.refreshUpdate()).resolves.toBeNull();
|
||||
expect(store.getSnapshot().updateInfo.error).toBe('检查失败');
|
||||
await expect(store.refreshUpdate(true)).rejects.toThrow('检查失败');
|
||||
expect(api.update.check).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createContactList } from '../src/lib/debug-contacts';
|
||||
import type { DebugInvokeResult } from '../src/types';
|
||||
|
||||
function deferred() {
|
||||
let resolve!: (result: DebugInvokeResult) => void;
|
||||
const promise = new Promise<DebugInvokeResult>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
const success = (nickname: string): DebugInvokeResult => ({
|
||||
status: 'ok',
|
||||
data: [{ user_id: 123, nickname }],
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('localStorage', { getItem: () => null, setItem: vi.fn() });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('debug contact lists', () => {
|
||||
it('keeps account state separate and ignores a response after leaving its list', async () => {
|
||||
const previous = deferred();
|
||||
const invoke = vi
|
||||
.fn()
|
||||
.mockReturnValueOnce(previous.promise)
|
||||
.mockResolvedValue(success('current'));
|
||||
const oldList = createContactList(invoke, 'friends', 'old-account');
|
||||
const pending = oldList.refresh();
|
||||
oldList.invalidate();
|
||||
const current = createContactList(invoke, 'friends', 'new-account');
|
||||
await current.refresh();
|
||||
previous.resolve(success('stale'));
|
||||
await pending;
|
||||
expect(current.getSnapshot().items[0].label).toBe('current');
|
||||
expect(oldList.getSnapshot().items).toEqual([]);
|
||||
expect(createContactList(invoke, 'friends', 'old-account').getSnapshot().items).toEqual([]);
|
||||
});
|
||||
|
||||
it('supersedes an in-flight refresh when using a fresh cached list', async () => {
|
||||
const pending = deferred();
|
||||
const invoke = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(success('cached'))
|
||||
.mockReturnValueOnce(pending.promise);
|
||||
const list = createContactList(invoke, 'friends', 'cache-account');
|
||||
await list.refresh();
|
||||
const refresh = list.refresh();
|
||||
await list.refresh(false);
|
||||
expect(list.getSnapshot().loading).toBe(false);
|
||||
pending.resolve(success('superseded'));
|
||||
await refresh;
|
||||
expect(list.getSnapshot().items[0].label).toBe('cached');
|
||||
});
|
||||
|
||||
it('ignores an earlier refresh that completes after its replacement', async () => {
|
||||
const first = deferred();
|
||||
const invoke = vi
|
||||
.fn()
|
||||
.mockReturnValueOnce(first.promise)
|
||||
.mockResolvedValueOnce(success('latest'));
|
||||
const list = createContactList(invoke, 'friends', 'race-account');
|
||||
const pending = list.refresh();
|
||||
await list.refresh();
|
||||
first.resolve(success('old'));
|
||||
await pending;
|
||||
expect(list.getSnapshot().items[0].label).toBe('latest');
|
||||
});
|
||||
|
||||
it('keeps group-member caches scoped to the account and group', async () => {
|
||||
const invoke = vi.fn().mockResolvedValue(success('member'));
|
||||
const first = createContactList(invoke, 'members', 'member-account', '111');
|
||||
await first.refresh();
|
||||
expect(invoke).toHaveBeenCalledWith('member-account', 'get_group_member_list', {
|
||||
group_id: '111',
|
||||
});
|
||||
expect(
|
||||
createContactList(invoke, 'members', 'member-account', '111').getSnapshot().items,
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
createContactList(invoke, 'members', 'member-account', '222').getSnapshot().items,
|
||||
).toEqual([]);
|
||||
expect(
|
||||
createContactList(invoke, 'members', 'other-account', '111').getSnapshot().items,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('reports malformed successful responses instead of caching an empty list', async () => {
|
||||
const invoke = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(success('retained'))
|
||||
.mockResolvedValueOnce({ status: 'ok', data: {} });
|
||||
const list = createContactList(invoke, 'friends', 'invalid-account');
|
||||
await list.refresh();
|
||||
await list.refresh();
|
||||
expect(list.getSnapshot()).toMatchObject({ loading: false, error: '联系人列表格式无效' });
|
||||
expect(list.getSnapshot().items[0].label).toBe('retained');
|
||||
await list.refresh(false);
|
||||
expect(list.getSnapshot().error).toBeNull();
|
||||
expect(invoke).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('does not request contacts without an account or group selection', async () => {
|
||||
const invoke = vi.fn();
|
||||
const lists = [
|
||||
createContactList(invoke, 'friends', ''),
|
||||
createContactList(invoke, 'members', 'account'),
|
||||
];
|
||||
|
||||
for (const list of lists) {
|
||||
await list.refresh();
|
||||
expect(list.getSnapshot()).toEqual({ items: [], loading: false, error: null });
|
||||
}
|
||||
|
||||
expect(invoke).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { startPolling } from '../src/lib/polling';
|
||||
|
||||
let page: EventTarget & { hidden: boolean };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
page = Object.assign(new EventTarget(), { hidden: false });
|
||||
vi.stubGlobal('document', page);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('resource polling', () => {
|
||||
it('starts immediately and skips ticks while a request is pending', async () => {
|
||||
const pending = Promise.withResolvers<void>();
|
||||
const refresh = vi.fn().mockReturnValueOnce(pending.promise).mockResolvedValue(undefined);
|
||||
const stop = startPolling(refresh, 1000);
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
pending.resolve();
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(refresh).toHaveBeenCalledTimes(2);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('pauses in the background and refreshes when the page becomes visible', async () => {
|
||||
page.hidden = true;
|
||||
const refresh = vi.fn().mockResolvedValue(undefined);
|
||||
const stop = startPolling(refresh, 1000);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
page.hidden = false;
|
||||
page.dispatchEvent(new Event('visibilitychange'));
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
stop();
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
page.dispatchEvent(new Event('visibilitychange'));
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('keeps initial and visibility refreshes when periodic polling is disabled', async () => {
|
||||
const refresh = vi.fn().mockResolvedValue(undefined);
|
||||
const stop = startPolling(refresh, 0);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
page.dispatchEvent(new Event('visibilitychange'));
|
||||
expect(refresh).toHaveBeenCalledTimes(2);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('keeps the update-check cadence independent of page visibility', async () => {
|
||||
page.hidden = true;
|
||||
const refresh = vi.fn().mockResolvedValue(undefined);
|
||||
const stop = startPolling(refresh, 6000, false);
|
||||
await vi.advanceTimersByTimeAsync(6000);
|
||||
expect(refresh).toHaveBeenCalledTimes(2);
|
||||
page.hidden = false;
|
||||
page.dispatchEvent(new Event('visibilitychange'));
|
||||
expect(refresh).toHaveBeenCalledTimes(2);
|
||||
stop();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user