diff --git a/packages/bridge/src/hook-manager.ts b/packages/bridge/src/hook-manager.ts index 1cb658f9..7c41b83a 100644 --- a/packages/bridge/src/hook-manager.ts +++ b/packages/bridge/src/hook-manager.ts @@ -6,10 +6,12 @@ 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 { QqHookClient } from './qq-hook-client'; import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; import type { HookProcessInfo } from './types'; @@ -81,7 +83,13 @@ export class HookManager { private readonly makeClient: HookSessionDeps['makeClient']; private readonly pipeWatcher: PipeWatcher; private readonly ownsPipeWatcher: boolean; - private readonly listProcessesNative: () => HookProcessBaseInfo[]; + /** 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; + /** 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 autoLoadOnDiscovery: boolean; private readonly onSessionsChangedRaw?: () => void; private readonly log: Logger; @@ -104,15 +112,38 @@ export class HookManager { }, }; this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); - this.listProcessesNative = deps.listProcesses ?? listHookProcesses; 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(); + } + if (deps.pipeWatcher) { this.pipeWatcher = deps.pipeWatcher; this.ownsPipeWatcher = false; } else { this.pipeWatcher = new PipeWatcher({ - listProcesses: this.listProcessesNative, + listProcesses: this.enumerate, listLivePipes: () => QqHookClient.listLivePipes(), intervalMs: deps.watcherIntervalMs, log: this.log, @@ -128,12 +159,13 @@ export class HookManager { async listProcesses(): Promise { await this.startPromise; - let processes: HookProcessBaseInfo[]; - try { - processes = this.listProcessesNative(); - } catch (error) { - this.log.warn('listProcesses failed: %s', errMsg(error)); - processes = []; + const processes = await this.enumerate(); + if (processes === null) { + // Enumeration timed out / failed — report the last-known sessions rather + // than an empty list (which the WebUI would render as "no QQ"). + return [...this.sessions.values()] + .map((s) => s.toInfo()) + .sort((a, b) => a.pid - b.pid); } const result: HookProcessInfo[] = []; for (const proc of processes) { @@ -181,6 +213,7 @@ export class HookManager { session.dispose(); } this.sessions.clear(); + this.enumerator?.dispose(); if (this.ownsPipeWatcher) { this.pipeWatcher.dispose(); } diff --git a/packages/bridge/src/pipe-watcher.ts b/packages/bridge/src/pipe-watcher.ts index c0d7cc82..7b615423 100644 --- a/packages/bridge/src/pipe-watcher.ts +++ b/packages/bridge/src/pipe-watcher.ts @@ -6,8 +6,11 @@ const DEFAULT_INTERVAL_MS = 1500; const MIN_INTERVAL_MS = 250; export type PipeWatcherDeps = { - /** Native: list QQ.exe processes currently running. */ - listProcesses: () => HookProcessBaseInfo[]; + /** Native: list QQ.exe processes currently running. May be async and may + * return `null` (UNKNOWN) when enumeration timed out / failed — in which + * case this tick keeps the prior process+pipe state instead of treating the + * missing data as "everything disappeared" (issue #158). */ + listProcesses: () => HookProcessBaseInfo[] | null | Promise; /** Native: PIDs that currently have a live SnowLuma named pipe. */ listLivePipes: () => Promise>; /** Polling interval in ms. Defaults to 1500, floored to 250. */ @@ -138,12 +141,22 @@ export class PipeWatcher extends EventEmitter { } this.ticking = true; try { - let processes: HookProcessBaseInfo[]; + let processes: HookProcessBaseInfo[] | null; try { - processes = this.listProcesses(); + processes = await this.listProcesses(); } catch (error) { this.log.warn('listProcesses failed: %s', errMsg(error)); - processes = []; + processes = null; + } + // UNKNOWN (timeout / failure): keep the prior process + pipe snapshot. + // Treating missing data as "everything disappeared" would fire + // process-gone for every live PID and dispose healthy sessions — the + // freeze-then-teardown footgun behind issue #158. Still emit 'tick' so + // the manager's per-tick reconnect retries keep running off last-known + // live pipes. + if (processes === null) { + this.emit('tick'); + return; } let livePipes: Set; try { diff --git a/packages/bridge/src/process-enumerator.ts b/packages/bridge/src/process-enumerator.ts new file mode 100644 index 00000000..82287745 --- /dev/null +++ b/packages/bridge/src/process-enumerator.ts @@ -0,0 +1,238 @@ +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. */ + enumerate(): Promise; + 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?". */ + 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 { + 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 void }>(); + 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; + } + }; + + return { + async enumerate(): Promise { + if (disposed || isolationBroken) return syncFallback(); + + 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(); + } + const w = worker; + if (!w) return syncFallback(); + + const id = ++seq; + const resultPromise = new Promise((resolve) => { + pending.set(id, { resolve }); + }); + 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) clearTimeout(timer); + + if (outcome === 'timeout') { + pending.delete(id); + log.warn('process enumeration timed out after %dms (worker abandoned) — keeping prior process set', timeoutMs); + teardownWorker(); + return null; + } + 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); + }, + + 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 */ }); + }, + }; +} + +function errMsg(value: unknown): string { + return value instanceof Error ? value.message : String(value); +} diff --git a/packages/bridge/tests/pipe-watcher.test.ts b/packages/bridge/tests/pipe-watcher.test.ts index 1623c8f8..29abc90e 100644 --- a/packages/bridge/tests/pipe-watcher.test.ts +++ b/packages/bridge/tests/pipe-watcher.test.ts @@ -192,4 +192,40 @@ describe('PipeWatcher', () => { expect(events).toEqual([['discovered', 1234], ['up', 1234]]); watcher.stop(); }); + + it('UNKNOWN (null) enumeration keeps prior state — no false process-gone (issue #158)', async () => { + let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }]; + let live = new Set([1234]); + const watcher = new PipeWatcher({ + listProcesses: () => result, + listLivePipes: async () => new Set(live), + intervalMs: 60_000, + }); + + await watcher.start(); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + const events = captureEvents(watcher); + + // Enumeration goes UNKNOWN (e.g. native /proc walk timed out during a QQ + // hot-update). Prior process + pipe state MUST be preserved — no teardown. + result = null; + await watcher.tickNow(); + expect(events).toEqual([]); + expect(watcher.isProcessAlive(1234)).toBe(true); + expect(watcher.isPipeLive(1234)).toBe(true); + + // Enumeration recovers with the same set → still no churn. + result = [{ pid: 1234, name: 'qq', path: '' }]; + await watcher.tickNow(); + expect(events).toEqual([]); + + // A REAL disappearance (empty list, not null) still fires the teardown. + result = []; + live = new Set(); + await watcher.tickNow(); + expect(events).toEqual([['down', 1234], ['gone', 1234]]); + watcher.stop(); + }); }); diff --git a/packages/bridge/tests/process-enumerator.test.ts b/packages/bridge/tests/process-enumerator.test.ts new file mode 100644 index 00000000..6d45d1de --- /dev/null +++ b/packages/bridge/tests/process-enumerator.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, vi } from 'vitest'; +import { createNativeProcessEnumerator } 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(); + }); + + 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(); + }); + }); + + 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, + }); + + // First call spawns the worker; the fatal message drains it to UNKNOWN. + const first = await en.enumerate(); + expect(first).toBeNull(); + + // 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(); + }); + }); +});