refactor: use native async discovery and simplify shared state

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

No files matched your search

+15 -45
View File
@@ -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 -4
View File
@@ -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,
+30 -37
View File
@@ -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);
}
+14 -44
View File
@@ -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: '' }));
+3 -6
View File
@@ -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);
}
+43 -257
View File
@@ -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);
}