Files
SnowLuma/packages/bridge/src/hook-session.ts
T
DrSmoothl a1688a33b0 fix(bridge): detect initial connection timeouts
Keep connection timeouts recoverable through retry or unload.

Refs #578
2026-11-02 08:25:15 +08:00

1354 lines
48 KiB
TypeScript

import { errorMessage } from '@snowluma/common/errors';
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';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult, ManualMapHandle } from './injector';
import { detectUinForPid } from './qq-account';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { statusFor } from './hook-status';
import type { HookProcessInfo, HookProcessStatus } from './types';
/** How often to re-check account identity while the connection is not ready.
* Identity alone never proves that requests can be served. */
const LOGIN_RECONCILE_INTERVAL_MS = 3000;
const LOGIN_IDENTITY_OBSERVE_INTERVAL_MS = 30_000;
const LOGIN_HINT_MAX_ATTEMPTS = 3;
const LOGIN_HINT_RETRY_DELAYS_MS = [3000, 9000] as const;
/** Bounds channel discovery and handshakes, not account login. */
const INITIAL_CONNECTION_TIMEOUT_MS = 60_000;
type InitialConnectionWatch = {
startedAt: number;
timer: ReturnType<typeof setTimeout>;
};
/** QQ emits this response periodically while its MSF receive path is healthy.
* Seeing it once arms the watchdog; before that, silence is UNKNOWN rather
* than unhealthy so QQ versions that do not expose this command cannot be
* false-flagged. Any later recv packet proves the same end-to-end path. */
const QQ_RECV_HEARTBEAT_CMD = 'trpc.qq_new_tech.status_svc.StatusService.SsoHeartBeat';
const RECEIVE_STALE_AFTER_MS = 90_000;
const RECEIVE_STALE_CONFIRM_MS = 15_000;
export type HookSessionDeps = {
injector: {
inject: (pid: number) => Promise<HookInjectResult>;
unload: (pid: number, handle: ManualMapHandle) => Promise<void>;
};
makeClient: (pid: number) => QqHookClient;
/** Account QQ's local data reports as signed in on `pid`, or null. Drives the
* login-reconcile safety net; injectable for tests. Defaults to
* `detectUinForPid`. */
detectLoginUin?: (pid: number) => Promise<string | null>;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
* staleness that would otherwise false-flag a successful unload. */
pipeWatcher: {
isPipeLive: (pid: number) => boolean;
tickNow?: () => Promise<void>;
};
/** Sink for parsed packets. Called with the BridgeManager-shaped
* PacketInfo for every packet received while logged in. If omitted,
* packets are dropped (useful in unit tests that don't care). */
onPacket?: PacketSink;
log?: Logger;
};
/**
* HookSession — owns the lifecycle of one QQ.exe process: injection,
* pipe client, login state, and the public status field.
*
* Concurrency: every state-mutating method goes through a per-session
* promise chain so user clicks (load/unload/refresh) and watcher-driven
* events (onPipeUp/onPipeDown) never interleave.
*
* Communication: emits high-level events instead of calling BridgeManager
* directly, so HookManager forwards them and tests can attach spies.
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
* dispose() of a logged-in session
* (process shutdown uses this path)
* 'receive-health-changed' (healthy) — combined receive/request path health changed
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
*/
export class HookSession extends EventEmitter {
readonly pid: number;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly detectLoginUin: (pid: number) => Promise<string | null>;
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
private _status: HookProcessStatus = 'available';
private _error = '';
private runtimeFailure = '';
private _uin = '0';
private _method = '';
private _name = '';
private _path = '';
private injected = false;
private connected = false;
private loggedIn = false;
private injectResult: HookInjectResult | null = null;
private client: QqHookClient | null = null;
private sender: HookPacketClient | null = null;
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
private initialConnectionWatch: InitialConnectionWatch | null = null;
private initialConnectionError = '';
private hasConnected = false;
private cancelConnectAttempt: (() => void) | null = null;
private pipeUpPending = false;
private loginReconcileTimer: ReturnType<typeof setInterval> | null = null;
private detecting = false;
private lastDetectFailure = '';
private acceptedLoginHintUin = '';
private loginHintAttemptUin = '';
private loginHintAttempts = 0;
private nextLoginHintAt = 0;
private nextLoginIdentityObservationAt = 0;
private _receiveHealthy = true;
private _outboundHealthy = true;
private receiveWatchUin = '';
private receiveWatchArmed = false;
private receiveWatchTimer: ReturnType<typeof setTimeout> | null = null;
private lastReceiveAt = 0;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.detectLoginUin = deps.detectLoginUin ?? detectUinForPid;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
}
// ─────────────── readonly public surface ───────────────
get status(): HookProcessStatus {
return this._status;
}
get error(): string {
return this._error;
}
get uin(): string {
return this._uin;
}
get method(): string {
return this._method;
}
get isDisposed(): boolean {
return this.disposed;
}
get receiveHealthy(): boolean {
return this._receiveHealthy && this._outboundHealthy;
}
attachProcessInfo(info: { name?: string; path?: string }): void {
if (info.name) {
this._name = info.name;
}
if (info.path) {
this._path = info.path;
}
}
toInfo(): HookProcessInfo {
return {
pid: this.pid,
name: this._name,
path: this._path,
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
uin: this._uin,
status: this._status,
error: this._error,
method: this._method,
// Filled in by HookManager from the client's local account data.
account: null,
};
}
// ─────────────── user-facing commands ───────────────
load(): Promise<HookProcessInfo> {
return this.traceCommand('load', () => this.loadInternal());
}
unload(): Promise<HookProcessInfo> {
this.cancelConnectAttempt?.();
return this.traceCommand('unload', () => this.unloadInternal());
}
refresh(): Promise<HookProcessInfo> {
return this.traceCommand('refresh', () => this.refreshInternal());
}
// ─────────────── watcher-driven events (called by manager) ───────────────
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
* every watcher tick where the pipe is live. */
onPipeUp(): void {
if (this.disposed || this.pipeUpPending || this.cancelConnectAttempt) {
return;
}
// Watcher ticks must not queue a backlog of stalled handshakes ahead of
// user commands. The next tick can retry once this attempt has settled.
this.pipeUpPending = true;
void this.serialize(async () => {
if (this.disposed) {
return;
}
await this.reconcilePipeUp();
})
.catch((err) =>
this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errorMessage(err)),
)
.finally(() => {
this.pipeUpPending = false;
});
}
onPipeDown(): void {
if (this.disposed) {
return;
}
void this.serialize(async () => {
if (this.disposed) {
return;
}
this.reconcilePipeDown();
}).catch((err) =>
this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
}
/** Called by the manager when the watcher reports the QQ.exe process is
* gone. Cleans up and signals the manager to remove this session. */
notifyProcessGone(): void {
if (this.disposed) {
return;
}
this.cancelConnectAttempt?.();
void this.serialize(async () => {
if (this.disposed) {
return;
}
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.stopInitialConnectionWatch();
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,
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}).catch((err) =>
this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
}
dispose(): void {
if (this.disposed) {
return;
}
const wasLoggedIn = this.loggedIn;
this.disposed = true;
this.stopInitialConnectionWatch();
this.tearDownClient();
// Process shutdown must take the same PID-detach path as a live drop.
// tearDownClient strips the pipe client first, so this emit is the only
// disconnected edge HookManager will see.
if (wasLoggedIn) {
this.emit('disconnected', true);
}
this.removeAllListeners();
}
// ─────────────── 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`,
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
private serialize<T>(op: () => Promise<T>): Promise<T> {
const result = this.opChain.then(op);
this.opChain = result.then(
() => undefined,
() => undefined,
);
return result;
}
// ─────────────── internal transitions ───────────────
private async loadInternal(): Promise<HookProcessInfo> {
if (this.disposed) {
return this.toInfo();
}
this._error = '';
this.setStatus('loading', '');
try {
if (!this.injected) {
// Fast path: a previous SnowLuma run may have left the hook DLL
// resident in QQ.exe. If the watcher already sees a live pipe,
// skip re-injection and let onPipeUp drive the reconnect.
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,
);
}
}
if (this.disposed) {
return this.toInfo();
}
// A retry reuses the loaded component and its unload handle. Only an
// expired deadline is restarted; repeated clicks cannot postpone it.
this.initialConnectionError = '';
this.startInitialConnectionWatch();
this.applyStatus();
} catch (error) {
this._error = errorMessage(error);
this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
// The module can already be listening even when this call returns
// failure: another load left it resident, or it came up after the
// call returned. A live pipe still has the account state, so connect
// instead of staying on the failed load.
await this.pipeWatcher.tickNow?.();
if (!this.disposed && this.pipeWatcher.isPipeLive(this.pid)) {
this.log.info('PID=%d load failed but pipe is up; connecting', this.pid);
await this.reconcilePipeUp();
}
}
return this.toInfo();
}
private async unloadInternal(): Promise<HookProcessInfo> {
this._error = '';
this.stopInitialConnectionWatch();
this.initialConnectionError = '';
this.hasConnected = false;
try {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (wasLoggedIn) {
this.emit('disconnected', true);
}
const handle = this.injectResult?.handle;
if (this.injected && handle) {
await this.injector.unload(this.pid, handle);
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
}
this.injected = false;
this.injectResult = null;
this._method = '';
this._uin = '0';
// Verify the unload took: if the pipe is still up the DLL is still
// resident. The cached snapshot is up to 1500ms stale and we just
// changed the world, so force a fresh poll first — otherwise even
// a successful unload reads as "pipe still live" until the next
// background tick runs and we'd report a spurious failure.
await this.pipeWatcher.tickNow?.();
if (this.pipeWatcher.isPipeLive(this.pid)) {
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
this.setStatus('connecting', this._error);
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
} else {
this.setStatus('available', '');
}
} catch (error) {
this._error = errorMessage(error);
this.setStatus('error', this._error);
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async refreshInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
// Same pipe-up / pipe-down reconcilers the watcher drives, chosen by
// a fresh poll. This collapses what used to be a hand-copied pair of
// onPipeUp/onPipeDown bodies — and fixes the drift where the down
// branch reported 'disconnected' even for a never-logged-in session.
if (this.pipeWatcher.isPipeLive(this.pid)) {
await this.reconcilePipeUp();
} else {
this.reconcilePipeDown();
}
} catch (error) {
this._error = errorMessage(error);
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
// ─────────────── settled-status reconcilers ───────────────
/** Push the settled status derived from the live flags. `wasLoggedIn`
* defaults to the current `loggedIn`; callers that just tore the client
* down pass the value captured *before* teardown (teardown clears it). */
private applyStatus(wasLoggedIn: boolean = this.loggedIn, error = ''): void {
if (this.runtimeFailure) {
this.setStatus('error', this.runtimeFailure);
return;
}
if (this.initialConnectionError) {
this.setStatus('error', this.initialConnectionError);
return;
}
this.setStatus(
statusFor({
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
wasLoggedIn,
}),
error,
);
}
/** Pipe is up: adopt a DLL that survived a SnowLuma restart, drop a
* stale client, then (re)connect if needed or just settle the status.
* Shared by onPipeUp and refresh's pipe-up branch. */
private async reconcilePipeUp(): Promise<void> {
if (!this.injected) {
this.injected = true;
if (!this._method) {
this._method = 'reconnect';
}
}
this.startInitialConnectionWatch();
if (this.client?.isClosed) {
this.tearDownClient();
}
if (!this.connected) {
await this.attemptConnect();
} else {
this.applyStatus();
}
}
/** Pipe is down (or the client closed): tear down, settle the status,
* and emit the disconnect notification iff we owed BridgeManager one
* (i.e. we had reached login). Shared by onPipeDown, refresh's pipe-down
* branch, and the client 'close' handler. */
private reconcilePipeDown(): void {
if (!this.connected) {
// Nothing live to tear down. A session that never connected can't owe
// a disconnect, and we must NOT clobber a diagnostic the failed
// connect/load already set — settle the status keeping `_error`, or
// (when not even injected) leave the status untouched entirely.
if (this.injected) {
this.applyStatus(this.loggedIn, this._error);
}
return;
}
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(true);
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,
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) {
return;
}
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.runtimeFailure = '';
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client, (healthy) =>
this.setOutboundHealthy(healthy),
);
this.bound = false;
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
const watch = this.initialConnectionWatch;
const timeoutMs = watch
? Math.max(1, INITIAL_CONNECTION_TIMEOUT_MS - (Date.now() - watch.startedAt))
: INITIAL_CONNECTION_TIMEOUT_MS;
try {
await this.connectWithTimeout(client, timeoutMs);
if (this.disposed || this.client !== client) {
return;
}
if (this.runtimeFailure) {
throw new Error(this.runtimeFailure);
}
this.connected = true;
this.hasConnected = true;
this.stopInitialConnectionWatch();
this.initialConnectionError = '';
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. Keep re-detecting 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) {
if (this.disposed || this.client !== client) {
return;
}
this._error = errorMessage(error);
const wasLoggedIn = this.loggedIn;
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient(true);
if (watch && Date.now() - watch.startedAt >= INITIAL_CONNECTION_TIMEOUT_MS) {
this.expireInitialConnection(watch, 'handshake');
}
this.applyStatus(wasLoggedIn, this._error);
// Login can arrive on one channel while the other is still
// handshaking. Revoke that binding if the full connection fails.
if (wasLoggedIn) {
this.emit('disconnected', true);
}
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 startInitialConnectionWatch(): void {
if (
this.disposed ||
this.hasConnected ||
this.initialConnectionWatch ||
this.initialConnectionError
) {
return;
}
const watch: InitialConnectionWatch = {
startedAt: Date.now(),
timer: setTimeout(() => {
void this.serialize(async () => this.expireInitialConnection(watch)).catch(
(error) =>
this.log.error(
'initial connection timeout transition failed: PID=%d err=%s',
this.pid,
errorMessage(error),
),
);
}, INITIAL_CONNECTION_TIMEOUT_MS),
};
watch.timer.unref();
this.initialConnectionWatch = watch;
this.log.debug(
'initial connection started: PID=%d timeoutMs=%d',
this.pid,
INITIAL_CONNECTION_TIMEOUT_MS,
);
}
private stopInitialConnectionWatch(): void {
if (this.initialConnectionWatch) {
clearTimeout(this.initialConnectionWatch.timer);
this.initialConnectionWatch = null;
}
}
private expireInitialConnection(
watch: InitialConnectionWatch,
phase: 'waiting_channel' | 'handshake' = 'waiting_channel',
): void {
if (this.disposed || this.connected || this.initialConnectionWatch !== watch) {
return;
}
const previousError = this._error;
this.stopInitialConnectionWatch();
this.initialConnectionError =
'首次连接超时(60 秒):组件已加载,但通信通道尚未就绪,可重试连接或卸载组件';
this.log.error(
'initial connection timed out: PID=%d phase=%s timeoutMs=%d elapsedMs=%d previousError=%j',
this.pid,
phase,
INITIAL_CONNECTION_TIMEOUT_MS,
Date.now() - watch.startedAt,
previousError,
);
this.applyStatus();
}
private async connectWithTimeout(client: QqHookClient, timeoutMs: number): Promise<void> {
let cancel!: () => void;
let timer!: ReturnType<typeof setTimeout>;
const deadline = new Promise<never>((_, reject) => {
cancel = () => reject(new Error('Connection attempt cancelled'));
timer = setTimeout(
() => reject(new Error(`Connection handshake timed out after ${timeoutMs} ms`)),
timeoutMs,
);
timer.unref();
});
this.cancelConnectAttempt = cancel;
try {
// A stalled handshake must release the serialized operation queue so
// timeout handling and unload can run. Late completion has no effects.
await Promise.race([client.connectAll({ recv: true }), deadline]);
} finally {
clearTimeout(timer);
if (this.cancelConnectAttempt === cancel) {
this.cancelConnectAttempt = null;
}
}
}
private bindClient(client: QqHookClient): void {
client.on('runtimeError', (error) => {
if (this.client !== client || this.disposed) {
return;
}
const wasLoggedIn = this.loggedIn;
this.runtimeFailure = errorMessage(error);
this.stopInitialConnectionWatch();
this.loggedIn = false;
this.stopLoginReconcile();
this.resetReceiveWatch();
this.applyStatus(wasLoggedIn);
this.log.error('QQ runtime unavailable: PID=%d err=%s', this.pid, this.runtimeFailure);
if (wasLoggedIn) {
this.emit('disconnected', true);
}
});
client.on('packet', (packet) => this.handlePacket(packet));
client.on('loginState', (state) => this.handleLoginState(state));
client.on('error', (error) => {
const msg = errorMessage(error);
this._error = this.runtimeFailure || this.initialConnectionError || msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
client.on('close', () => {
if (this.disposed) {
return;
}
// Only the currently-registered client should drive a reconcile;
// listeners may fire for an already-replaced client.
if (this.client !== client) {
return;
}
void this.serialize(async () => {
if (this.disposed) {
return;
}
if (this.client !== client) {
return;
}
this.reconcilePipeDown();
}).catch((err) =>
this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errorMessage(err)),
);
});
}
private tearDownClient(preserveRuntimeFailure = false): void {
this.cancelConnectAttempt?.();
this.stopLoginReconcile();
this.resetReceiveWatch();
const client = this.client;
if (client) {
client.removeAllListeners();
try {
client.close();
} catch {
/* ignore */
}
}
this.client = null;
if (!preserveRuntimeFailure) {
this.runtimeFailure = '';
}
this.sender = null;
this.bound = false;
this.connected = false;
this.loggedIn = false;
this._outboundHealthy = true;
this.resetLoginHint();
}
private handleLoginState(state: QqHookLoginState): void {
if (this.runtimeFailure) {
return;
}
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
// Login readiness has now been confirmed, so identity probing is done.
if (this.loggedIn) {
this.stopLoginReconcile();
// A PID can switch accounts without an intermediate logout edge. Never
// carry the previous account's heartbeat deadline into the new epoch.
if (this.receiveWatchUin !== this._uin) {
this.resetReceiveWatch(this._uin);
this._outboundHealthy = true;
}
} else {
this.resetReceiveWatch();
this._outboundHealthy = true;
}
// Only the connected/logged-in states are ours to set here; when fully
// down we leave the status the teardown path already settled.
// Load-bearing invariant: `loggedIn ⇒ connected` (login can only be
// observed on a live client, and teardown clears `loggedIn` before
// `connected`), so statusFor lands 'online' here rather than the
// disconnected/connecting branch.
if (this.connected || this.loggedIn) {
this.applyStatus(wasLoggedIn, this.loggedIn ? '' : this._error);
}
if (!this.loggedIn || !this.sender) {
return;
}
if (wasLoggedIn && previousUin === this._uin) {
return;
}
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,
errorMessage(error),
renderParamsVerbose(this.toInfo()),
Date.now() - startedAt,
]);
throw error;
}
});
}
// ─────────────── login reconcile (Docker auto-login safety net) ───────────
// QQ can restore an account on its own before the runtime is ready, and its
// local account data names that account. Forward the identity for
// reconciliation, but never synthesize online state from the detection.
private startLoginReconcile(): void {
if (this.loginReconcileTimer || this.disposed || this.runtimeFailure) {
return;
}
this.log.info('awaiting login: PID=%d', this.pid);
void this.detectLoginOnce(); // immediate — catch already-logged-in fast
this.loginReconcileTimer = setInterval(
() => void this.detectLoginOnce(),
LOGIN_RECONCILE_INTERVAL_MS,
);
this.loginReconcileTimer.unref();
}
private stopLoginReconcile(): void {
if (this.loginReconcileTimer) {
clearInterval(this.loginReconcileTimer);
this.loginReconcileTimer = null;
}
}
private async detectLoginOnce(): Promise<void> {
// Detecting the account reads the filesystem; skip overlapping ticks so a
// slow read never stacks on top of the interval.
if (this.detecting) {
return;
}
const client = this.client;
if (this.disposed || !client || !this.connected || this.loggedIn || this.runtimeFailure) {
this.stopLoginReconcile();
return;
}
if (Date.now() < this.nextLoginIdentityObservationAt) {
return;
}
this.detecting = true;
try {
let uin: string | null;
try {
uin = await this.detectLoginUin(this.pid);
} catch (error) {
const message = errorMessage(error);
if (this.lastDetectFailure !== message) {
this.lastDetectFailure = message;
this.log.warn(
'login identity detection failed: PID=%d err=%s',
this.pid,
message,
);
}
return; // best-effort; the interval retries
}
// A reconnect owns a new client; an older read cannot supply its identity.
if (
this.client !== client ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
this.lastDetectFailure = '';
if (uin !== null && isRealUin(uin)) {
if (this.acceptedLoginHintUin === uin) {
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
return;
}
if (this.loginHintAttemptUin !== uin) {
this.loginHintAttemptUin = uin;
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
}
if (
this.loginHintAttempts >= LOGIN_HINT_MAX_ATTEMPTS ||
Date.now() < this.nextLoginHintAt
) {
return;
}
const attempt = ++this.loginHintAttempts;
this.log.info(
'login identity discovered: PID=%d UIN=%s; awaiting readiness',
this.pid,
uin,
);
try {
await client.reconcileLoginIdentity(uin);
if (
this.client !== client ||
this.disposed ||
!this.connected ||
this.loggedIn ||
this.runtimeFailure
) {
return;
}
this.acceptedLoginHintUin = uin;
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} catch (error) {
if (this.client !== client || this.disposed || this.runtimeFailure) {
return;
}
if (attempt >= LOGIN_HINT_MAX_ATTEMPTS) {
this.log.warn(
'login identity reconciliation failed: PID=%d UIN=%s attempts=%d err=%s',
this.pid,
uin,
attempt,
errorMessage(error),
);
this.nextLoginIdentityObservationAt =
Date.now() + LOGIN_IDENTITY_OBSERVE_INTERVAL_MS;
} else {
this.nextLoginHintAt =
Date.now() + LOGIN_HINT_RETRY_DELAYS_MS[attempt - 1]!;
this.log.trace(
'login identity hint failed: PID=%d UIN=%s attempt=%d err=%s',
this.pid,
uin,
attempt,
errorMessage(error),
);
}
}
}
} finally {
this.detecting = false;
}
}
private resetLoginHint(): void {
this.acceptedLoginHintUin = '';
this.loginHintAttemptUin = '';
this.loginHintAttempts = 0;
this.nextLoginHintAt = 0;
this.nextLoginIdentityObservationAt = 0;
this.lastDetectFailure = '';
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) {
return;
}
if (
packet.source === 'client-message' &&
(!isRealUin(packet.uin) || packet.uin !== this._uin)
) {
this.log.warn(
'Client message receipt belongs to an inactive account: PID=%d',
this.pid,
);
return;
}
const uin = packet.uin || this._uin;
// Routing requires a real UIN, but even a frame carrying UIN=0 proves the
// receive hook is alive. Attribute that evidence to the current epoch
// without forwarding the malformed packet into BridgeManager.
const receiveUin = isRealUin(uin) ? uin : this.receiveWatchUin || this._uin;
if (isRealUin(receiveUin)) {
this.noteReceiveActivity(packet.cmd, receiveUin);
}
if (!isRealUin(uin)) {
return;
}
if (!this.onPacket) {
return;
}
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
// renaming was that module's entire purpose, so it lives at the source
// now (no need for a single-listener event-emitter in between).
this.onPacket({
pid: this.pid,
uin,
serviceCmd: packet.cmd,
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
...(packet.source ? { source: packet.source } : {}),
body: Buffer.from(packet.body),
});
}
private setStatus(status: HookProcessStatus, error: string): void {
if (this._status === status && this._error === error) {
return;
}
this._status = status;
this._error = error;
this.emit('status-changed', status, error);
}
private noteReceiveActivity(cmd: string, uin: string): void {
// BridgeManager treats packet.uin as authoritative and may move this PID
// before the next loginState edge. Keep the watchdog on that same epoch.
if (this.receiveWatchUin !== uin) {
this.resetReceiveWatch(uin);
}
if (!this.receiveWatchArmed) {
if (cmd !== QQ_RECV_HEARTBEAT_CMD) {
return;
}
this.receiveWatchArmed = true;
this.log.debug(
'receive health armed by QQ heartbeat: PID=%d UIN=%s',
this.pid,
this.receiveWatchUin,
);
}
const now = Date.now();
const silentForMs = this.lastReceiveAt > 0 ? now - this.lastReceiveAt : 0;
this.lastReceiveAt = now;
this.scheduleReceiveStaleCheck();
if (!this._receiveHealthy) {
this.setReceiveHealthy(true);
this.log.info(
'receive path recovered: PID=%d UIN=%s silentFor=%dms',
this.pid,
this.receiveWatchUin,
silentForMs,
);
}
}
private scheduleReceiveStaleCheck(): void {
if (this.receiveWatchTimer) {
clearTimeout(this.receiveWatchTimer);
}
this.receiveWatchTimer = setTimeout(() => {
this.receiveWatchTimer = null;
if (!this.shouldWatchReceive()) {
return;
}
// A delayed event loop (notably system sleep/resume) lands here long
// after the nominal 90s deadline. Do not flip health immediately: give
// the real QQ heartbeat one short confirmation window to arrive.
this.receiveWatchTimer = setTimeout(() => {
this.receiveWatchTimer = null;
if (!this.shouldWatchReceive()) {
return;
}
const silentForMs = Date.now() - this.lastReceiveAt;
if (silentForMs < RECEIVE_STALE_AFTER_MS + RECEIVE_STALE_CONFIRM_MS) {
this.scheduleReceiveStaleCheck();
return;
}
this.setReceiveHealthy(false);
this.log.warn(
'receive path stale: PID=%d UIN=%s lastRecvAt=%s silentFor=%dms; reporting good=false',
this.pid,
this.receiveWatchUin,
new Date(this.lastReceiveAt).toISOString(),
silentForMs,
);
}, RECEIVE_STALE_CONFIRM_MS);
this.receiveWatchTimer.unref();
}, RECEIVE_STALE_AFTER_MS);
this.receiveWatchTimer.unref();
}
private shouldWatchReceive(): boolean {
return !this.disposed && this.connected && this.loggedIn && this.receiveWatchArmed;
}
private setReceiveHealthy(healthy: boolean): void {
if (this._receiveHealthy === healthy) {
return;
}
const previous = this.receiveHealthy;
this._receiveHealthy = healthy;
if (previous !== this.receiveHealthy) {
this.emit('receive-health-changed', this.receiveHealthy);
}
}
private setOutboundHealthy(healthy: boolean): void {
if (this._outboundHealthy === healthy) {
return;
}
const previous = this.receiveHealthy;
this._outboundHealthy = healthy;
if (previous !== this.receiveHealthy) {
this.emit('receive-health-changed', this.receiveHealthy);
}
if (healthy) {
this.log.info('request path recovered: PID=%d UIN=%s', this.pid, this._uin);
} else {
this.log.warn(
'request path unavailable: PID=%d UIN=%s; reporting good=false',
this.pid,
this._uin,
);
}
}
private resetReceiveWatch(uin = ''): void {
if (this.receiveWatchTimer) {
clearTimeout(this.receiveWatchTimer);
this.receiveWatchTimer = null;
}
this.receiveWatchUin = uin;
this.receiveWatchArmed = false;
this.lastReceiveAt = 0;
this._receiveHealthy = true;
}
}