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:
27 files changed
+4029
-352
No files matched your search
@@ -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));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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) ───────────
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user