fix: serialize process polling and keep database shutdown terminal

This commit is contained in:
手瓜一十雪 committed 2026-10-18 13:40:00 +08:00
1 parent 95a2d0d257
commit 652b9c4eda
4 files changed
+382 -193

No files matched your search

+116 -159
View File
@@ -1,56 +1,36 @@
import { errorMessage } from '@snowluma/common/errors';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { EventEmitter } from 'events';
import { EventEmitter } from 'node:events';
import { setImmediate as nextTurn } from 'node:timers/promises';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** 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<HookProcessBaseInfo[] | null>;
/** Native: PIDs that currently have a live SnowLuma named pipe. The current
* process snapshot lets Linux inspect each target user's runtime directory. */
/** Failed enumeration returns null and preserves the last known snapshot. */
listProcesses: () => Promise<HookProcessBaseInfo[] | null>;
/** Linux uses this snapshot to locate each target user's runtime directory. */
listLivePipes: (processes: readonly HookProcessBaseInfo[]) => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
};
/**
* PipeWatcher — the only module that polls the OS for QQ.exe processes
* and live SnowLuma named pipes. Subscribers consume diffs as events.
*
* Lifecycle: start() runs one tick synchronously, then schedules a poll
* every `intervalMs`. tickNow() drains a single tick on demand. wake()
* pulls the next scheduled tick forward to the next event-loop turn.
*
* Emitted events:
* 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared
* 'process-gone' (pid: number) — a QQ.exe disappeared
* 'pipe-up' (pid: number) — named pipe came up
* 'pipe-down' (pid: number) — named pipe dropped
* 'tick' () — fired after every poll
*
* Within a single tick the order is: process-discovered, pipe-up,
* pipe-down, process-gone, tick. That ordering lets HookManager create
* a session before it gets a pipe event and run disconnect logic before
* dispose logic when QQ.exe is killed with a live pipe.
*/
type PipeEvent =
| ['process-discovered', HookProcessBaseInfo]
| ['pipe-up' | 'pipe-down' | 'process-gone', number];
/** Publishes process and pipe snapshots, then emits their ordered differences. */
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private tickTask: Promise<void> | null = null;
private pendingTick = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
@@ -62,51 +42,63 @@ export class PipeWatcher extends EventEmitter {
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
/** Read the initial snapshot and start polling. Repeated calls share startup. */
start(): Promise<void> {
if (this.startPromise) {
return this.startPromise;
}
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
return (this.startPromise ??= this.tickNow().finally(() => {
this.scheduleNext(this.intervalMs);
}));
}
/** Pull the next scheduled tick forward to the next event-loop turn. */
/** Coalesce wake requests into one scan after the current read. */
wake(): void {
if (this.stopped) {
return;
}
this.scheduleNext(0);
if (this.tickTask) {
this.pendingTick = true;
} else {
this.scheduleNext(0);
}
}
/** Force a single tick now. Resolves after diff events have been emitted. */
/** Wait for a fresh snapshot, including a scan queued behind an active read. */
tickNow(): Promise<void> {
return this.tickOnce();
if (this.stopped) {
return Promise.resolve();
}
if (this.tickTask) {
this.pendingTick = true;
return this.tickTask;
}
this.tickTask = (async () => {
do {
this.pendingTick = false;
await this.readSnapshot();
if (this.pendingTick && !this.stopped) {
await nextTurn();
}
} while (this.pendingTick && !this.stopped);
})().finally(() => {
this.tickTask = null;
});
return this.tickTask;
}
stop(): void {
this.stopped = true;
this.pendingTick = false;
if (this.timer) {
clearTimeout(this.timer);
@@ -126,135 +118,100 @@ export class PipeWatcher extends EventEmitter {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(
() => {
this.timer = null;
void this.tickAndReschedule();
},
Math.max(0, delayMs),
);
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, delayMs);
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
await this.tickNow();
} catch (error) {
this.log.warn('poll failed: %s', errorMessage(error));
} finally {
this.scheduleNext(this.intervalMs);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
private async readSnapshot(): Promise<void> {
let processes: HookProcessBaseInfo[] | null;
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errorMessage(error));
processes = null;
}
if (this.stopped) {
return;
}
this.ticking = true;
if (processes === null) {
// Missing data must not disconnect healthy sessions. Reconnect retries
// still run against the last known snapshot (issue #158).
this.emit('tick');
return;
}
let livePipes: Set<number>;
try {
let processes: HookProcessBaseInfo[] | null;
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errorMessage(error));
livePipes = this.livePipes;
}
try {
processes = await this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errorMessage(error));
processes = null;
if (this.stopped) {
return;
}
const knownPids = new Set(processes.map(({ pid }) => pid));
const currentPipes = new Set([...livePipes].filter((pid) => knownPids.has(pid)));
const events: PipeEvent[] = [];
for (const process of processes) {
if (!this.knownPids.has(process.pid)) {
events.push(['process-discovered', process]);
}
}
// 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');
for (const pid of currentPipes) {
if (!this.livePipes.has(pid)) {
events.push(['pipe-up', pid]);
}
}
// Disconnect pipes before disposing their departed processes.
for (const pid of this.livePipes) {
if (!currentPipes.has(pid)) {
events.push(['pipe-down', pid]);
}
}
for (const pid of this.knownPids) {
if (!knownPids.has(pid)) {
events.push(['process-gone', pid]);
}
}
this.knownPids = knownPids;
this.livePipes = currentPipes;
for (const [event, payload] of events) {
if (this.stopped) {
return;
}
let livePipes: Set<number> | null;
this.emit(event, payload);
}
try {
livePipes = await this.listLivePipes(processes);
} catch (error) {
this.log.warn('listLivePipes failed: %s', errorMessage(error));
livePipes = null;
}
const newKnownPids = new Set<number>();
for (const proc of processes) {
newKnownPids.add(proc.pid);
}
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
if (livePipes === null) {
// Keep the last known pipe state for processes that still exist, while
// allowing confirmed process exits to complete their normal teardown.
for (const pid of this.livePipes) {
if (newKnownPids.has(pid)) {
newLivePipes.add(pid);
}
}
} else {
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) {
continue;
}
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
if (!this.stopped) {
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => {
void this.tickOnce();
});
}
}
}
}
+168 -6
View File
@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { createLogger } from '@snowluma/common/logger';
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookProcessBaseInfo } from '../src/injector';
@@ -6,7 +7,7 @@ function setupWatcher(initial: { processes: HookProcessBaseInfo[]; live: Set<num
let processes = initial.processes;
let live = initial.live;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listProcesses: async () => processes,
// Defensively copy so the watcher can't mutate the test's reference.
listLivePipes: async () => new Set(live),
intervalMs: 60_000, // disable the internal timer; tests drive ticks manually
@@ -36,6 +37,167 @@ function captureEvents(watcher: PipeWatcher): EventRow[] {
}
describe('PipeWatcher', () => {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it('waits for a fresh scan when another tick is already reading processes', async () => {
let release!: (processes: HookProcessBaseInfo[]) => void;
const pending = new Promise<HookProcessBaseInfo[]>((resolve) => {
release = resolve;
});
const latest = [{ pid: 1234, name: 'QQ.exe', path: '' }];
const listProcesses = vi.fn().mockReturnValueOnce(pending).mockResolvedValue(latest);
const watcher = new PipeWatcher({
listProcesses,
listLivePipes: async () => new Set([1234]),
});
const first = watcher.tickNow();
let completed = false;
const second = watcher.tickNow().then(() => {
completed = true;
});
await Promise.resolve();
expect(completed).toBe(false);
release([]);
await Promise.all([first, second]);
expect(listProcesses).toHaveBeenCalledTimes(2);
expect(watcher.isPipeLive(1234)).toBe(true);
watcher.dispose();
});
it.each(['processes', 'pipes'] as const)(
'discards a pending %s scan after stop',
async (stage) => {
let release!: () => void;
let entered!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const started = new Promise<void>((resolve) => {
entered = resolve;
});
const processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
const listProcesses = vi.fn(async () => {
if (stage === 'processes') {
entered();
await gate;
}
return processes;
});
const listLivePipes = vi.fn(async () => {
if (stage === 'pipes') {
entered();
await gate;
}
return new Set([1234]);
});
const watcher = new PipeWatcher({ listProcesses, listLivePipes });
const events = captureEvents(watcher);
const tick = vi.fn();
watcher.on('tick', tick);
const reading = watcher.start();
await started;
const queued = watcher.tickNow();
watcher.stop();
release();
await Promise.all([reading, queued]);
await watcher.tickNow();
watcher.wake();
expect(events).toEqual([]);
expect(tick).not.toHaveBeenCalled();
expect(watcher.isProcessAlive(1234)).toBe(false);
expect(listProcesses).toHaveBeenCalledOnce();
expect(listLivePipes).toHaveBeenCalledTimes(stage === 'pipes' ? 1 : 0);
watcher.dispose();
},
);
it('keeps a wake requested by a tick listener ahead of the regular interval', async () => {
vi.useFakeTimers();
const listProcesses = vi.fn(async () => []);
const watcher = new PipeWatcher({
listProcesses,
listLivePipes: async () => new Set(),
intervalMs: 60_000,
});
watcher.once('tick', () => watcher.wake());
await watcher.start();
await vi.advanceTimersByTimeAsync(1);
expect(listProcesses).toHaveBeenCalledTimes(2);
watcher.dispose();
});
it('reports a scheduled tick failure and continues polling', async () => {
vi.useFakeTimers();
const listProcesses = vi.fn(async () => []);
const log = createLogger('PipeWatcherTest');
const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});
const watcher = new PipeWatcher({
listProcesses,
listLivePipes: async () => new Set(),
intervalMs: 250,
log,
});
try {
await watcher.start();
watcher.once('tick', () => {
throw new Error('subscriber failed');
});
await vi.advanceTimersByTimeAsync(250);
expect(warn).toHaveBeenCalledWith('poll failed: %s', 'subscriber failed');
await vi.advanceTimersByTimeAsync(250);
expect(listProcesses).toHaveBeenCalledTimes(3);
} finally {
watcher.dispose();
}
});
it('publishes the complete snapshot before notifying subscribers', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
const snapshots: boolean[][] = [];
const observe = () =>
snapshots.push([ctx.watcher.isProcessAlive(1234), ctx.watcher.isPipeLive(1234)]);
ctx.watcher.on('process-discovered', observe);
ctx.watcher.on('pipe-up', observe);
ctx.watcher.on('pipe-down', observe);
ctx.watcher.on('process-gone', observe);
await ctx.watcher.tickNow();
ctx.setProcesses([]);
ctx.setLive(new Set());
await ctx.watcher.tickNow();
expect(snapshots).toEqual([
[true, true],
[true, true],
[false, false],
[false, false],
]);
ctx.watcher.dispose();
});
it('stops emitting the current diff when a subscriber stops the watcher', async () => {
const ctx = setupWatcher({
processes: [{ pid: 1234, name: 'QQ.exe', path: '' }],
live: new Set([1234]),
});
ctx.watcher.on('process-discovered', () => ctx.watcher.stop());
const up = vi.fn();
const tick = vi.fn();
ctx.watcher.on('pipe-up', up);
ctx.watcher.on('tick', tick);
await ctx.watcher.tickNow();
expect(up).not.toHaveBeenCalled();
expect(tick).not.toHaveBeenCalled();
ctx.watcher.dispose();
});
it('passes the current process snapshot to pipe discovery', async () => {
const processes = [
{ pid: 1234, name: 'qq', path: '/opt/QQ/qq' },
@@ -43,7 +205,7 @@ describe('PipeWatcher', () => {
];
let observed: readonly HookProcessBaseInfo[] | undefined;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listProcesses: async () => processes,
listLivePipes: async (current) => {
observed = current;
return new Set();
@@ -208,7 +370,7 @@ describe('PipeWatcher', () => {
let live = new Set<number>();
let shouldThrow = true;
const watcher = new PipeWatcher({
listProcesses: () => {
listProcesses: async () => {
if (shouldThrow) {
throw new Error('boom');
}
@@ -239,7 +401,7 @@ describe('PipeWatcher', () => {
let processes = [{ pid: 1234, name: 'QQ.exe', path: '' }];
let failPipeDiscovery = false;
const watcher = new PipeWatcher({
listProcesses: () => processes,
listProcesses: async () => processes,
listLivePipes: async () => {
if (failPipeDiscovery) {
throw new Error('permission denied');
@@ -277,7 +439,7 @@ describe('PipeWatcher', () => {
let result: HookProcessBaseInfo[] | null = [{ pid: 1234, name: 'qq', path: '' }];
let live = new Set<number>([1234]);
const watcher = new PipeWatcher({
listProcesses: () => result,
listProcesses: async () => result,
listLivePipes: async () => new Set(live),
intervalMs: 60_000,
});
+32 -26
View File
@@ -13,12 +13,11 @@ const context = new AsyncLocalStorage<{ database: SqliteDatabase; active: boolea
*/
export class SqliteDatabase {
readonly initialization: Promise<void>;
private database!: Database;
private opened = false;
private database: Database | null = null;
private tail: Promise<unknown>;
private readonly statements = new Map<string, Statement>();
private pending = 0;
private closing: Promise<void> | null = null;
private shutdown: { task: Promise<void> | null } | null = null;
constructor(filename: string, options: { readOnly?: boolean; busyTimeout?: number } = {}) {
this.initialization = (async () => {
@@ -26,21 +25,21 @@ export class SqliteDatabase {
await mkdir(path.dirname(filename), { recursive: true });
}
this.database = await openDatabase(filename, options.readOnly ?? false);
this.opened = true;
const database = await openDatabase(filename, options.readOnly ?? false);
this.database = database;
try {
await this.database.exec(`PRAGMA busy_timeout = ${options.busyTimeout ?? 1000}`);
await this.database.exec('PRAGMA foreign_keys = ON');
await database.exec(`PRAGMA busy_timeout = ${options.busyTimeout ?? 1000}`);
await database.exec('PRAGMA foreign_keys = ON');
if (!options.readOnly) {
await this.database.exec('PRAGMA journal_mode = WAL');
await this.database.exec('PRAGMA synchronous = NORMAL');
await database.exec('PRAGMA journal_mode = WAL');
await database.exec('PRAGMA synchronous = NORMAL');
}
} catch (error) {
try {
await this.database.close();
this.opened = false;
await database.close();
this.database = null;
} catch (closeError) {
throw new AggregateError(
[error, closeError],
@@ -62,7 +61,7 @@ export class SqliteDatabase {
return Promise.resolve().then(operation);
}
if (this.closing) {
if (this.shutdown) {
return Promise.reject(new Error('SQLite database is closing'));
}
@@ -97,7 +96,7 @@ export class SqliteDatabase {
}
exec(sql: string): Promise<void> {
return this.serial(() => this.database.exec(sql));
return this.serial(() => this.database!.exec(sql));
}
/** Preparation and statement execution both happen in the driver's native workers. */
@@ -106,7 +105,7 @@ export class SqliteDatabase {
let statement = this.statements.get(sql);
if (!statement) {
statement = await this.database.prepare(sql);
statement = await this.database!.prepare(sql);
this.statements.set(sql, statement);
}
@@ -121,17 +120,24 @@ export class SqliteDatabase {
}
close(): Promise<void> {
if (this.closing) {
return this.closing;
const current = context.getStore();
if (current?.database === this && current.active) {
return Promise.reject(new Error('Cannot close SQLite from a serialized operation'));
}
this.closing = (async () => {
await this.tail;
// The initialization promise reports startup failures. Cleanup must still
// release a partially initialized connection without repeating that error.
await this.initialization.catch(() => undefined);
// Shutdown remains terminal for callers even if native cleanup needs a retry.
const shutdown = (this.shutdown ??= { task: null });
if (!this.opened) {
if (shutdown.task) {
return shutdown.task;
}
shutdown.task = (async () => {
// The queue includes initialization and every accepted operation.
await this.tail;
if (!this.database) {
return;
}
@@ -145,7 +151,7 @@ export class SqliteDatabase {
try {
await this.database.close();
this.opened = false;
this.database = null;
} catch (error) {
errors.push(error);
}
@@ -154,10 +160,10 @@ export class SqliteDatabase {
throw new AggregateError(errors, 'SQLite close failed');
}
})();
void this.closing.catch(() => {
this.closing = null;
void shutdown.task.catch(() => {
shutdown.task = null;
});
return this.closing;
return shutdown.task;
}
}
+66 -2
View File
@@ -1,9 +1,10 @@
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { afterEach, expect, it } from 'vitest';
import { setImmediate as nextTurn, setTimeout as delay } from 'node:timers/promises';
import { afterEach, expect, it, vi } from 'vitest';
import { SqliteDatabase } from '../src/index';
import { Database, Statement } from '../src/driver';
const directories: string[] = [];
afterEach(async () => {
@@ -137,3 +138,66 @@ it('rejects failed opens and safely closes a partially initialized connection',
await expect(db.prepare('SELECT 1').get()).rejects.toMatchObject({ code: 'SQLITE_CANTOPEN' });
await db.close();
});
it('keeps writes rejected after a failed close while allowing cleanup to retry', async () => {
const db = new SqliteDatabase(':memory:');
await db.initialization;
const close = vi
.spyOn(Database.prototype, 'close')
.mockRejectedValueOnce(new Error('close failed'));
try {
await expect(db.close()).rejects.toThrow('SQLite close failed');
await expect(db.exec('CREATE TABLE late_write (value INTEGER)')).rejects.toThrow('closing');
const retry = db.close();
expect(db.close()).toBe(retry);
await retry;
expect(close).toHaveBeenCalledTimes(2);
await expect(db.serial(() => 1)).rejects.toThrow('closing');
} finally {
close.mockRestore();
await db.close();
}
});
it('does not accept work when connection close succeeds but statement cleanup reports an error', async () => {
const db = new SqliteDatabase(':memory:');
await db.prepare('SELECT 1').get();
const original = Statement.prototype.finalize;
const finalize = vi
.spyOn(Statement.prototype, 'finalize')
.mockImplementationOnce(async function (this: Statement) {
await original.call(this);
throw new Error('statement cleanup failed');
});
try {
await expect(db.close()).rejects.toThrow('SQLite close failed');
await expect(db.serial(() => 1)).rejects.toThrow('closing');
await db.close();
} finally {
finalize.mockRestore();
await db.close();
}
});
it('rejects close from inside its own serialized operation instead of waiting on itself', async () => {
const db = new SqliteDatabase(':memory:');
try {
await db.serial(async () => {
await expect(
Promise.race([
db.close(),
nextTurn().then(() => {
throw new Error('close is waiting on its own operation');
}),
]),
).rejects.toThrow('Cannot close SQLite from a serialized operation');
await db.exec('CREATE TABLE records (value INTEGER)');
});
await db.prepare('INSERT INTO records VALUES (?)').run(1);
} finally {
await db.close();
}
});