feat(logging): complete runtime trace diagnostics

Complete byte-level diagnostics for network, upload, runtime lifecycle, authenticated write, and background operation paths.

Preserve streaming behavior, file-storage boundaries, and default log volume while making failures, retries, cancellation, and final outcomes independently diagnosable.

Add focused regression coverage for correlation, partial data, resource context ownership, and terminal-state accuracy.
This commit is contained in:
DrSmoothl committed 2026-07-31 11:21:12 +08:00
1 parent 0ed85e7745
commit a67614fa09
27 files changed
+4029 -352

No files matched your search

+130 -55
View File
@@ -1,4 +1,9 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
createLogger,
runWithTraceRequest,
type Logger,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
import fs from 'fs';
@@ -238,23 +243,38 @@ export class HookManager {
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) return;
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
this.runAutoLoad(session);
}
this.notifySessionsChanged();
runWithTraceRequest(() => {
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
this.log.trace(() => [
'hook_manager_fact event=process_discovered pid=%d info=%s autoLoad=%s',
info.pid,
renderParamsVerbose(info),
this.autoLoadOnDiscovery,
]);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
this.runAutoLoad(session);
}
this.notifySessionsChanged();
});
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
this.autoLoadAttempts.delete(pid);
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
this.notifySessionsChanged();
runWithTraceRequest(() => {
this.autoLoadAttempts.delete(pid);
const session = this.sessions.get(pid);
this.log.trace(
'hook_manager_fact event=process_gone pid=%d tracked=%s',
pid,
session !== undefined,
);
if (session) session.notifyProcessGone();
this.notifySessionsChanged();
});
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
@@ -307,51 +327,106 @@ export class HookManager {
this.autoLoadAttempts.set(session.pid, state);
const attempt = state.attempts;
void session.load().then((info) => {
if (this.autoLoadAttempts.get(session.pid) !== state) return;
state.inFlight = false;
if (info.status !== 'error') {
this.autoLoadAttempts.delete(session.pid);
if (attempt > 1) {
this.log.info(
'auto-load recovered: PID=%d attempt=%d/%d',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
);
}
return;
}
if (!isTransientLibcMappingError(info.error)) {
this.autoLoadAttempts.delete(session.pid);
return;
}
if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) {
this.autoLoadAttempts.delete(session.pid);
this.log.warn(
'auto-load retry exhausted: PID=%d attempts=%d err=%s',
session.pid,
attempt,
info.error,
);
return;
}
this.log.warn(
'auto-load retry pending: PID=%d attempt=%d/%d err=%s',
void runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(
'hook_autoload_start pid=%d attempt=%d maxAttempts=%d',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
info.error,
);
}).catch((err) => {
if (this.autoLoadAttempts.get(session.pid) === state) {
this.autoLoadAttempts.delete(session.pid);
try {
const info = await session.load();
if (this.autoLoadAttempts.get(session.pid) !== state) {
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=dropped reason=superseded elapsedMs=%d',
session.pid,
attempt,
Date.now() - startedAt,
);
return;
}
state.inFlight = false;
if (info.status !== 'error') {
this.autoLoadAttempts.delete(session.pid);
const reason = attempt > 1 ? 'recovered' : 'loaded';
this.log.trace(() => [
'hook_autoload_terminal pid=%d attempt=%d outcome=completed reason=%s state=%s elapsedMs=%d',
session.pid,
attempt,
reason,
renderParamsVerbose(info),
Date.now() - startedAt,
]);
if (attempt > 1) {
this.log.info(
'auto-load recovered: PID=%d attempt=%d/%d',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
);
}
return;
}
if (!isTransientLibcMappingError(info.error)) {
this.autoLoadAttempts.delete(session.pid);
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=permanent_failure error=%j elapsedMs=%d',
session.pid,
attempt,
info.error,
Date.now() - startedAt,
);
return;
}
if (attempt >= AUTO_LOAD_MAX_ATTEMPTS) {
this.autoLoadAttempts.delete(session.pid);
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_exhausted error=%j elapsedMs=%d',
session.pid,
attempt,
info.error,
Date.now() - startedAt,
);
this.log.warn(
'auto-load retry exhausted: PID=%d attempts=%d err=%s',
session.pid,
attempt,
info.error,
);
return;
}
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=retry_pending error=%j elapsedMs=%d',
session.pid,
attempt,
info.error,
Date.now() - startedAt,
);
this.log.warn(
'auto-load retry pending: PID=%d attempt=%d/%d err=%s',
session.pid,
attempt,
AUTO_LOAD_MAX_ATTEMPTS,
info.error,
);
} catch (err) {
if (this.autoLoadAttempts.get(session.pid) === state) {
this.autoLoadAttempts.delete(session.pid);
}
this.log.trace(
'hook_autoload_terminal pid=%d attempt=%d outcome=failed reason=unexpected_failure error=%j elapsedMs=%d',
session.pid,
attempt,
errMsg(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, errMsg(err));
});
}
+228 -55
View File
@@ -1,4 +1,10 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
createLogger,
runWithoutRequestContext,
runWithTraceRequest,
type Logger,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin';
import { EventEmitter } from 'events';
@@ -142,15 +148,15 @@ export class HookSession extends EventEmitter {
// ─────────────── user-facing commands ───────────────
load(): Promise<HookProcessInfo> {
return this.serialize(() => this.loadInternal());
return this.traceCommand('load', () => this.loadInternal());
}
unload(): Promise<HookProcessInfo> {
return this.serialize(() => this.unloadInternal());
return this.traceCommand('unload', () => this.unloadInternal());
}
refresh(): Promise<HookProcessInfo> {
return this.serialize(() => this.refreshInternal());
return this.traceCommand('refresh', () => this.refreshInternal());
}
// ─────────────── watcher-driven events (called by manager) ───────────────
@@ -180,16 +186,42 @@ export class HookSession extends EventEmitter {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.removeAllListeners();
runWithTraceRequest(() => {
const startedAt = Date.now();
const wasLoggedIn = this.loggedIn;
this.log.trace(() => [
'hook_session_process_start pid=%d event=process_gone state=%s',
this.pid,
renderParamsVerbose(this.toInfo()),
]);
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
try {
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.log.trace(() => [
'hook_session_process_terminal pid=%d outcome=completed reason=process_gone wasLoggedIn=%s state=%s elapsedMs=%d',
this.pid,
wasLoggedIn,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
this.removeAllListeners();
} catch (error) {
this.log.trace(() => [
'hook_session_process_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
}
@@ -202,6 +234,58 @@ export class HookSession extends EventEmitter {
// ─────────────── per-session serialization ───────────────
private traceCommand(
operation: 'load' | 'unload' | 'refresh',
command: () => Promise<HookProcessInfo>,
): Promise<HookProcessInfo> {
return runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(() => [
'hook_session_start pid=%d operation=%s state=%s',
this.pid,
operation,
renderParamsVerbose(this.toInfo()),
]);
try {
const info = await this.serialize(command);
const outcome = info.status === 'error'
|| (operation === 'unload' && info.status !== 'available')
? 'failed'
: 'completed';
let reason: string;
if (operation === 'unload' && info.status === 'connecting') {
reason = 'unload_verification_failed';
} else if (outcome === 'failed') {
reason = `${operation}_failed`;
} else {
reason = `${operation}_settled`;
}
this.log.trace(() => [
'hook_session_terminal pid=%d operation=%s outcome=%s reason=%s%s state=%s elapsedMs=%d',
this.pid,
operation,
outcome,
reason,
info.error ? ` error=${JSON.stringify(info.error)}` : '',
renderParamsVerbose(info),
Date.now() - startedAt,
]);
return info;
} catch (error) {
this.log.trace(() => [
'hook_session_terminal pid=%d operation=%s outcome=failed reason=%s error=%j state=%s elapsedMs=%d',
this.pid,
operation,
`${operation}_threw`,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
@@ -230,11 +314,25 @@ export class HookSession extends EventEmitter {
if (this.pipeWatcher.isPipeLive(this.pid)) {
this.injected = true;
this._method = this._method || 'reconnect';
this.log.trace(
'hook_session_branch pid=%d operation=load branch=existing_pipe method=%j',
this.pid,
this._method,
);
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
} else {
this.log.trace(
'hook_session_branch pid=%d operation=load branch=inject_begin',
this.pid,
);
this.injectResult = await this.injector.inject(this.pid);
this.injected = true;
this._method = this.injectResult.method;
this.log.trace(
'hook_session_branch pid=%d operation=load branch=inject_completed method=%j',
this.pid,
this._method,
);
}
}
this.applyStatus();
@@ -348,52 +446,99 @@ export class HookSession extends EventEmitter {
if (this.injected) this.applyStatus(this.loggedIn, this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.applyStatus(wasLoggedIn);
if (wasLoggedIn) this.emit('disconnected', true);
runWithTraceRequest(() => {
const startedAt = Date.now();
const wasLoggedIn = this.loggedIn;
this.log.trace(() => [
'hook_session_disconnect_start pid=%d reason=pipe_down state=%s',
this.pid,
renderParamsVerbose(this.toInfo()),
]);
this.tearDownClient();
this.applyStatus(wasLoggedIn);
try {
if (wasLoggedIn) this.emit('disconnected', true);
this.log.trace(() => [
'hook_session_disconnect_terminal pid=%d outcome=completed reason=pipe_down wasLoggedIn=%s state=%s elapsedMs=%d',
this.pid,
wasLoggedIn,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
} catch (error) {
this.log.trace(() => [
'hook_session_disconnect_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) return;
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.bound = false;
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
const loginState = client.getLoginState();
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
this.startLoginReconcile();
return runWithTraceRequest(async () => {
const startedAt = Date.now();
this.log.trace(() => [
'hook_session_connect_start pid=%d state=%s',
this.pid,
renderParamsVerbose(this.toInfo()),
]);
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.bound = false;
}
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(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();
this.applyStatus(false, this._error);
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
const loginState = client.getLoginState();
// handleLoginState owns the connected+loggedIn → 'online' (+ login
// emit) transition; defer to it so the status is set once. Otherwise
// we're connected-but-not-logged-in → 'loaded'.
if (loginState.loggedIn) {
this.handleLoginState(loginState);
} else {
this.applyStatus();
// The native hook only PUSHES a loginState frame on the login edge;
// if QQ logged in before/around connect (Docker auto-login) that edge
// is missed and we'd wait forever. Actively re-probe until logged in.
runWithoutRequestContext(() => this.startLoginReconcile());
}
this.log.info('pipe connected: PID=%d', this.pid);
this.log.trace(() => [
'hook_session_connect_terminal pid=%d outcome=completed reason=connect_settled state=%s elapsedMs=%d',
this.pid,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
} catch (error) {
this._error = errMsg(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();
this.applyStatus(false, this._error);
this.log.trace(() => [
'hook_session_connect_terminal pid=%d outcome=failed reason=connect_failed error=%j state=%s elapsedMs=%d',
this.pid,
this._error,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
}
});
}
private bindClient(client: QqHookClient): void {
@@ -461,8 +606,36 @@ export class HookSession extends EventEmitter {
if (!this.loggedIn || !this.sender) return;
if (wasLoggedIn && previousUin === this._uin) return;
this.emit('login', this._uin, this.sender);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
runWithTraceRequest(() => {
const startedAt = Date.now();
this.log.trace(
'hook_session_login_start pid=%d previousUin=%j uin=%j',
this.pid,
previousUin,
this._uin,
);
try {
this.emit('login', this._uin, this.sender!);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
this.log.trace(() => [
'hook_session_login_terminal pid=%d outcome=completed reason=login_detected previousUin=%j uin=%j state=%s elapsedMs=%d',
this.pid,
previousUin,
this._uin,
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
} catch (error) {
this.log.trace(() => [
'hook_session_login_terminal pid=%d outcome=failed reason=listener_failed error=%j state=%s elapsedMs=%d',
this.pid,
errMsg(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
+90 -22
View File
@@ -1,5 +1,11 @@
import { EventEmitter } from 'events';
import { createLogger, renderTraceBytes } from '@snowluma/common/logger';
import {
createLogger,
renderTraceBytes,
runWithoutRequestContext,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
import { readdirSync, promises as fs } from 'fs';
import net from 'net';
import os from 'os';
@@ -12,6 +18,7 @@ export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
const packetLog = createLogger('QQHook.Packet');
const runtimeLog = createLogger('QQHook.Runtime');
export enum PipeOp {
hello = 1,
@@ -479,14 +486,7 @@ export class QqHookClient extends EventEmitter {
if (this.controlConnectPromise) {
return this.controlConnectPromise;
}
this.controlConnectPromise = (async () => {
this.controlSocket = await this.connectSocket(
QqHookClient.controlPipeName(this.pid),
'control',
frame => this.handleControlFrame(frame));
this.controlHello = await this.waitForHello(false);
return this.controlHello;
})();
this.controlConnectPromise = this.connectPipe('control');
try {
return await this.controlConnectPromise;
} finally {
@@ -507,14 +507,7 @@ export class QqHookClient extends EventEmitter {
if (this.recvConnectPromise) {
return this.recvConnectPromise;
}
this.recvConnectPromise = (async () => {
this.recvSocket = await this.connectSocket(
QqHookClient.recvPipeName(this.pid),
'recv',
frame => this.handleRecvFrame(frame));
this.recvHello = await this.waitForHello(true);
return this.recvHello;
})();
this.recvConnectPromise = this.connectPipe('recv');
try {
return await this.recvConnectPromise;
} finally {
@@ -770,6 +763,60 @@ export class QqHookClient extends EventEmitter {
return writePromise;
}
private async connectPipe(kind: 'control' | 'recv'): Promise<QqHookHello> {
return runWithTraceRequest(async () => {
const startedAt = Date.now();
const pipeName = kind === 'control'
? QqHookClient.controlPipeName(this.pid)
: QqHookClient.recvPipeName(this.pid);
let phase: 'connect' | 'hello' = 'connect';
runtimeLog.trace(
'hook_pipe_start pid=%d kind=%s pipeName=%j',
this.pid,
kind,
pipeName,
);
try {
const socket = await runWithoutRequestContext(() => this.connectSocket(
pipeName,
kind,
kind === 'control'
? frame => this.handleControlFrame(frame)
: frame => this.handleRecvFrame(frame),
));
if (kind === 'control') this.controlSocket = socket;
else this.recvSocket = socket;
runtimeLog.trace(
'hook_pipe_branch pid=%d kind=%s branch=socket_connected',
this.pid,
kind,
);
phase = 'hello';
const hello = await this.waitForHello(kind === 'recv');
if (kind === 'control') this.controlHello = hello;
else this.recvHello = hello;
runtimeLog.trace(() => [
'hook_pipe_terminal pid=%d kind=%s outcome=completed reason=hello_received hello=%s elapsedMs=%d',
this.pid,
kind,
renderParamsVerbose(hello),
Date.now() - startedAt,
]);
return hello;
} catch (error) {
runtimeLog.trace(() => [
'hook_pipe_terminal pid=%d kind=%s outcome=failed reason=%s error=%j elapsedMs=%d',
this.pid,
kind,
phase === 'connect' ? 'connect_failed' : 'hello_failed',
error instanceof Error ? error.message : String(error),
Date.now() - startedAt,
]);
throw error;
}
});
}
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(pipeName);
@@ -790,8 +837,10 @@ export class QqHookClient extends EventEmitter {
this.emit('error', error);
});
socket.on('close', () => {
this.handleSocketClose(kind);
this.emit('close', kind);
runWithTraceRequest(() => {
this.handleSocketClose(kind);
this.emit('close', kind);
});
});
resolve(socket);
});
@@ -821,6 +870,13 @@ export class QqHookClient extends EventEmitter {
}
private handleSocketClose(kind: 'control' | 'recv'): void {
runtimeLog.trace(
'hook_runtime_fact pid=%d event=pipe_closed kind=%s loggedIn=%s uin=%j',
this.pid,
kind,
this.loginState.loggedIn,
this.loginState.uin,
);
if (kind === 'control') {
this.controlSocket = null;
this.controlHello = null;
@@ -844,14 +900,26 @@ export class QqHookClient extends EventEmitter {
private applyLoginState(next: QqHookLoginState): void {
const previous = this.loginState;
this.loginState = next;
this.emit('loginState', next);
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
if (previous.loggedIn === next.loggedIn && previous.uin === next.uin) {
this.emit('loginState', next);
return;
}
runWithTraceRequest(() => {
runtimeLog.trace(
'hook_runtime_fact pid=%d event=login_state_changed previousLoggedIn=%s previousUin=%j loggedIn=%s uin=%j',
this.pid,
previous.loggedIn,
previous.uin,
next.loggedIn,
next.uin,
);
this.emit('loginState', next);
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.resolve({ ...next });
}
}
});
}
private handleControlFrame(frame: PipeFrame): void {
+189 -3
View File
@@ -5,21 +5,39 @@ import os from 'os';
import path from 'path';
import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
const flush = () => new Promise<void>(r => setImmediate(r));
const previousLogLevel = getLogLevel();
function managerTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'Hook',
);
}
function makeManager(opts: {
autoLoadOnDiscovery?: boolean;
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
const inject = vi.fn(opts.inject ?? (() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})));
const unload = vi.fn();
const pipeWatcher = new PipeWatcher({
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
@@ -48,6 +66,7 @@ function makeManager(opts: {
injector: { inject, unload },
makeClient,
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
});
return {
@@ -58,6 +77,173 @@ function makeManager(opts: {
};
}
afterEach(() => {
setLogLevel(previousLogLevel);
});
describe('HookManager runtime TRACE', () => {
it('records discovery and process-gone facts while unchanged ticks stay silent', async () => {
const entries: LogEntry[] = [];
const sessionsChanged = vi.fn();
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: false,
processes: [],
onSessionsChanged: sessionsChanged,
});
try {
await ctx.pipeWatcher.start();
const baseline = managerTrace(entries).length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
expect(managerTrace(entries)).toHaveLength(baseline);
ctx.setProcesses([4242]);
await ctx.pipeWatcher.tickNow();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
const facts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_manager_fact '),
);
expect(facts.map((entry) => entry.message)).toEqual([
expect.stringContaining('hook_manager_fact event=process_discovered pid=4242'),
'hook_manager_fact event=process_gone pid=4242 tracked=true',
]);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('records bounded transient retries and recovery as separate attempts', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject
.mockImplementationOnce(() => {
throw new Error(
'target process does not map /lib/x86_64-linux-gnu/libc.so.6 while resolving mmap',
);
})
.mockImplementationOnce(() => ({
method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
}));
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=1 outcome=failed reason=retry_pending error=.*elapsedMs=\d+$/),
'hook_autoload_start pid=4242 attempt=2 maxAttempts=3',
expect.stringMatching(/^hook_autoload_terminal pid=4242 attempt=2 outcome=completed reason=recovered state=.*elapsedMs=\d+$/),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
expect(attempts[2]!.req).toBe(attempts[3]!.req);
expect(attempts[0]!.req).not.toBe(attempts[2]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it('ends an in-flight auto-load as dropped when a manual load supersedes it', async () => {
const entries: LogEntry[] = [];
let resolveInjection!: (result: HookInjectResult) => void;
const injection = new Promise<HookInjectResult>((resolve) => {
resolveInjection = resolve;
});
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({
autoLoadOnDiscovery: true,
processes: [4242],
inject: () => injection,
});
try {
await ctx.pipeWatcher.start();
await flush();
const manualLoad = ctx.manager.loadProcess(4242);
resolveInjection({ method: 'loadModuleManual', handle: DUMMY_HANDLE });
await manualLoad;
await flush();
const attempts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_'),
);
expect(attempts.map((entry) => entry.message)).toEqual([
'hook_autoload_start pid=4242 attempt=1 maxAttempts=3',
expect.stringMatching(
/^hook_autoload_terminal pid=4242 attempt=1 outcome=dropped reason=superseded elapsedMs=\d+$/,
),
]);
expect(attempts[0]!.req).toBe(attempts[1]!.req);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
it.each([
{
name: 'permanent failure',
error: 'ptrace denied',
ticks: 1,
attempts: 1,
reason: 'permanent_failure',
},
{
name: 'retry exhaustion',
error: 'target process does not map /lib/libc.so.6 while resolving mmap',
ticks: 4,
attempts: 3,
reason: 'retry_exhausted',
},
])('records $name terminal', async ({ error, ticks, attempts, reason }) => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
ctx.inject.mockImplementation(() => { throw new Error(error); });
try {
await ctx.pipeWatcher.start();
await flush();
await flush();
for (let tick = 0; tick < ticks; tick += 1) {
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
}
const starts = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_start '),
);
const terminals = managerTrace(entries).filter(
(entry) => entry.message.startsWith('hook_autoload_terminal '),
);
expect(starts).toHaveLength(attempts);
expect(terminals).toHaveLength(attempts);
expect(terminals.at(-1)!.message).toContain(`reason=${reason}`);
} finally {
unsubscribe();
ctx.manager.dispose();
}
});
});
describe('HookManager.autoLoadOnDiscovery', () => {
it('does NOT inject on process-discovered when flag is off', async () => {
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
+198 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from 'vitest';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { EventEmitter } from 'events';
import { HookSession } from '../src/hook-session';
import type { ManualMapHandle } from '../src/injector';
@@ -6,6 +6,24 @@ import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketSink } from '@snowluma/common/protocol-types';
import {
getLogLevel,
setLogLevel,
subscribeLogs,
type LogEntry,
} from '@snowluma/common/logger';
const previousLogLevel = getLogLevel();
function sessionTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'HookSession',
);
}
afterEach(() => {
setLogLevel(previousLogLevel);
});
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
@@ -95,6 +113,185 @@ function makeSession(opts: {
const flush = () => new Promise<void>(r => setImmediate(r));
describe('HookSession — runtime TRACE', () => {
it('records injection and existing-pipe load branches with unique terminals', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injected = makeSession({ pid: 7101, pipeLive: false });
const reconnect = makeSession({ pid: 7102, pipeLive: true });
await injected.session.load();
await reconnect.session.load();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringContaining('hook_session_start pid=7101 operation=load'),
'hook_session_branch pid=7101 operation=load branch=inject_begin',
'hook_session_branch pid=7101 operation=load branch=inject_completed method="loadModuleManual"',
expect.stringMatching(/^hook_session_terminal pid=7101 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
expect.stringContaining('hook_session_start pid=7102 operation=load'),
'hook_session_branch pid=7102 operation=load branch=existing_pipe method="reconnect"',
expect.stringMatching(/^hook_session_terminal pid=7102 operation=load outcome=completed reason=load_settled state=.*elapsedMs=\d+$/),
]));
for (const pid of [7101, 7102]) {
expect(messages.filter(
(message) => message.startsWith(`hook_session_terminal pid=${pid} operation=load `),
)).toHaveLength(1);
}
} finally {
unsubscribe();
}
});
it('records load and connection failures with truthful settled state', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const injector = {
inject: vi.fn(() => { throw new Error('fixture inject failure'); }),
unload: vi.fn(),
};
const failedLoad = new HookSession(7103, {
injector,
makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => false },
});
await failedLoad.load();
const failedConnect = makeSession({
pid: 7104,
pipeLive: true,
clientFailsConnect: true,
});
await failedConnect.session.load();
failedConnect.session.onPipeUp();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages).toEqual(expect.arrayContaining([
expect.stringMatching(/^hook_session_terminal pid=7103 operation=load outcome=failed reason=load_failed error="fixture inject failure" state=.*elapsedMs=\d+$/),
expect.stringContaining('hook_session_connect_start pid=7104'),
expect.stringMatching(/^hook_session_connect_terminal pid=7104 outcome=failed reason=connect_failed error="connect failed" state=.*elapsedMs=\d+$/),
]));
expect(messages.filter(
(message) => message.startsWith('hook_session_connect_terminal pid=7104 '),
)).toHaveLength(1);
} finally {
unsubscribe();
}
});
it('records login, disconnect, and process-gone only when state changes', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeSession({ pid: 7105, pipeLive: true });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.currentClient().fireLogin('10001');
ctx.session.onPipeDown();
await flush();
ctx.session.onPipeDown();
await flush();
ctx.session.notifyProcessGone();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages.filter(
(message) => message.startsWith('hook_session_login_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages.filter(
(message) => message.startsWith('hook_session_disconnect_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages.filter(
(message) => message.startsWith('hook_session_process_terminal pid=7105 '),
)).toHaveLength(1);
expect(messages).toEqual(expect.arrayContaining([
expect.stringMatching(/^hook_session_login_terminal pid=7105 outcome=completed reason=login_detected previousUin="0" uin="10001" state=.*elapsedMs=\d+$/),
expect.stringMatching(/^hook_session_disconnect_terminal pid=7105 outcome=completed reason=pipe_down wasLoggedIn=true state=.*elapsedMs=\d+$/),
expect.stringMatching(/^hook_session_process_terminal pid=7105 outcome=completed reason=process_gone wasLoggedIn=false state=.*elapsedMs=\d+$/),
]));
} finally {
unsubscribe();
ctx.session.dispose();
}
});
it('records failed terminals when lifecycle listeners throw', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const login = makeSession({ pid: 7107, pipeLive: true });
const disconnect = makeSession({ pid: 7108, pipeLive: true });
const processGone = makeSession({ pid: 7109, pipeLive: true });
try {
await login.session.load();
login.session.onPipeUp();
await flush();
login.session.on('login', () => { throw new Error('login listener boom'); });
expect(() => login.currentClient().fireLogin('10001')).toThrow('login listener boom');
await disconnect.session.load();
disconnect.session.onPipeUp();
await flush();
disconnect.currentClient().fireLogin('10002');
disconnect.session.on('disconnected', () => { throw new Error('disconnect listener boom'); });
disconnect.session.onPipeDown();
await flush();
processGone.session.on('disposed', () => { throw new Error('dispose listener boom'); });
processGone.session.notifyProcessGone();
await flush();
const messages = sessionTrace(entries).map((entry) => entry.message);
expect(messages.filter((message) =>
message.startsWith('hook_session_login_terminal pid=7107 '))).toEqual([
expect.stringMatching(/^hook_session_login_terminal pid=7107 outcome=failed reason=listener_failed error="login listener boom" state=.*elapsedMs=\d+$/),
]);
expect(messages.filter((message) =>
message.startsWith('hook_session_disconnect_terminal pid=7108 '))).toEqual([
expect.stringMatching(/^hook_session_disconnect_terminal pid=7108 outcome=failed reason=listener_failed error="disconnect listener boom" state=.*elapsedMs=\d+$/),
]);
expect(messages.filter((message) =>
message.startsWith('hook_session_process_terminal pid=7109 '))).toEqual([
expect.stringMatching(/^hook_session_process_terminal pid=7109 outcome=failed reason=listener_failed error="dispose listener boom" state=.*elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
login.session.dispose();
disconnect.session.dispose();
processGone.session.dispose();
}
});
it('records unload verification failure as a failed terminal', async () => {
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const ctx = makeSession({ pid: 7106, pipeLive: false });
try {
await ctx.session.load();
ctx.setPipeLive(true);
await ctx.session.unload();
const terminals = sessionTrace(entries).filter(
(entry) => entry.message.startsWith('hook_session_terminal pid=7106 operation=unload '),
);
expect(terminals).toHaveLength(1);
expect(terminals[0]!.message).toMatch(
/^hook_session_terminal pid=7106 operation=unload outcome=failed reason=unload_verification_failed error=.*state=.*elapsedMs=\d+$/,
);
} finally {
unsubscribe();
}
});
});
describe('HookSession — load', () => {
it('with no live pipe: injects, status → connecting, method from inject result', async () => {
const { session, injector } = makeSession({ pipeLive: false });
@@ -4,6 +4,7 @@ import os from 'os';
import path from 'path';
import { Duplex } from 'stream';
import {
currentRequestId,
getLogLevel,
runWithRequestId,
setLogLevel,
@@ -106,6 +107,12 @@ function traceMessages(entries: LogEntry[]): string[] {
.map((entry) => entry.message);
}
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
return entries.filter(
(entry) => entry.level === 'trace' && entry.scope === 'QQHook.Runtime',
);
}
afterEach(async () => {
setLogLevel(previousLogLevel);
vi.restoreAllMocks();
@@ -140,6 +147,136 @@ describe('listLiveLinuxPipePids', () => {
});
});
describe('QqHookClient — runtime TRACE', () => {
it('records control and receive pipe hello lifecycles under the parent request', async () => {
const pid = 778820;
const entries: LogEntry[] = [];
let connectionIndex = 0;
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const kind = connectionIndex === 0 ? 'control' : 'recv';
connectionIndex += 1;
const socket = new Duplex({
read() { /* peer data is injected with emit('data') */ },
}) as net.Socket;
queueMicrotask(() => {
socket.emit('connect');
queueMicrotask(() => socket.emit('data', pipeFrame({
op: PipeOp.hello,
value0: BigInt(pid),
message: `${kind}-fixture`,
})));
});
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await runWithRequestId(4201, () => client.connectAll());
const trace = runtimeTrace(entries);
expect(trace).toHaveLength(6);
expect(trace.every((entry) => entry.req === 4201)).toBe(true);
expect(trace.map((entry) => entry.message)).toEqual([
expect.stringMatching(/^hook_pipe_start pid=778820 kind=control pipeName=.*$/),
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=control branch=socket_connected$/),
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=control outcome=completed reason=hello_received hello=\{pipeName:"control-fixture",pid:778820,recvPipe:false\} elapsedMs=\d+$/),
expect.stringMatching(/^hook_pipe_start pid=778820 kind=recv pipeName=.*$/),
expect.stringMatching(/^hook_pipe_branch pid=778820 kind=recv branch=socket_connected$/),
expect.stringMatching(/^hook_pipe_terminal pid=778820 kind=recv outcome=completed reason=hello_received hello=\{pipeName:"recv-fixture",pid:778820,recvPipe:true\} elapsedMs=\d+$/),
]);
} finally {
unsubscribe();
client.close();
createConnection.mockRestore();
}
});
it('records a pre-request connection failure without a pipe request id', async () => {
const pid = 778821;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const createConnection = vi.spyOn(net, 'createConnection').mockImplementation((() => {
const socket = new Duplex({ read() { /* no peer */ } }) as net.Socket;
queueMicrotask(() => socket.emit('error', new Error('fixture connect failure')));
return socket;
}) as typeof net.createConnection);
const client = new QqHookClient(pid);
try {
await expect(client.connect()).rejects.toThrow('fixture connect failure');
const trace = runtimeTrace(entries);
expect(trace).toHaveLength(2);
expect(trace.every((entry) => entry.req !== undefined)).toBe(true);
expect(trace[0]!.req).toBe(trace[1]!.req);
expect(trace.map((entry) => entry.message)).toEqual([
expect.stringMatching(/^hook_pipe_start pid=778821 kind=control pipeName=.*$/),
expect.stringMatching(/^hook_pipe_terminal pid=778821 kind=control outcome=failed reason=connect_failed error="fixture connect failure" elapsedMs=\d+$/),
]);
expect(trace.map((entry) => entry.message).join('\n')).not.toContain('requestId=');
} finally {
unsubscribe();
client.close();
createConnection.mockRestore();
}
});
it('assigns fresh request contexts to material login and close events only', async () => {
const pid = 778822;
const entries: LogEntry[] = [];
setLogLevel('trace');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
const connection = mockControlPipe(pid, () => { /* no packet writes */ });
const client = new QqHookClient(pid);
const eventRequestIds: Array<{ event: 'login' | 'close'; req: number | undefined }> = [];
client.on('loginState', () => {
eventRequestIds.push({ event: 'login', req: currentRequestId() });
});
client.on('close', () => {
eventRequestIds.push({ event: 'close', req: currentRequestId() });
});
try {
await runWithRequestId(4202, () => client.connect());
const controlSocket = connection.mock.results[0]!.value as net.Socket;
controlSocket.emit('data', pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.emit('data', pipeFrame({
op: PipeOp.loginState,
status: 1,
value0: 123456n,
message: '123456',
}));
controlSocket.destroy();
await new Promise<void>((resolve) => setImmediate(resolve));
const facts = runtimeTrace(entries).filter(
(entry) => entry.message.startsWith('hook_runtime_fact pid=778822 '),
);
expect(facts).toHaveLength(2);
expect(facts.every((entry) => entry.req !== undefined)).toBe(true);
expect(facts[0]!.req).not.toBe(facts[1]!.req);
expect(facts.map((entry) => entry.message)).toEqual([
'hook_runtime_fact pid=778822 event=login_state_changed previousLoggedIn=false previousUin="0" loggedIn=true uin="123456"',
'hook_runtime_fact pid=778822 event=pipe_closed kind=control loggedIn=true uin="123456"',
]);
expect(eventRequestIds).toEqual([
{ event: 'login', req: facts[0]!.req },
{ event: 'login', req: undefined },
{ event: 'close', req: facts[1]!.req },
]);
} finally {
unsubscribe();
client.close();
connection.mockRestore();
}
});
});
describe('QqHookClient — packet TRACE', () => {
it('records complete request and reply bodies with the real pipe request id', async () => {
const pid = 778810;