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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user