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 {
|
||||
|
||||
@@ -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] });
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2,7 +2,12 @@ import { format } from 'util';
|
||||
import { getFileTransport } from './log-file-transport';
|
||||
import { redactLogMessage } from './log-summary';
|
||||
import { sanitizeLogLine } from './log-sanitize';
|
||||
import { currentRequestId, nextRequestId, runWithRequestId } from './request-context';
|
||||
import {
|
||||
currentRequestId,
|
||||
nextRequestId,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
} from './request-context';
|
||||
|
||||
type LogLevel = 'trace' | 'debug' | 'info' | 'success' | 'warn' | 'error';
|
||||
type FileLogLevel = Exclude<LogLevel, 'trace'>;
|
||||
@@ -366,4 +371,4 @@ export function logInitialWebuiCredentials(password: string): void {
|
||||
// Request-correlation primitives remain available for callers that already own
|
||||
// an explicit request id. New semantic entrypoints should prefer
|
||||
// runWithTraceRequest() so disabled TRACE does not allocate one.
|
||||
export { nextRequestId, runWithRequestId, currentRequestId };
|
||||
export { nextRequestId, runWithoutRequestContext, runWithRequestId, currentRequestId };
|
||||
@@ -4,7 +4,7 @@ interface RequestStore {
|
||||
id: number;
|
||||
}
|
||||
|
||||
const storage = new AsyncLocalStorage<RequestStore>();
|
||||
const storage = new AsyncLocalStorage<RequestStore | undefined>();
|
||||
let counter = 0;
|
||||
|
||||
/**
|
||||
@@ -29,6 +29,11 @@ export function runWithRequestId<T>(id: number, fn: () => T): T {
|
||||
return storage.run({ id }, fn);
|
||||
}
|
||||
|
||||
/** Run `fn` without inheriting an ambient request id. */
|
||||
export function runWithoutRequestContext<T>(fn: () => T): T {
|
||||
return storage.run(undefined, fn);
|
||||
}
|
||||
|
||||
/** The request id bound to the current async context, or undefined outside one. */
|
||||
export function currentRequestId(): number | undefined {
|
||||
return storage.getStore()?.id;
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
getLogLevel,
|
||||
nextRequestId,
|
||||
renderTraceBytes,
|
||||
runWithoutRequestContext,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
setLogLevel,
|
||||
@@ -88,6 +89,20 @@ describe('TRACE diagnostics contract', () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('detaches long-lived resources from the current request context', async () => {
|
||||
await runWithRequestId(4243, async () => {
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
const detached = await runWithoutRequestContext(async () => {
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
return currentRequestId();
|
||||
});
|
||||
expect(detached).toBeUndefined();
|
||||
expect(currentRequestId()).toBe(4243);
|
||||
});
|
||||
expect(currentRequestId()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reuses an existing request context even while TRACE is disabled', async () => {
|
||||
setLogLevel('info');
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
|
||||
@@ -20,6 +24,7 @@ import {
|
||||
import type { BridgeInterface } from './bridge-interface';
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
@@ -166,10 +171,20 @@ export class Bridge implements BridgeInterface {
|
||||
/** Atomically attach a process and make its sender the active sender.
|
||||
* Set insertion order is the recency order used for fallback. */
|
||||
bindPid(pid: number, client: PacketSender): void {
|
||||
const previousPid = this.packetClientPid_;
|
||||
const previousClient = this.packetClient_;
|
||||
this.attachPid(pid);
|
||||
this.packetClientsByPid_.set(pid, client);
|
||||
this.packetClient_ = client;
|
||||
this.packetClientPid_ = pid;
|
||||
if (previousPid !== pid || previousClient !== client) {
|
||||
runtimeLog.trace(
|
||||
'bridge_sender_fact event=selected uin=%j pid=%d previousPid=%j',
|
||||
this.identity.uin,
|
||||
pid,
|
||||
previousPid,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal BridgeManager lookup used when an incoming packet is the first
|
||||
@@ -263,11 +278,32 @@ export class Bridge implements BridgeInterface {
|
||||
}
|
||||
async sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs = 15000): Promise<SendPacketResult> {
|
||||
if (!this.packetClient_) {
|
||||
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
return runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
runtimeLog.trace(() => [
|
||||
'bridge_send_start serviceCmd=%j uin=%j activePid=%j timeoutMs=%d length=%d body=%s',
|
||||
serviceCmd,
|
||||
this.identity.uin,
|
||||
this.activePid,
|
||||
timeoutMs,
|
||||
body.byteLength,
|
||||
renderTraceBytes(body),
|
||||
]);
|
||||
log.warn('packet %s dropped: no packet sender attached', serviceCmd);
|
||||
runtimeLog.trace(() => [
|
||||
'bridge_send_terminal serviceCmd=%j uin=%j activePid=%j outcome=dropped reason=no_sender length=%d body=%s elapsedMs=%d',
|
||||
serviceCmd,
|
||||
this.identity.uin,
|
||||
this.activePid,
|
||||
body.byteLength,
|
||||
renderTraceBytes(body),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return {
|
||||
success: false, gotResponse: false, errorCode: -1,
|
||||
errorMessage: 'no packet sender attached', responseData: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
const startedAt = Date.now();
|
||||
const result = await this.packetClient_.sendPacket(serviceCmd, Buffer.from(body), timeoutMs);
|
||||
@@ -297,6 +333,12 @@ export class Bridge implements BridgeInterface {
|
||||
|
||||
this.packetClient_ = fallback;
|
||||
this.packetClientPid_ = fallbackPid;
|
||||
runtimeLog.trace(
|
||||
'bridge_sender_fact event=fallback uin=%j detachedPid=%d fallbackPid=%d',
|
||||
this.identity.uin,
|
||||
detachedPid,
|
||||
fallbackPid,
|
||||
);
|
||||
log.debug(
|
||||
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
|
||||
this.identity.uin,
|
||||
|
||||
@@ -18,6 +18,7 @@ interface QQSession {
|
||||
|
||||
const log = createLogger('Bridge');
|
||||
const packetLog = createLogger('Bridge.Packet');
|
||||
const runtimeLog = createLogger('Bridge.Runtime');
|
||||
|
||||
export class BridgeManager {
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
@@ -62,7 +63,42 @@ export class BridgeManager {
|
||||
const uin = this.pidToUin_.get(pid);
|
||||
if (!uin) return;
|
||||
|
||||
this.detachPidFromSession(pid, uin);
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_start pid=%d uin=%j',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
try {
|
||||
const closed = this.detachPidFromSession(pid, uin);
|
||||
const activePid = this.sessions_.get(uin)?.bridge.activePid ?? null;
|
||||
if (closed) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_branch pid=%d uin=%j branch=session_closed',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
}
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=completed reason=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
closed ? 'session_closed' : 'pid_detached',
|
||||
activePid,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
runtimeLog.trace(
|
||||
'bridge_detach_terminal pid=%d uin=%j outcome=failed reason=invariant_violation error=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPidReceiveHealthChanged(pid: number, healthy: boolean): void {
|
||||
@@ -85,12 +121,65 @@ export class BridgeManager {
|
||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||
if (!isRealUin(uin)) return;
|
||||
|
||||
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
const previousUin = this.pidToUin_.get(pid) ?? null;
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_start pid=%d uin=%j source=login previousUin=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousUin,
|
||||
);
|
||||
|
||||
if (created) {
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
try {
|
||||
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||
if (previousUin && previousUin !== uin) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=account_rebind previousUin=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousUin,
|
||||
);
|
||||
const previousSession = this.sessions_.get(previousUin);
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=%s previousUin=%j activePid=%j',
|
||||
pid,
|
||||
uin,
|
||||
previousSession ? 'previous_session_retained' : 'previous_session_closed',
|
||||
previousUin,
|
||||
previousSession?.bridge.activePid ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
if (created) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_branch pid=%d uin=%j branch=session_created',
|
||||
pid,
|
||||
uin,
|
||||
);
|
||||
log.debug('session started: UIN=%s', uin);
|
||||
this.fireSessionStarted(uin, session.bridge);
|
||||
}
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=completed reason=%s created=%s activePid=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
previousUin && previousUin !== uin ? 'rebound' : 'bound',
|
||||
created,
|
||||
session.bridge.activePid,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
runtimeLog.trace(
|
||||
'bridge_binding_terminal pid=%d uin=%j source=login outcome=failed reason=binding_failed error=%j elapsedMs=%d',
|
||||
pid,
|
||||
uin,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onPacket(pkt: PacketInfo): void {
|
||||
@@ -233,7 +322,7 @@ export class BridgeManager {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
private detachPidFromSession(pid: number, uin: string): void {
|
||||
private detachPidFromSession(pid: number, uin: string): boolean {
|
||||
const mappedUin = this.pidToUin_.get(pid);
|
||||
if (mappedUin !== uin) {
|
||||
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
|
||||
@@ -263,13 +352,14 @@ export class BridgeManager {
|
||||
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||
this.pidToUin_.delete(pid);
|
||||
session.bridge.detachPid(pid);
|
||||
if (!session.bridge.empty) return;
|
||||
if (!session.bridge.empty) return false;
|
||||
|
||||
this.sessions_.delete(uin);
|
||||
log.debug('session closed: UIN=%s', uin);
|
||||
// Fire before dispose() so listeners can still read bridge.identity.
|
||||
this.fireSessionClosed(uin, session.bridge);
|
||||
session.bridge.dispose();
|
||||
return true;
|
||||
}
|
||||
|
||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||
|
||||
@@ -11,8 +11,15 @@
|
||||
* something update.
|
||||
*/
|
||||
|
||||
import {
|
||||
createLogger,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import type { StateBus } from './state-bus';
|
||||
|
||||
const log = createLogger('WebUI.Connections');
|
||||
|
||||
export interface ConnectionDiffLoopOptions {
|
||||
bus: StateBus;
|
||||
/** Read the current adapter-status snapshot for every live UIN. */
|
||||
@@ -43,6 +50,7 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
// a shape regression would otherwise wedge the baseline silently — no
|
||||
// publishes, no log, no symptom besides "the dashboard's connections
|
||||
// card stops updating". Surface it ONCE so the failure is visible.
|
||||
let warnedSnapshotThrew = false;
|
||||
let warnedProjectorThrew = false;
|
||||
|
||||
const tick = (): void => {
|
||||
@@ -50,7 +58,19 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
let snap: unknown;
|
||||
try {
|
||||
snap = opts.getSnapshot();
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (!warnedSnapshotThrew) {
|
||||
warnedSnapshotThrew = true;
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace('connection_diff_start phase=snapshot_read');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=snapshot_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
// Snapshot read failed (e.g. mid-shutdown). Skip this tick; the
|
||||
// next one will retry. Don't reset the baseline so we don't
|
||||
// spuriously republish when the snapshot starts working again.
|
||||
@@ -65,10 +85,22 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
// so an operator can find it without re-running the loop locally.
|
||||
if (!warnedProjectorThrew) {
|
||||
warnedProjectorThrew = true;
|
||||
// Static logger import avoided to keep the loop self-contained;
|
||||
// stderr is good enough for a once-per-process latch.
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[connection-diff-loop] pickComparable threw — connections SSE diff will wedge until restart:', err);
|
||||
log.error(
|
||||
'connection snapshot projector failed; updates may be stale: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start phase=project snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=failed reason=projector_failed error=%j elapsedMs=%d',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -84,7 +116,19 @@ export function startConnectionDiffLoop(opts: ConnectionDiffLoopOptions): Connec
|
||||
}
|
||||
if (serialized === lastSerialized) return;
|
||||
lastSerialized = serialized;
|
||||
opts.bus.publish('connections');
|
||||
runWithTraceRequest(() => {
|
||||
const startedAt = Date.now();
|
||||
log.trace(() => [
|
||||
'connection_diff_start snapshot=%s',
|
||||
renderParamsVerbose(snap),
|
||||
]);
|
||||
log.trace('connection_diff_branch branch=publish resource=connections');
|
||||
opts.bus.publish('connections');
|
||||
log.trace(
|
||||
'connection_diff_terminal outcome=completed reason=published elapsedMs=%d',
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const timer = setInterval(tick, intervalMs);
|
||||
|
||||
@@ -19,6 +19,7 @@ import { mkdir, readdir, rm, stat } from 'fs/promises';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { traceWebuiMutationRequestChunk } from './mutation-trace';
|
||||
|
||||
/** Temp dir for browser→server uploads. Siblings the Stream API's temp root but
|
||||
* kept distinct so the two cleanup stories don't entangle. */
|
||||
@@ -38,7 +39,7 @@ export function safeUploadName(raw: string | undefined): string {
|
||||
// `../` / absolute prefix is discarded regardless of host platform.
|
||||
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'));
|
||||
const cleaned = base
|
||||
.replace(/[^\w.\-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/[^\w.-]+/g, '_') // collapse anything exotic to underscore
|
||||
.replace(/^\.+/, '') // no leading dots (no hidden / '..' names)
|
||||
.slice(0, 120);
|
||||
return cleaned || 'file';
|
||||
@@ -88,7 +89,9 @@ export async function streamUploadToDisk(
|
||||
const { done, value } = await Promise.race([errored, reader.read()]);
|
||||
if (done) break;
|
||||
if (!value || value.byteLength === 0) continue;
|
||||
const offset = size;
|
||||
size += value.byteLength;
|
||||
traceWebuiMutationRequestChunk(value, offset);
|
||||
if (size > maxBytes) throw new Error('上传超出大小上限');
|
||||
// Respect the write stream's backpressure (but never hang on an error).
|
||||
if (!out.write(value)) {
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
import {
|
||||
createLogger,
|
||||
currentRequestId,
|
||||
getLogLevel,
|
||||
renderTraceBytes,
|
||||
runWithRequestId,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
|
||||
const log = createLogger('WebUI.Mutation');
|
||||
const READ_ONLY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
const STREAMED_REQUEST_PATHS = new Set(['/api/debug/upload']);
|
||||
const STREAMED_RESPONSE_PATHS = new Set(['/api/debug/invoke-stream']);
|
||||
// This route can disable TRACE while its own operation is in flight; its
|
||||
// existing WebUI info record is the authoritative result.
|
||||
const TRACE_EXCLUDED_PATHS = new Set([
|
||||
'/api/auth/check-strength',
|
||||
'/api/logs/level',
|
||||
]);
|
||||
|
||||
interface CapturedBody {
|
||||
bytes: Uint8Array;
|
||||
text: string;
|
||||
}
|
||||
|
||||
function shouldTraceMutation(request: Request): boolean {
|
||||
if (getLogLevel() !== 'trace') return false;
|
||||
if (READ_ONLY_METHODS.has(request.method.toUpperCase())) return false;
|
||||
return !TRACE_EXCLUDED_PATHS.has(new URL(request.url).pathname);
|
||||
}
|
||||
|
||||
async function captureBody(message: Request | Response): Promise<CapturedBody> {
|
||||
const bytes = new Uint8Array(await message.arrayBuffer());
|
||||
return {
|
||||
bytes,
|
||||
text: new TextDecoder().decode(bytes),
|
||||
};
|
||||
}
|
||||
|
||||
function traceBody(
|
||||
branch: 'request_body' | 'response',
|
||||
body: CapturedBody,
|
||||
response?: Response,
|
||||
): void {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=%s%s length=%d text=%j body=%s',
|
||||
branch,
|
||||
response
|
||||
? ` status=${response.status} statusText=${JSON.stringify(response.statusText)} headers=${renderParamsVerbose([...response.headers.entries()])}`
|
||||
: '',
|
||||
body.bytes.byteLength,
|
||||
body.text,
|
||||
renderTraceBytes(body.bytes),
|
||||
]);
|
||||
}
|
||||
|
||||
function traceStreamChunk(
|
||||
branch: 'request_body_chunk' | 'response_chunk',
|
||||
chunk: Uint8Array,
|
||||
offset: number,
|
||||
): void {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=%s offset=%d length=%d body=%s',
|
||||
branch,
|
||||
offset,
|
||||
chunk.byteLength,
|
||||
renderTraceBytes(chunk),
|
||||
]);
|
||||
}
|
||||
|
||||
export function traceWebuiMutationRequestChunk(chunk: Uint8Array, offset: number): void {
|
||||
traceStreamChunk('request_body_chunk', chunk, offset);
|
||||
}
|
||||
|
||||
function traceStreamedResponse(
|
||||
response: Response,
|
||||
requestBody: Promise<CapturedBody> | null,
|
||||
startedAt: number,
|
||||
): Response {
|
||||
if (!response.body) {
|
||||
void settleMutation(
|
||||
requestBody,
|
||||
Promise.resolve({ bytes: new Uint8Array(), text: '' }),
|
||||
response,
|
||||
startedAt,
|
||||
false,
|
||||
);
|
||||
return response;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const requestId = currentRequestId();
|
||||
const inContext = <T>(fn: () => T): T => requestId === undefined
|
||||
? fn()
|
||||
: runWithRequestId(requestId, fn);
|
||||
let offset = 0;
|
||||
let settled = false;
|
||||
const terminal = (outcome: 'completed' | 'failed' | 'cancelled', reason: string, error?: unknown) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
void inContext(() => traceRequestBody(requestBody)).then(() => {
|
||||
inContext(() => log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d%s elapsedMs=%d',
|
||||
outcome,
|
||||
reason,
|
||||
response.status,
|
||||
error === undefined ? '' : ` error=${JSON.stringify(error instanceof Error ? error.message : String(error))}`,
|
||||
Date.now() - startedAt,
|
||||
));
|
||||
});
|
||||
};
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
try {
|
||||
const result = await reader.read();
|
||||
if (result.done) {
|
||||
terminal(response.ok ? 'completed' : 'failed', response.ok ? 'response_completed' : 'http_status');
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
const chunk = result.value;
|
||||
inContext(() => traceStreamChunk('response_chunk', chunk, offset));
|
||||
offset += chunk.byteLength;
|
||||
controller.enqueue(chunk);
|
||||
} catch (error) {
|
||||
terminal(error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed', error);
|
||||
controller.error(error);
|
||||
}
|
||||
},
|
||||
async cancel(reason) {
|
||||
terminal('cancelled', 'body_cancelled', reason);
|
||||
await reader.cancel(reason);
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
return new Response(body, response);
|
||||
}
|
||||
|
||||
async function traceRequestBody(requestBody: Promise<CapturedBody> | null): Promise<void> {
|
||||
if (!requestBody) return;
|
||||
try {
|
||||
traceBody('request_body', await requestBody);
|
||||
} catch (error) {
|
||||
log.trace(
|
||||
'webui_mutation_branch branch=request_body_failed error=%j',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function settleMutation(
|
||||
requestBody: Promise<CapturedBody> | null,
|
||||
responseBody: Promise<CapturedBody>,
|
||||
response: Response,
|
||||
startedAt: number,
|
||||
requestCancelled: boolean,
|
||||
): Promise<void> {
|
||||
const results = await Promise.allSettled([
|
||||
requestBody ?? Promise.resolve<CapturedBody>({ bytes: new Uint8Array(), text: '' }),
|
||||
responseBody,
|
||||
]);
|
||||
const [requestResult, responseResult] = results;
|
||||
if (requestBody && requestResult.status === 'fulfilled') traceBody('request_body', requestResult.value);
|
||||
if (requestBody && requestResult.status === 'rejected') {
|
||||
log.trace('webui_mutation_branch branch=request_body_failed error=%j',
|
||||
requestResult.reason instanceof Error ? requestResult.reason.message : String(requestResult.reason));
|
||||
}
|
||||
if (responseResult.status === 'fulfilled') traceBody('response', responseResult.value, response);
|
||||
else {
|
||||
log.trace(() => [
|
||||
'webui_mutation_branch branch=response_body_failed status=%d statusText=%j headers=%s error=%j',
|
||||
response.status,
|
||||
response.statusText,
|
||||
renderParamsVerbose([...response.headers.entries()]),
|
||||
responseResult.reason instanceof Error ? responseResult.reason.message : String(responseResult.reason),
|
||||
]);
|
||||
}
|
||||
const error = responseResult.status === 'rejected'
|
||||
? responseResult.reason
|
||||
: requestResult.status === 'rejected'
|
||||
? requestResult.reason
|
||||
: undefined;
|
||||
if (error === undefined) {
|
||||
if (requestCancelled) {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=cancelled reason=request_cancelled status=%d elapsedMs=%d',
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s status=%d elapsedMs=%d',
|
||||
response.ok ? 'completed' : 'failed',
|
||||
response.ok ? 'response_completed' : 'http_status',
|
||||
response.status,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return;
|
||||
}
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'failed',
|
||||
error instanceof Error && error.name === 'AbortError' ? 'body_cancelled' : 'body_read_failed',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
}
|
||||
|
||||
function failureOutcome(error: unknown): {
|
||||
outcome: 'failed' | 'timeout' | 'cancelled';
|
||||
reason: string;
|
||||
} {
|
||||
if (error instanceof Error && error.name === 'TimeoutError') {
|
||||
return { outcome: 'timeout', reason: 'handler_timeout' };
|
||||
}
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
return { outcome: 'cancelled', reason: 'handler_cancelled' };
|
||||
}
|
||||
return { outcome: 'failed', reason: 'handler_threw' };
|
||||
}
|
||||
|
||||
/** Trace one authenticated WebUI write without consuming its live streams. */
|
||||
export function traceAuthenticatedWebuiMutation(
|
||||
request: Request,
|
||||
next: () => Promise<Response>,
|
||||
): Promise<Response> {
|
||||
if (!shouldTraceMutation(request)) return next();
|
||||
|
||||
return runWithTraceRequest(async () => {
|
||||
const startedAt = Date.now();
|
||||
const requestHeaders = [...request.headers.entries()];
|
||||
const pathname = new URL(request.url).pathname;
|
||||
let requestBody: Promise<CapturedBody> | null = null;
|
||||
|
||||
log.trace(() => [
|
||||
'webui_mutation_start method=%j url=%j headers=%s',
|
||||
request.method,
|
||||
request.url,
|
||||
renderParamsVerbose(requestHeaders),
|
||||
]);
|
||||
|
||||
if (!STREAMED_REQUEST_PATHS.has(pathname)) {
|
||||
try {
|
||||
requestBody = captureBody(request.clone());
|
||||
} catch (error) {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=failed reason=request_clone_failed error=%j elapsedMs=%d',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await next();
|
||||
if (STREAMED_RESPONSE_PATHS.has(pathname)) {
|
||||
return traceStreamedResponse(response, requestBody, startedAt);
|
||||
}
|
||||
let responseBody: Promise<CapturedBody>;
|
||||
try {
|
||||
responseBody = captureBody(response.clone());
|
||||
} catch (error) {
|
||||
void traceRequestBody(requestBody).then(() => {
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=failed reason=response_clone_failed error=%j elapsedMs=%d',
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
void settleMutation(
|
||||
requestBody,
|
||||
responseBody,
|
||||
response,
|
||||
startedAt,
|
||||
STREAMED_REQUEST_PATHS.has(pathname) && request.signal.aborted,
|
||||
);
|
||||
return response;
|
||||
} catch (error) {
|
||||
await traceRequestBody(requestBody);
|
||||
const failure = failureOutcome(error);
|
||||
log.trace(
|
||||
'webui_mutation_terminal outcome=%s reason=%s error=%j elapsedMs=%d',
|
||||
failure.outcome,
|
||||
failure.reason,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -58,6 +58,7 @@ import { bindStateStream } from './state-stream';
|
||||
import type { StateBus, StateResource } from './state-bus';
|
||||
import { startConnectionDiffLoop } from './connection-diff-loop';
|
||||
import { comparableConnectionSnapshot } from './connection-snapshot';
|
||||
import { traceAuthenticatedWebuiMutation } from './mutation-trace';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { findAvailablePort } from './port';
|
||||
import {
|
||||
@@ -607,7 +608,10 @@ export async function initWebUI(
|
||||
}
|
||||
|
||||
c.set('sessionToken' as never, token);
|
||||
await next();
|
||||
c.res = await traceAuthenticatedWebuiMutation(c.req.raw, async () => {
|
||||
await next();
|
||||
return c.res;
|
||||
});
|
||||
});
|
||||
|
||||
// Periodic janitor — keeps sessionTokens / loginAttempts from growing
|
||||
|
||||
@@ -28,6 +28,12 @@ function makeSender() {
|
||||
};
|
||||
}
|
||||
|
||||
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'Bridge.Runtime',
|
||||
);
|
||||
}
|
||||
|
||||
function packet(pid: number, uin: string): PacketInfo {
|
||||
return {
|
||||
pid,
|
||||
@@ -51,6 +57,78 @@ describe('BridgeManager PID ownership', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('traces binding, account replacement, detach, and session closure under semantic contexts', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
manager.onHookLogin(202, '10001', makeSender().client);
|
||||
manager.onHookLogin(101, '20002', makeSender().client);
|
||||
manager.onPidDisconnected(202);
|
||||
manager.onPidDisconnected(101);
|
||||
manager.onPidDisconnected(101);
|
||||
|
||||
const trace = runtimeTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('bridge_binding_')
|
||||
|| entry.message.startsWith('bridge_detach_'));
|
||||
expect(trace.map((entry) => entry.message)).toEqual([
|
||||
'bridge_binding_start pid=101 uin="10001" source=login previousUin=null',
|
||||
'bridge_binding_branch pid=101 uin="10001" branch=session_created',
|
||||
expect.stringMatching(/^bridge_binding_terminal pid=101 uin="10001" source=login outcome=completed reason=bound created=true activePid=101 elapsedMs=\d+$/),
|
||||
'bridge_binding_start pid=202 uin="10001" source=login previousUin=null',
|
||||
expect.stringMatching(/^bridge_binding_terminal pid=202 uin="10001" source=login outcome=completed reason=bound created=false activePid=202 elapsedMs=\d+$/),
|
||||
'bridge_binding_start pid=101 uin="20002" source=login previousUin="10001"',
|
||||
'bridge_binding_branch pid=101 uin="20002" branch=account_rebind previousUin="10001"',
|
||||
'bridge_binding_branch pid=101 uin="20002" branch=previous_session_retained previousUin="10001" activePid=202',
|
||||
'bridge_binding_branch pid=101 uin="20002" branch=session_created',
|
||||
expect.stringMatching(/^bridge_binding_terminal pid=101 uin="20002" source=login outcome=completed reason=rebound created=true activePid=101 elapsedMs=\d+$/),
|
||||
'bridge_detach_start pid=202 uin="10001"',
|
||||
'bridge_detach_branch pid=202 uin="10001" branch=session_closed',
|
||||
expect.stringMatching(/^bridge_detach_terminal pid=202 uin="10001" outcome=completed reason=session_closed activePid=null elapsedMs=\d+$/),
|
||||
'bridge_detach_start pid=101 uin="20002"',
|
||||
'bridge_detach_branch pid=101 uin="20002" branch=session_closed',
|
||||
expect.stringMatching(/^bridge_detach_terminal pid=101 uin="20002" outcome=completed reason=session_closed activePid=null elapsedMs=\d+$/),
|
||||
]);
|
||||
|
||||
const starts = trace.filter((entry) => entry.message.includes('_start '));
|
||||
const terminals = trace.filter((entry) => entry.message.includes('_terminal '));
|
||||
expect(starts).toHaveLength(5);
|
||||
expect(terminals).toHaveLength(5);
|
||||
for (const start of starts) {
|
||||
expect(terminals.some((terminal) => terminal.req === start.req)).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records ownership invariant failures as the unique detach terminal', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
expect(() => manager.onPidDisconnected(101)).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
|
||||
);
|
||||
|
||||
const detach = runtimeTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('bridge_detach_'),
|
||||
);
|
||||
expect(detach.map((entry) => entry.message)).toEqual([
|
||||
'bridge_detach_start pid=101 uin="10001"',
|
||||
expect.stringMatching(/^bridge_detach_terminal pid=101 uin="10001" outcome=failed reason=invariant_violation error="BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID" elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(detach[0]!.req).toBe(detach[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records complete incoming packet bytes under one top-level TRACE request', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
@@ -230,6 +308,43 @@ describe('BridgeManager PID ownership', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('traces material sender selection, fallback, and no-sender drops without polling noise', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const first = makeSender();
|
||||
const second = makeSender();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', first.client);
|
||||
manager.onHookLogin(202, '10001', second.client);
|
||||
manager.onPacket(packet(202, '10001'));
|
||||
manager.onPidDisconnected(202);
|
||||
const bridge = manager.getSession('10001')!.bridge;
|
||||
manager.onPidDisconnected(101);
|
||||
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
|
||||
|
||||
const sender = runtimeTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('bridge_sender_fact ')
|
||||
|| entry.message.startsWith('bridge_send_'));
|
||||
expect(sender.map((entry) => entry.message)).toEqual([
|
||||
'bridge_sender_fact event=selected uin="10001" pid=101 previousPid=null',
|
||||
'bridge_sender_fact event=selected uin="10001" pid=202 previousPid=101',
|
||||
'bridge_sender_fact event=fallback uin="10001" detachedPid=202 fallbackPid=101',
|
||||
'bridge_send_start serviceCmd="Test.NoSender" uin="10001" activePid=null timeoutMs=15000 length=2 body=00ff',
|
||||
expect.stringMatching(/^bridge_send_terminal serviceCmd="Test\.NoSender" uin="10001" activePid=null outcome=dropped reason=no_sender length=2 body=00ff elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(sender[2]!.req).toBe(
|
||||
runtimeTrace(entries).find((entry) =>
|
||||
entry.message.startsWith('bridge_detach_start pid=202 '))!.req,
|
||||
);
|
||||
expect(sender[3]!.req).toEqual(expect.any(Number));
|
||||
expect(sender[4]!.req).toBe(sender[3]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports an account healthy while any attached PID still receives packets', () => {
|
||||
const manager = new BridgeManager();
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
|
||||
@@ -12,6 +12,14 @@
|
||||
// - closeafter:每个响应后半关闭(readableEnded/emit close)→ 退化成每块
|
||||
// 一连接,但仍全部成功。
|
||||
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { HttpConn0x6FF501Response } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
@@ -41,6 +49,10 @@ function buildErrorCodeFrame(): Buffer {
|
||||
return frame;
|
||||
}
|
||||
|
||||
function buildMalformedHighwayResponseFrame(): Buffer {
|
||||
return Buffer.from([0x28, 0, 0, 0, 5, 0, 0, 0, 0, 0x08, 0x01, 0x29]);
|
||||
}
|
||||
|
||||
function httpWrap(frame: Buffer): Buffer {
|
||||
const headers = ['HTTP/1.1 200 OK', `Content-Length: ${frame.length}`, '', ''].join('\r\n');
|
||||
return Buffer.concat([Buffer.from(headers, 'ascii'), frame]);
|
||||
@@ -62,6 +74,7 @@ class FakeSocket extends EventEmitter {
|
||||
private readonly mode: ServerMode,
|
||||
private readonly failOnPost = -1,
|
||||
private readonly truncateOnPost = -1,
|
||||
private readonly errorAfterPartialOnPost = -1,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
@@ -102,6 +115,15 @@ class FakeSocket extends EventEmitter {
|
||||
this.emit('close');
|
||||
return;
|
||||
}
|
||||
if (thisPost === this.errorAfterPartialOnPost) {
|
||||
const full = httpWrap(this.responseFrame);
|
||||
this.emit('data', full.subarray(0, full.length - 3));
|
||||
this.writable = false;
|
||||
this.readableEnded = true;
|
||||
this.emit('error', new Error('ECONNRESET after partial response'));
|
||||
this.emit('close');
|
||||
return;
|
||||
}
|
||||
if (thisPost === this.truncateOnPost) {
|
||||
// Send the HTTP header + only part of the declared body, then FIN —
|
||||
// a truncated response. Dropping the last 3 body bytes keeps the
|
||||
@@ -144,6 +166,7 @@ vi.mock('net', () => ({
|
||||
}));
|
||||
|
||||
import {
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
BufferChunkSource,
|
||||
type ChunkSource,
|
||||
@@ -152,6 +175,11 @@ import {
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function highwayTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
|
||||
}
|
||||
|
||||
function makeBridge(): BridgeContext {
|
||||
return { identity: { uin: '10001' } as unknown } as unknown as BridgeContext;
|
||||
@@ -200,8 +228,272 @@ class RecordingChunkSource implements ChunkSource {
|
||||
}
|
||||
}
|
||||
|
||||
describe('fetchHighwaySession trace lifecycle', () => {
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('records session metadata without duplicating packet control bytes', async () => {
|
||||
const responseData = protobuf_encode<HttpConn0x6FF501Response>({
|
||||
httpConn: {
|
||||
sigSession: new Uint8Array([0xAA, 0xBB]),
|
||||
sessionKey: new Uint8Array([0xCC]),
|
||||
serverInfos: [{
|
||||
serviceType: 1,
|
||||
serverAddrs: [{ ip: 0x04030201, port: 8080 }],
|
||||
}],
|
||||
},
|
||||
});
|
||||
const sendRawPacket = vi.fn<
|
||||
(cmd: string, body: Uint8Array) => Promise<{
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer;
|
||||
}>
|
||||
>(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(responseData),
|
||||
}));
|
||||
const bridge = {
|
||||
identity: { uin: '10001' },
|
||||
sendRawPacket,
|
||||
} as unknown as BridgeContext;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
expect([...session.sigSession]).toEqual([0xAA, 0xBB]);
|
||||
expect([...session.sessionKey]).toEqual([0xCC]);
|
||||
expect(session.host).toBe('1.2.3.4');
|
||||
expect(session.port).toBe(8080);
|
||||
const requestBytes = sendRawPacket.mock.calls[0]![1] as Uint8Array;
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
`highway_session_start serviceCmd="HttpConn.0x6ff_501" requestBytes=${requestBytes.byteLength}`,
|
||||
expect.stringContaining(`branch=control_response success=true gotResponse=true errorCode=0 errorMessage="" responseBytes=${responseData.byteLength}`),
|
||||
expect.stringMatching(/^highway_session_terminal outcome=completed reason=session_ready host="1\.2\.3\.4" port=8080 sigBytes=2 sessionKeyBytes=1 elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.join('\n')).not.toContain('requestHex=');
|
||||
expect(messages.join('\n')).not.toContain('responseHex=');
|
||||
expect(messages.filter((message) => message.startsWith('highway_session_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records a thrown control request as one failed terminal', async () => {
|
||||
const bridge = {
|
||||
identity: { uin: '10001' },
|
||||
sendRawPacket: vi.fn(async () => { throw new Error('fixture session pipe failure'); }),
|
||||
} as unknown as BridgeContext;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(fetchHighwaySession(bridge)).rejects.toThrow('fixture session pipe failure');
|
||||
const terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_session_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('records complete chunk control lifecycle without copying source bytes', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const sourceBytes = new Uint8Array([0xDE, 0xAD, 0xBE, 0xEF]);
|
||||
const fileMd5 = new Uint8Array([0x00, 0xFF, 0x10, 0x20]);
|
||||
const extend = new Uint8Array([0xCA, 0xFE]);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
new BufferChunkSource(sourceBytes),
|
||||
fileMd5,
|
||||
extend,
|
||||
);
|
||||
|
||||
const trace = highwayTrace(entries);
|
||||
expect(trace.every((entry) => entry.req !== undefined && entry.req === trace[0]!.req)).toBe(true);
|
||||
const messages = trace.map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('highway_put_start cmdId=1004'),
|
||||
expect.stringContaining('totalBytes=4'),
|
||||
expect.stringContaining('fileMd5=00ff1020'),
|
||||
expect.stringContaining('extendBytes=2'),
|
||||
expect.stringContaining('branch=chunk_read offset=0 bytes=4'),
|
||||
expect.stringMatching(/^highway_put_branch branch=chunk_control_request offset=0 bytes=4 headBytes=\d+ headHex=[0-9a-f]+$/),
|
||||
expect.stringContaining('branch=chunk_attempt offset=0 bytes=4 attempt=1'),
|
||||
expect.stringContaining('branch=chunk_control_response offset=0'),
|
||||
expect.stringContaining('branch=chunk_control_decoded offset=0 errorCode=0'),
|
||||
expect.stringMatching(/^highway_put_terminal cmdId=1004 outcome=completed reason=upload_complete totalBytes=4 uploadedBytes=4 connections=1 elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.join('\n')).not.toContain('deadbeef');
|
||||
expect(messages.filter((message) => message.startsWith('highway_put_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records reconnect at the same offset and one successful terminal', async () => {
|
||||
installFactory((idx) => idx === 0
|
||||
? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', 1)
|
||||
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
new BufferChunkSource(new Uint8Array([1, 2, 3])),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(0),
|
||||
);
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('branch=chunk_retry offset=0 bytes=3 attempt=1'),
|
||||
expect.stringContaining('branch=reconnect offset=0 attempt=2 connection=2'),
|
||||
expect.stringContaining('outcome=completed reason=upload_complete'),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('highway_put_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records definitive server rejection as one failed terminal', async () => {
|
||||
installFactory(() => new FakeSocket(buildErrorCodeFrame(), 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
new BufferChunkSource(new Uint8Array([1])),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(0),
|
||||
)).rejects.toThrow(/error_code=921/);
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('branch=chunk_control_response offset=0'),
|
||||
expect.stringContaining('errorCode=921'),
|
||||
expect.stringContaining('outcome=failed reason=server_rejected'),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('highway_put_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records malformed control bytes before the decode failure terminal', async () => {
|
||||
const malformed = buildMalformedHighwayResponseFrame();
|
||||
installFactory(() => new FakeSocket(malformed, 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array([1])),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow();
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toContainEqual(expect.stringContaining(
|
||||
`responseBytes=${malformed.byteLength} responseHex=${malformed.toString('hex')}`,
|
||||
));
|
||||
const terminals = messages.filter((message) => message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]).toContain('outcome=failed reason=control_decode_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records transport exhaustion after exactly three attempts', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', 1));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array([1])),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow(/transport failed after 3 attempts/);
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages.filter((message) => message.includes('branch=chunk_attempt offset=0'))).toHaveLength(3);
|
||||
expect(messages.filter((message) => message.includes('branch=chunk_retry offset=0'))).toHaveLength(2);
|
||||
const terminals = messages.filter((message) => message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]).toContain('outcome=failed reason=transport_exhausted');
|
||||
expect(terminals[0]).toContain('connections=3');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records source read and close failures with truthful unique terminals', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
const readFailure: ChunkSource = {
|
||||
size: 1,
|
||||
read: vi.fn(async () => { throw new Error('fixture read failed'); }),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, readFailure,
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow('fixture read failed');
|
||||
let terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=source_read_failed');
|
||||
|
||||
entries.length = 0;
|
||||
const closeFailure: ChunkSource = {
|
||||
size: 0,
|
||||
read: vi.fn(async () => new Uint8Array(0)),
|
||||
close: vi.fn(async () => { throw new Error('fixture close failed'); }),
|
||||
};
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, closeFailure,
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow('fixture close failed');
|
||||
terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=source_close_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
it('reuses ONE connection for a multi-block payload when keep-alive holds', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
@@ -258,22 +550,87 @@ describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => {
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('reconnects and re-sends the block when a response body is truncated mid-stream', async () => {
|
||||
it('reconnects and preserves partial control-response bytes when a body is truncated', async () => {
|
||||
// Peer FINs after the HTTP header but before the highway body is complete.
|
||||
// That truncation must be treated as a retryable transport failure (reject
|
||||
// in readHttpResponseBody), NOT resolved as a partial frame — otherwise
|
||||
// unpackHighwayFrame throws OUTSIDE the retry loop and fails the upload.
|
||||
const frame = buildEmptyHighwayResponseFrame();
|
||||
installFactory((idx) =>
|
||||
idx === 0
|
||||
? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', -1, /* truncateOnPost */ 1)
|
||||
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'),
|
||||
? new FakeSocket(frame, 'keepalive', -1, /* truncateOnPost */ 1)
|
||||
: new FakeSocket(frame, 'keepalive'),
|
||||
);
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
// conn #0 truncated block 0 → reconnect (#1) re-sends it and finishes.
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
const partial = frame.subarray(0, frame.length - 3);
|
||||
expect(highwayTrace(entries).map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
`branch=chunk_control_response_partial offset=0 attempt=1 responseBytes=${partial.byteLength} responseHex=${partial.toString('hex')}`,
|
||||
),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reconnects and preserves partial control-response bytes when the socket errors', async () => {
|
||||
const frame = buildEmptyHighwayResponseFrame();
|
||||
installFactory((idx) =>
|
||||
idx === 0
|
||||
? new FakeSocket(frame, 'keepalive', -1, -1, 1)
|
||||
: new FakeSocket(frame, 'keepalive'),
|
||||
);
|
||||
// conn #0 truncated block 0 → reconnect (#1) re-sends it and finishes.
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE))),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
const partial = frame.subarray(0, frame.length - 3);
|
||||
expect(highwayTrace(entries).map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
`branch=chunk_control_response_partial offset=0 attempt=1 responseBytes=${partial.byteLength} responseHex=${partial.toString('hex')}`,
|
||||
),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not preserve diagnostic response copies while TRACE is disabled', async () => {
|
||||
const frame = buildEmptyHighwayResponseFrame();
|
||||
installFactory((idx) =>
|
||||
idx === 0
|
||||
? new FakeSocket(frame, 'keepalive', -1, -1, 1)
|
||||
: new FakeSocket(frame, 'keepalive'),
|
||||
);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('info');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE))),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
expect(highwayTrace(entries)).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reads every offset exactly once, in order, and closes the source once (data safety)', async () => {
|
||||
|
||||
@@ -5,8 +5,14 @@
|
||||
// The OIDB response is built with real protobuf encoding so we exercise
|
||||
// the actual decode path inside the pipeline.
|
||||
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
@@ -28,6 +34,12 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from '@snowluma/protocol/highway/pipeline';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function highwayTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
|
||||
}
|
||||
|
||||
interface FakeUploadResponse {
|
||||
upload?: {
|
||||
uKey?: string;
|
||||
@@ -108,6 +120,122 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
vi.mocked(highway.buildHighwayExtend).mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
it('records fast-upload selection and one completed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } },
|
||||
}),
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await runNtv2Upload(baseParams({
|
||||
bridge,
|
||||
label: 'image',
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1003,
|
||||
bytes: new Uint8Array([0xDE, 0xAD]),
|
||||
md5: new Uint8Array([0x00, 0xFF]),
|
||||
sha1: new Uint8Array([0x10, 0x20]),
|
||||
}],
|
||||
}));
|
||||
const trace = highwayTrace(entries);
|
||||
expect(trace.every((entry) => entry.req !== undefined && entry.req === trace[0]!.req)).toBe(true);
|
||||
const messages = trace.map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^highway_media_start label="image" .*businessType=1 .*source:"top",cmdId:1003,size:2,storage:"buffer",md5:00ff,sha1:\[1020\]/),
|
||||
expect.stringContaining('branch=fast_upload'),
|
||||
expect.stringMatching(/^highway_media_terminal label="image" outcome=completed reason=fast_upload .*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.join('\n')).not.toContain('dead');
|
||||
expect(messages.filter((message) => message.startsWith('highway_media_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records required PUT and one failed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
upload: {
|
||||
uKey: 'ukey-secret',
|
||||
msgInfo: { msgInfoBody: [], extBizInfo: {} },
|
||||
},
|
||||
}),
|
||||
});
|
||||
vi.mocked(highway.uploadHighwayHttp).mockRejectedValueOnce(
|
||||
new Error('fixture PUT failed'),
|
||||
);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({
|
||||
bridge,
|
||||
label: 'video',
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1001,
|
||||
bytes: new Uint8Array([1]),
|
||||
md5: new Uint8Array([2]),
|
||||
sha1: new Uint8Array([3]),
|
||||
}],
|
||||
}))).rejects.toThrow('fixture PUT failed');
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('branch=put_required source="top" cmdId=1001 size=1'),
|
||||
expect.stringContaining('uKey="ukey-secret"'),
|
||||
expect.stringContaining('outcome=failed reason=put_failed'),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('highway_media_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records OIDB rejection as one failed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({}, { errorCode: 42, errorMsg: 'boom' }),
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
|
||||
.rejects.toThrow('OIDB error 42');
|
||||
const terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_media_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=oidb_rejected');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies a thrown OIDB transport call as request_failed', async () => {
|
||||
const bridge = makeBridge();
|
||||
bridge.sendRawPacket.mockRejectedValueOnce(new Error('fixture OIDB pipe failure'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
|
||||
.rejects.toThrow('fixture OIDB pipe failure');
|
||||
const terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_media_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('builds an NTV2 request body and dispatches to the configured serviceCmd', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
|
||||
@@ -155,6 +283,25 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
expect(upload.msgInfo?.msgInfoBody).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('rejects a successful envelope that is missing msgInfo with one failed terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({ upload: { uKey: 'fake-ukey' } }),
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
|
||||
.rejects.toThrow(/upload response missing msgInfo/);
|
||||
const terminals = highwayTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('highway_media_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=response_invalid');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('throws on transport failure', async () => {
|
||||
const bridge = makeBridge({ success: false, errorMessage: 'pipe broken', responseData: null });
|
||||
await expect(runNtv2Upload(baseParams({ bridge })))
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StateBus } from '../src/webui/state-bus';
|
||||
import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop';
|
||||
import { comparableConnectionSnapshot } from '../src/webui/connection-snapshot';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
describe('startConnectionDiffLoop', () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('does NOT publish when the snapshot is stable tick after tick', () => {
|
||||
const bus = new StateBus();
|
||||
@@ -22,6 +33,108 @@ describe('startConnectionDiffLoop', () => {
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('traces only changed snapshot publication under one semantic context', () => {
|
||||
const bus = new StateBus();
|
||||
const entries: LogEntry[] = [];
|
||||
let snap: unknown = [{ uin: '1', adapters: [] }];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => snap,
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(500);
|
||||
vi.advanceTimersByTime(1_500);
|
||||
expect(entries.filter((entry) => entry.scope === 'WebUI.Connections')).toEqual([]);
|
||||
|
||||
snap = [{ uin: '1', adapters: [{ kind: 'ws', status: 'connected' }] }];
|
||||
vi.advanceTimersByTime(500);
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
const trace = entries.filter((entry) =>
|
||||
entry.level === 'trace' && entry.scope === 'WebUI.Connections');
|
||||
expect(trace.map((entry) => entry.message)).toEqual([
|
||||
'connection_diff_start snapshot=[{uin:"1",adapters:[{kind:"ws",status:"connected"}]}]',
|
||||
'connection_diff_branch branch=publish resource=connections',
|
||||
expect.stringMatching(/^connection_diff_terminal outcome=completed reason=published elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(trace.map((entry) => entry.req)).toEqual([
|
||||
expect.any(Number),
|
||||
trace[0]!.req,
|
||||
trace[0]!.req,
|
||||
]);
|
||||
} finally {
|
||||
handle.dispose();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('routes snapshot and projector failures through the common logger without repeated noise', () => {
|
||||
const bus = new StateBus();
|
||||
const entries: LogEntry[] = [];
|
||||
const getSnapshot = vi.fn(() => { throw new Error('snapshot boom'); });
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const snapshotHandle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot,
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(2_000);
|
||||
expect(entries.filter((entry) =>
|
||||
entry.scope === 'WebUI.Connections'
|
||||
&& entry.message.includes('reason=snapshot_failed'))).toHaveLength(1);
|
||||
} finally {
|
||||
snapshotHandle.dispose();
|
||||
}
|
||||
|
||||
const projectorHandle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => [{ uin: '1' }],
|
||||
pickComparable: () => { throw new Error('projector boom'); },
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(2_000);
|
||||
const failures = entries.filter((entry) =>
|
||||
entry.scope === 'WebUI.Connections'
|
||||
&& entry.message.includes('reason=projector_failed'));
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]!.message).toMatch(
|
||||
/^connection_diff_terminal outcome=failed reason=projector_failed error="projector boom" elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
projectorHandle.dispose();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps one-shot projector failures visible when TRACE is disabled', () => {
|
||||
const bus = new StateBus();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('info');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => [{ uin: '1' }],
|
||||
pickComparable: () => { throw new Error('projector boom'); },
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(2_000);
|
||||
expect(entries.filter((entry) =>
|
||||
entry.level === 'error'
|
||||
&& entry.scope === 'WebUI.Connections'
|
||||
&& entry.message.includes('projector boom'))).toHaveLength(1);
|
||||
} finally {
|
||||
handle.dispose();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { traceAuthenticatedWebuiMutation } from '../src/webui/mutation-trace';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function mutationTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'WebUI.Mutation',
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForTerminal(entries: LogEntry[]): Promise<LogEntry[]> {
|
||||
await vi.waitFor(() => {
|
||||
expect(mutationTrace(entries).some(
|
||||
(entry) => entry.message.startsWith('webui_mutation_terminal '),
|
||||
)).toBe(true);
|
||||
});
|
||||
return mutationTrace(entries);
|
||||
}
|
||||
|
||||
describe('traceAuthenticatedWebuiMutation', () => {
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
it('traces a successful JSON write with complete request and response data', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const requestBody = '{"logLevel":"trace"}';
|
||||
const responseBody = '{"success":true}';
|
||||
const request = new Request('http://127.0.0.1/api/system/settings?source=test', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: 'Bearer exact-token',
|
||||
'content-type': 'application/json',
|
||||
'x-request-detail': 'complete',
|
||||
},
|
||||
body: requestBody,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(request, async () => new Response(
|
||||
responseBody,
|
||||
{
|
||||
status: 201,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'x-response-detail': 'complete',
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(await response.text()).toBe(responseBody);
|
||||
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace).toHaveLength(4);
|
||||
expect(trace[0]!.message).toContain('webui_mutation_start method="POST"');
|
||||
expect(trace[0]!.message).toContain(
|
||||
'url="http://127.0.0.1/api/system/settings?source=test"',
|
||||
);
|
||||
expect(trace[0]!.message).toContain('authorization');
|
||||
expect(trace[0]!.message).toContain('Bearer exact-token');
|
||||
expect(trace[0]!.message).toContain('x-request-detail');
|
||||
expect(trace[1]!.message).toContain('branch=request_body');
|
||||
expect(trace[1]!.message).toContain(`text=${JSON.stringify(requestBody)}`);
|
||||
expect(trace[1]!.message).toContain(
|
||||
`body=${Buffer.from(requestBody).toString('hex')}`,
|
||||
);
|
||||
expect(trace[2]!.message).toContain('branch=response status=201');
|
||||
expect(trace[2]!.message).toContain('x-response-detail');
|
||||
expect(trace[2]!.message).toContain(`text=${JSON.stringify(responseBody)}`);
|
||||
expect(trace[2]!.message).toContain(
|
||||
`body=${Buffer.from(responseBody).toString('hex')}`,
|
||||
);
|
||||
expect(trace[3]!.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=completed reason=response_completed status=201 elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.every((entry) => entry.req === trace[0]!.req)).toBe(true);
|
||||
expect(trace[0]!.req).toEqual(expect.any(Number));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('traces non-2xx and binary bodies without consuming the response', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const requestBytes = Uint8Array.from([0x00, 0xff, 0x80, 0x41]);
|
||||
const responseBytes = Uint8Array.from([0xde, 0xad, 0xbe, 0xef, 0x00]);
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/system/backup/import', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
body: requestBytes,
|
||||
}),
|
||||
async () => new Response(responseBytes, {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(new Uint8Array(await response.arrayBuffer())).toEqual(responseBytes);
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.find((entry) => entry.message.includes('branch=request_body'))?.message)
|
||||
.toContain('length=4');
|
||||
expect(trace.find((entry) => entry.message.includes('branch=request_body'))?.message)
|
||||
.toContain('body=00ff8041');
|
||||
expect(trace.find((entry) => entry.message.includes('branch=response'))?.message)
|
||||
.toContain('body=deadbeef00');
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=http_status status=422 elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.filter((entry) => entry.message.startsWith('webui_mutation_terminal ')))
|
||||
.toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('traces a thrown handler with one failed terminal and preserves the error', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const failure = new Error('write exploded');
|
||||
|
||||
try {
|
||||
await expect(traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/global-config', {
|
||||
method: 'POST',
|
||||
body: 'complete request',
|
||||
}),
|
||||
async () => { throw failure; },
|
||||
)).rejects.toBe(failure);
|
||||
|
||||
const trace = mutationTrace(entries);
|
||||
expect(trace.some((entry) =>
|
||||
entry.message.includes('branch=request_body')
|
||||
&& entry.message.includes('body=636f6d706c6574652072657175657374'))).toBe(true);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=handler_threw error="write exploded" elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.filter((entry) => entry.message.startsWith('webui_mutation_terminal ')))
|
||||
.toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies handler cancellation and timeout from their error provenance', async () => {
|
||||
setLogLevel('trace');
|
||||
|
||||
for (const [name, outcome, reason] of [
|
||||
['AbortError', 'cancelled', 'handler_cancelled'],
|
||||
['TimeoutError', 'timeout', 'handler_timeout'],
|
||||
] as const) {
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const failure = new DOMException(`${name} detail`, name);
|
||||
try {
|
||||
await expect(traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/processes/42/load', { method: 'POST' }),
|
||||
async () => { throw failure; },
|
||||
)).rejects.toBe(failure);
|
||||
expect(mutationTrace(entries).at(-1)?.message).toMatch(
|
||||
new RegExp(`^webui_mutation_terminal outcome=${outcome} reason=${reason} error="${name} detail" elapsedMs=\\d+$`),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('bypasses cloning and logging when TRACE is disabled', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('info');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request('http://127.0.0.1/api/system/settings', {
|
||||
method: 'POST',
|
||||
body: 'must remain unread',
|
||||
});
|
||||
const clone = vi.spyOn(request, 'clone');
|
||||
const next = vi.fn(async () => new Response('ok'));
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(request, next);
|
||||
expect(await response.text()).toBe('ok');
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect(clone).not.toHaveBeenCalled();
|
||||
expect(entries).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not clone the streamed upload request body', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request('http://127.0.0.1/api/debug/upload?filename=large.bin', {
|
||||
method: 'POST',
|
||||
body: Uint8Array.from([0x00, 0xff]),
|
||||
});
|
||||
const clone = vi.spyOn(request, 'clone');
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
request,
|
||||
async () => new Response('{"status":"ok"}', {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
expect(await response.json()).toEqual({ status: 'ok' });
|
||||
expect(clone).not.toHaveBeenCalled();
|
||||
await waitForTerminal(entries);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports an aborted streamed upload as cancelled even when the route returns 400', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const abort = new AbortController();
|
||||
const request = new Request('http://127.0.0.1/api/debug/upload?filename=cancelled.bin', {
|
||||
method: 'POST',
|
||||
body: Uint8Array.from([0x01]),
|
||||
signal: abort.signal,
|
||||
});
|
||||
|
||||
try {
|
||||
abort.abort();
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
request,
|
||||
async () => new Response('{"status":"failed"}', { status: 400 }),
|
||||
);
|
||||
expect(response.status).toBe(400);
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=cancelled reason=request_cancelled status=400 elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a non-abort streamed upload rejection as an HTTP failure', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request('http://127.0.0.1/api/debug/upload?filename=too-large.bin', {
|
||||
method: 'POST',
|
||||
body: Uint8Array.from([0x01]),
|
||||
});
|
||||
|
||||
try {
|
||||
await traceAuthenticatedWebuiMutation(
|
||||
request,
|
||||
async () => new Response('{"status":"failed"}', { status: 400 }),
|
||||
);
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=http_status status=400 elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not pull a streaming response ahead of the client', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
let pulls = 0;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
pulls += 1;
|
||||
controller.enqueue(Uint8Array.from([pulls]));
|
||||
if (pulls === 2) controller.close();
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/debug/invoke-stream', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
async () => new Response(stream),
|
||||
);
|
||||
|
||||
await Promise.resolve();
|
||||
expect(pulls).toBe(0);
|
||||
expect(new Uint8Array(await response.arrayBuffer()))
|
||||
.toEqual(Uint8Array.from([0x01, 0x02]));
|
||||
await waitForTerminal(entries);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns a streaming response before its body completes and traces completion later', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
let controller!: ReadableStreamDefaultController<Uint8Array>;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(value) {
|
||||
controller = value;
|
||||
value.enqueue(Uint8Array.from([0x01, 0x02]));
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/debug/invoke-stream', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
async () => new Response(stream, { status: 200 }),
|
||||
);
|
||||
|
||||
expect(response.body).not.toBeNull();
|
||||
expect(mutationTrace(entries).some(
|
||||
(entry) => entry.message.startsWith('webui_mutation_terminal '),
|
||||
)).toBe(false);
|
||||
|
||||
controller.enqueue(Uint8Array.from([0x03, 0x04]));
|
||||
controller.close();
|
||||
expect(new Uint8Array(await response.arrayBuffer()))
|
||||
.toEqual(Uint8Array.from([0x01, 0x02, 0x03, 0x04]));
|
||||
|
||||
const trace = await waitForTerminal(entries);
|
||||
const responseChunks = trace.filter((entry) =>
|
||||
entry.message.includes('branch=response_chunk'));
|
||||
expect(responseChunks.map((entry) => entry.message)).toEqual([
|
||||
'webui_mutation_branch branch=response_chunk offset=0 length=2 body=0102',
|
||||
'webui_mutation_branch branch=response_chunk offset=2 length=2 body=0304',
|
||||
]);
|
||||
expect(trace.every((entry) => entry.req === trace[0]!.req)).toBe(true);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=completed reason=response_completed status=200 elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records one failed terminal when the traced response body cannot be read', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const streamFailure = new Error('response stream exploded');
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Uint8Array.from([0xaa]));
|
||||
controller.error(streamFailure);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/debug/invoke-stream', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
async () => new Response(stream),
|
||||
);
|
||||
await expect(response.arrayBuffer()).rejects.toBe(streamFailure);
|
||||
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.some((entry) =>
|
||||
entry.message.includes('branch=request_body')
|
||||
&& entry.message.includes('body=7b7d'))).toBe(true);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=body_read_failed status=200 error="response stream exploded" elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.filter((entry) => entry.message.startsWith('webui_mutation_terminal ')))
|
||||
.toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['GET', '/api/config/12345'],
|
||||
['HEAD', '/api/config/12345'],
|
||||
['OPTIONS', '/api/config/12345'],
|
||||
['POST', '/api/auth/check-strength'],
|
||||
['POST', '/api/logs/level'],
|
||||
])('keeps %s %s outside mutation TRACE', async (method, pathname) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request(`http://127.0.0.1${pathname}`, { method });
|
||||
const clone = vi.spyOn(request, 'clone');
|
||||
|
||||
try {
|
||||
await traceAuthenticatedWebuiMutation(request, async () => new Response(null, { status: 204 }));
|
||||
expect(clone).not.toHaveBeenCalled();
|
||||
expect(mutationTrace(entries)).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { BridgeManager } from '@snowluma/core/manager';
|
||||
import { loadOneBotConfig } from './config';
|
||||
@@ -107,7 +107,7 @@ export class OneBotManager {
|
||||
|
||||
bind(bridgeManager: BridgeManager): void {
|
||||
bridgeManager.addSessionStartedListener((uin, bridge) => {
|
||||
this.onSessionStarted(uin, bridge);
|
||||
runWithoutRequestContext(() => this.onSessionStarted(uin, bridge));
|
||||
});
|
||||
|
||||
bridgeManager.addSessionClosedListener((uin) => {
|
||||
@@ -155,7 +155,7 @@ export class OneBotManager {
|
||||
const instance = this.instances.get(uin);
|
||||
if (!instance) return { online: false, applied: false, errors: [], adapters: [] };
|
||||
|
||||
const result = await instance.reloadConfig(config);
|
||||
const result = await runWithoutRequestContext(() => instance.reloadConfig(config));
|
||||
if (result.applied) {
|
||||
log.info('configuration applied: UIN=%s adapters=%d', uin, result.statuses.length);
|
||||
} else {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { currentRequestId, runWithRequestId } from '@snowluma/common/logger';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { OneBotManager } from '../src/manager';
|
||||
import type { OneBotConfig } from '../src/types';
|
||||
@@ -34,4 +35,23 @@ describe('OneBotManager config apply value ownership', () => {
|
||||
expect(instance.reloadConfig).toHaveBeenNthCalledWith(1, a);
|
||||
expect(instance.reloadConfig).toHaveBeenNthCalledWith(2, b);
|
||||
});
|
||||
|
||||
it('does not attach a caller operation to reconfigured network resources', async () => {
|
||||
const manager = new OneBotManager();
|
||||
const observedRequestIds: Array<number | undefined> = [];
|
||||
let observeDeferred!: () => void;
|
||||
const instance = {
|
||||
reloadConfig: vi.fn(async () => {
|
||||
observedRequestIds.push(currentRequestId());
|
||||
observeDeferred = () => observedRequestIds.push(currentRequestId());
|
||||
return { applied: true, errors: [], statuses: [] };
|
||||
}),
|
||||
};
|
||||
(manager as unknown as { instances: Map<string, unknown> }).instances.set('10001', instance);
|
||||
|
||||
await runWithRequestId(5101, () => manager.reloadConfig('10001', config('#reload')));
|
||||
observeDeferred();
|
||||
|
||||
expect(observedRequestIds).toEqual([undefined, undefined]);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { currentRequestId, runWithRequestId } from '@snowluma/common/logger';
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -44,6 +45,50 @@ describe('database migration estimates', () => {
|
||||
});
|
||||
|
||||
describe('OneBotManager database preparation', () => {
|
||||
it('detaches migration and network startup from the login operation', () => {
|
||||
let callbacks!: DatabaseMigrationCallbacks;
|
||||
const observedRequestIds: Array<number | undefined> = [];
|
||||
const task: DatabaseMigrationTask = {
|
||||
beginMigration: vi.fn(() => observedRequestIds.push(currentRequestId())),
|
||||
cancel: vi.fn(),
|
||||
start: vi.fn((next) => {
|
||||
observedRequestIds.push(currentRequestId());
|
||||
callbacks = next;
|
||||
}),
|
||||
};
|
||||
const instance = {
|
||||
...fakeInstance('10001', async () => undefined),
|
||||
waitUntilNetworkReady: vi.fn(() => {
|
||||
observedRequestIds.push(currentRequestId());
|
||||
return new Promise(() => undefined);
|
||||
}),
|
||||
startLoginHistorySync: vi.fn(),
|
||||
} as unknown as OneBotInstance;
|
||||
const manager = new OneBotManager({
|
||||
createDatabaseMigrationTask: () => task,
|
||||
createInstance: () => {
|
||||
observedRequestIds.push(currentRequestId());
|
||||
return instance;
|
||||
},
|
||||
});
|
||||
let startListener!: (uin: string, bridge: never) => void;
|
||||
manager.bind({
|
||||
addSessionStartedListener: (listener) => { startListener = listener; },
|
||||
addSessionClosedListener: vi.fn(),
|
||||
} as never);
|
||||
const bridge = {
|
||||
activePid: null,
|
||||
identity: { nickname: 'test' },
|
||||
fetchFriends: vi.fn(() => new Promise(() => undefined)),
|
||||
fetchGroups: vi.fn(() => new Promise(() => undefined)),
|
||||
};
|
||||
|
||||
runWithRequestId(5201, () => startListener('10001', bridge as never));
|
||||
callbacks.onReady();
|
||||
|
||||
expect(observedRequestIds).toEqual([undefined, undefined, undefined, undefined]);
|
||||
});
|
||||
|
||||
it('surfaces preparation as unavailable and ignores a stale completion after logout', async () => {
|
||||
let callbacks!: DatabaseMigrationCallbacks;
|
||||
const cancel = vi.fn();
|
||||
|
||||
@@ -8,7 +8,12 @@ import type {
|
||||
ReqDataHighwayHead,
|
||||
RespDataHighwayHead,
|
||||
} from '@snowluma/proto-defs/highway';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import net from 'net';
|
||||
import { promises as fsp } from 'fs';
|
||||
@@ -52,47 +57,109 @@ function ipv4ToString(value: number): string {
|
||||
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
|
||||
}
|
||||
|
||||
export async function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
|
||||
const request = protobuf_encode<HttpConn0x6FF501Request>({
|
||||
httpConn: {
|
||||
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||
serviceTypes: [1, 5, 10, 21],
|
||||
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||
},
|
||||
});
|
||||
type HighwayPutFailureReason =
|
||||
| 'control_decode_failed'
|
||||
| 'server_rejected'
|
||||
| 'source_close_failed'
|
||||
| 'source_read_failed'
|
||||
| 'transport_exhausted';
|
||||
|
||||
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||
interface HighwayPutTraceState {
|
||||
startedAt: number;
|
||||
uploadedBytes: number;
|
||||
connectCount: number;
|
||||
failureReason?: HighwayPutFailureReason;
|
||||
error?: unknown;
|
||||
}
|
||||
|
||||
class HighwayResponseReadError extends Error {
|
||||
constructor(message: string, readonly responseBody?: Uint8Array) {
|
||||
super(message);
|
||||
this.name = 'HighwayResponseReadError';
|
||||
}
|
||||
}
|
||||
|
||||
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
|
||||
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||
throw new Error('HttpConn response missing sig_session');
|
||||
}
|
||||
function highwayErrorText(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
const session: HighwaySession = {
|
||||
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||
host: 'htdata3.qq.com',
|
||||
port: 80,
|
||||
};
|
||||
export function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
|
||||
const startedAt = Date.now();
|
||||
return runWithTraceRequest(async () => {
|
||||
const request = protobuf_encode<HttpConn0x6FF501Request>({
|
||||
httpConn: {
|
||||
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
|
||||
serviceTypes: [1, 5, 10, 21],
|
||||
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
|
||||
},
|
||||
});
|
||||
log.trace(
|
||||
'highway_session_start serviceCmd=%j requestBytes=%d',
|
||||
'HttpConn.0x6ff_501',
|
||||
request.byteLength,
|
||||
);
|
||||
|
||||
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||
for (const addr of si.serverAddrs) {
|
||||
const ip = addr.ip ?? 0;
|
||||
const port = addr.port ?? 0;
|
||||
if (ip && port) {
|
||||
session.host = ipv4ToString(ip);
|
||||
session.port = port;
|
||||
let failureReason = 'request_failed';
|
||||
try {
|
||||
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
|
||||
log.trace(
|
||||
'highway_session_branch branch=control_response success=%s gotResponse=%s errorCode=%d errorMessage=%j responseBytes=%d',
|
||||
result.success,
|
||||
result.gotResponse,
|
||||
result.errorCode,
|
||||
result.errorMessage ?? '',
|
||||
result.responseData?.byteLength ?? 0,
|
||||
);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || 'HttpConn request failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.trace('session %s:%d sig=%dB', session.host, session.port, (session.sigSession as Uint8Array).length);
|
||||
return session;
|
||||
failureReason = 'response_decode_failed';
|
||||
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
|
||||
failureReason = 'response_invalid';
|
||||
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
|
||||
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
|
||||
throw new Error('HttpConn response missing sig_session');
|
||||
}
|
||||
|
||||
const session: HighwaySession = {
|
||||
sigSession: resp.httpConn.sigSession as Uint8Array,
|
||||
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
|
||||
host: 'htdata3.qq.com',
|
||||
port: 80,
|
||||
};
|
||||
|
||||
for (const si of resp.httpConn.serverInfos ?? []) {
|
||||
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
|
||||
for (const addr of si.serverAddrs) {
|
||||
const ip = addr.ip ?? 0;
|
||||
const port = addr.port ?? 0;
|
||||
if (ip && port) {
|
||||
session.host = ipv4ToString(ip);
|
||||
session.port = port;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'highway_session_terminal outcome=completed reason=session_ready host=%j port=%d sigBytes=%d sessionKeyBytes=%d elapsedMs=%d',
|
||||
session.host,
|
||||
session.port,
|
||||
session.sigSession.byteLength,
|
||||
session.sessionKey.byteLength,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return session;
|
||||
} catch (error) {
|
||||
log.trace(() => [
|
||||
'highway_session_terminal outcome=failed reason=%s error=%j elapsedMs=%d',
|
||||
failureReason,
|
||||
highwayErrorText(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function makeHighwayHead(
|
||||
@@ -192,12 +259,21 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
let totalNeeded = 0;
|
||||
let settled = false;
|
||||
|
||||
const partialResponseBody = (): Uint8Array | undefined => {
|
||||
if (headerEnd < 0 || getLogLevel() !== 'trace') return undefined;
|
||||
const buf = Buffer.concat(chunks);
|
||||
return new Uint8Array(buf.subarray(headerEnd));
|
||||
};
|
||||
|
||||
// Reset on every inbound chunk; fire if the peer goes silent mid-response.
|
||||
let idleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const armIdle = () => {
|
||||
if (idleTimer) clearTimeout(idleTimer);
|
||||
idleTimer = setTimeout(
|
||||
() => finish(() => reject(new Error('highway response read timeout (peer idle)'))),
|
||||
() => finish(() => reject(new HighwayResponseReadError(
|
||||
'highway response read timeout (peer idle)',
|
||||
partialResponseBody(),
|
||||
))),
|
||||
HIGHWAY_READ_IDLE_MS,
|
||||
);
|
||||
};
|
||||
@@ -232,7 +308,12 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
|
||||
}
|
||||
};
|
||||
const onError = (err: Error) => finish(() => reject(err));
|
||||
const onError = (err: Error) => finish(() => {
|
||||
const responseBody = partialResponseBody();
|
||||
reject(responseBody === undefined
|
||||
? err
|
||||
: new HighwayResponseReadError(err.message, responseBody));
|
||||
});
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
// A fully-received body would already have resolved in onData; reaching
|
||||
@@ -251,9 +332,12 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
if (headerEnd >= 0 && contentLength === 0) {
|
||||
resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
} else {
|
||||
reject(new Error(
|
||||
reject(new HighwayResponseReadError(
|
||||
`connection closed before full response (received=${buf.length}B, ` +
|
||||
`headerSeen=${headerEnd >= 0}${headerEnd >= 0 ? `, need=${totalNeeded}` : ''})`,
|
||||
headerEnd >= 0 && getLogLevel() === 'trace'
|
||||
? new Uint8Array(buf.subarray(headerEnd))
|
||||
: undefined,
|
||||
));
|
||||
}
|
||||
});
|
||||
@@ -332,9 +416,64 @@ export class FileChunkSource implements ChunkSource {
|
||||
close(): Promise<void> { return this.fh.close(); }
|
||||
}
|
||||
|
||||
export async function uploadHighwayHttp(
|
||||
export function uploadHighwayHttp(
|
||||
bridge: BridgeContext, session: HighwaySession, commandId: number,
|
||||
source: ChunkSource, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const state: HighwayPutTraceState = {
|
||||
startedAt: Date.now(),
|
||||
uploadedBytes: 0,
|
||||
connectCount: 0,
|
||||
};
|
||||
return runWithTraceRequest(async () => {
|
||||
log.trace(() => [
|
||||
'highway_put_start cmdId=%d uin=%j host=%j port=%d totalBytes=%d fileMd5=%s extendBytes=%d',
|
||||
commandId,
|
||||
bridge.identity.uin,
|
||||
session.host,
|
||||
session.port,
|
||||
source.size,
|
||||
renderTraceBytes(fileMd5),
|
||||
extend.byteLength,
|
||||
]);
|
||||
try {
|
||||
await uploadHighwayHttpOperation(
|
||||
bridge,
|
||||
session,
|
||||
commandId,
|
||||
source,
|
||||
fileMd5,
|
||||
extend,
|
||||
state,
|
||||
);
|
||||
log.trace(
|
||||
'highway_put_terminal cmdId=%d outcome=completed reason=upload_complete totalBytes=%d uploadedBytes=%d connections=%d elapsedMs=%d',
|
||||
commandId,
|
||||
source.size,
|
||||
state.uploadedBytes,
|
||||
state.connectCount,
|
||||
Date.now() - state.startedAt,
|
||||
);
|
||||
} catch (error) {
|
||||
log.trace(() => [
|
||||
'highway_put_terminal cmdId=%d outcome=failed reason=%s totalBytes=%d uploadedBytes=%d connections=%d error=%j elapsedMs=%d',
|
||||
commandId,
|
||||
state.failureReason ?? 'unexpected_failure',
|
||||
source.size,
|
||||
state.uploadedBytes,
|
||||
state.connectCount,
|
||||
highwayErrorText(state.error ?? error),
|
||||
Date.now() - state.startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function uploadHighwayHttpOperation(
|
||||
bridge: BridgeContext, session: HighwaySession, commandId: number,
|
||||
source: ChunkSource, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
trace: HighwayPutTraceState,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const totalSize = source.size;
|
||||
@@ -367,6 +506,7 @@ export async function uploadHighwayHttp(
|
||||
// disk (FileChunkSource); either way one chunk is read/held at a time. We
|
||||
// own the source and close it exactly once in the `finally` below.
|
||||
let succeeded = false;
|
||||
let sourceCloseFailure: { error: unknown } | undefined;
|
||||
let socket: net.Socket | null = null;
|
||||
let connectCount = 0;
|
||||
const dropSocket = (): void => {
|
||||
@@ -376,12 +516,27 @@ export async function uploadHighwayHttp(
|
||||
let offset = 0;
|
||||
while (offset < totalSize) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, totalSize - offset);
|
||||
const chunk = await source.read(offset, chunkSize);
|
||||
let chunk: Uint8Array;
|
||||
try {
|
||||
chunk = await source.read(offset, chunkSize);
|
||||
} catch (error) {
|
||||
trace.failureReason = 'source_read_failed';
|
||||
trace.error = error;
|
||||
throw error;
|
||||
}
|
||||
log.trace('highway_put_branch branch=chunk_read offset=%d bytes=%d', offset, chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, totalSize, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
log.trace(() => [
|
||||
'highway_put_branch branch=chunk_control_request offset=%d bytes=%d headBytes=%d headHex=%s',
|
||||
offset,
|
||||
chunkSize,
|
||||
head.byteLength,
|
||||
renderTraceBytes(head),
|
||||
]);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
|
||||
// Send this block, reusing the live connection when there is one. On any
|
||||
@@ -394,27 +549,84 @@ export async function uploadHighwayHttp(
|
||||
if (!socket) {
|
||||
socket = await tcpConnect(session.host, session.port);
|
||||
connectCount += 1;
|
||||
trace.connectCount = connectCount;
|
||||
log.trace(
|
||||
'highway_put_branch branch=%s offset=%d attempt=%d connection=%d',
|
||||
connectCount === 1 ? 'connect' : 'reconnect',
|
||||
offset,
|
||||
attempt,
|
||||
connectCount,
|
||||
);
|
||||
}
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_attempt offset=%d bytes=%d attempt=%d connection=%d',
|
||||
offset,
|
||||
chunkSize,
|
||||
attempt,
|
||||
connectCount,
|
||||
);
|
||||
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
break;
|
||||
} catch (err) {
|
||||
if (err instanceof HighwayResponseReadError && err.responseBody) {
|
||||
log.trace(() => [
|
||||
'highway_put_branch branch=chunk_control_response_partial offset=%d attempt=%d responseBytes=%d responseHex=%s',
|
||||
offset,
|
||||
attempt,
|
||||
err.responseBody!.byteLength,
|
||||
renderTraceBytes(err.responseBody!),
|
||||
]);
|
||||
}
|
||||
dropSocket();
|
||||
if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) {
|
||||
throw new Error(
|
||||
trace.failureReason = 'transport_exhausted';
|
||||
const exhausted = new Error(
|
||||
`highway upload transport failed after ${attempt} attempts ` +
|
||||
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`,
|
||||
);
|
||||
trace.error = exhausted;
|
||||
throw exhausted;
|
||||
}
|
||||
log.trace('chunk offset=%d attempt %d failed (%s), reconnecting', offset, attempt, String(err));
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d error=%j',
|
||||
offset,
|
||||
chunkSize,
|
||||
attempt,
|
||||
highwayErrorText(err),
|
||||
);
|
||||
await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt);
|
||||
}
|
||||
}
|
||||
|
||||
// Unreachable: the retry loop only exits via break (responseBody set) or
|
||||
// throw — the guard just narrows the type for the compiler.
|
||||
if (!responseBody) throw new Error('highway upload: missing response');
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (!responseBody) {
|
||||
trace.failureReason = 'transport_exhausted';
|
||||
trace.error = new Error('highway upload: missing response');
|
||||
throw trace.error;
|
||||
}
|
||||
log.trace(() => [
|
||||
'highway_put_branch branch=chunk_control_response offset=%d bytes=%d responseBytes=%d responseHex=%s',
|
||||
offset,
|
||||
chunkSize,
|
||||
responseBody.byteLength,
|
||||
renderTraceBytes(responseBody),
|
||||
]);
|
||||
let resp: RespDataHighwayHead;
|
||||
try {
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_control_decoded offset=%d errorCode=%d segRetCode=%d',
|
||||
offset,
|
||||
resp?.errorCode ?? 0,
|
||||
resp?.msgSegHead?.retCode ?? 0,
|
||||
);
|
||||
} catch (error) {
|
||||
trace.failureReason = 'control_decode_failed';
|
||||
trace.error = error;
|
||||
throw error;
|
||||
}
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
// Surface every diagnostic the highway response carries so
|
||||
// user reports of `error_code=921` and friends include the
|
||||
@@ -424,12 +636,14 @@ export async function uploadHighwayHttp(
|
||||
// limit.
|
||||
const segRetCode = resp.msgSegHead?.retCode ?? 0;
|
||||
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
|
||||
throw new Error(
|
||||
trace.failureReason = 'server_rejected';
|
||||
trace.error = new Error(
|
||||
`highway upload error_code=${resp.errorCode}` +
|
||||
` (cmdId=${commandId} chunk=${chunkSize}/${totalSize}` +
|
||||
` offset=${offset} segRetCode=${segRetCode}` +
|
||||
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
|
||||
);
|
||||
throw trace.error;
|
||||
}
|
||||
|
||||
// If the peer half-closed after sending its response, the socket can no
|
||||
@@ -440,7 +654,12 @@ export async function uploadHighwayHttp(
|
||||
}
|
||||
|
||||
offset += chunkSize;
|
||||
log.trace('uploaded %d/%d bytes', offset, totalSize);
|
||||
trace.uploadedBytes = offset;
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_completed offset=%d totalBytes=%d',
|
||||
offset,
|
||||
totalSize,
|
||||
);
|
||||
}
|
||||
succeeded = true;
|
||||
if (totalSize > 0) {
|
||||
@@ -454,7 +673,14 @@ export async function uploadHighwayHttp(
|
||||
try {
|
||||
await source.close();
|
||||
} catch (closeErr) {
|
||||
if (succeeded) throw closeErr;
|
||||
if (succeeded) {
|
||||
sourceCloseFailure = { error: closeErr };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sourceCloseFailure) {
|
||||
trace.failureReason = 'source_close_failed';
|
||||
trace.error = sourceCloseFailure.error;
|
||||
throw sourceCloseFailure.error;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import {
|
||||
createLogger,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import type {
|
||||
EncodableMediaMsgInfo,
|
||||
HighwayMsgInfoBody,
|
||||
@@ -106,6 +110,27 @@ export function hexToBytes(hex: string): Uint8Array {
|
||||
return out;
|
||||
}
|
||||
|
||||
function sha1TraceValue(value: Uint8Array | Uint8Array[]): string {
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
return `[${values.map((item) => renderTraceBytes(item)).join(',')}]`;
|
||||
}
|
||||
|
||||
function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
|
||||
return `[${uploads.map((sub) => [
|
||||
`source:${JSON.stringify(String(sub.source))}`,
|
||||
`cmdId:${sub.cmdId}`,
|
||||
`size:${sub.fileSource ? sub.fileSource.fileSize : sub.bytes.byteLength}`,
|
||||
`storage:${JSON.stringify(sub.fileSource ? 'disk' : 'buffer')}`,
|
||||
`md5:${renderTraceBytes(sub.md5)}`,
|
||||
`sha1:${sha1TraceValue(sub.sha1)}`,
|
||||
`subFileIndex:${sub.subFileIndex ?? 0}`,
|
||||
].join(',')).join(';')}]`;
|
||||
}
|
||||
|
||||
function mediaErrorText(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
// ─────────────── main entrypoint ───────────────
|
||||
|
||||
/**
|
||||
@@ -116,7 +141,54 @@ export function hexToBytes(hex: string): Uint8Array {
|
||||
* Sessions are cached across sub-file uploads — video does two PUTs but
|
||||
* only fetches the Highway session once.
|
||||
*/
|
||||
export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
|
||||
export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
|
||||
const startedAt = Date.now();
|
||||
const label = params.label ?? 'media';
|
||||
let failureReason = 'unexpected_failure';
|
||||
let didPut = false;
|
||||
return runWithTraceRequest(async () => {
|
||||
moduleLog.trace(() => [
|
||||
'highway_media_start label=%j scope=%s target=%j oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
|
||||
label,
|
||||
params.isGroup ? 'group' : 'private',
|
||||
String(params.targetIdOrUid),
|
||||
params.oidbCmd,
|
||||
params.serviceCmd,
|
||||
params.requestId,
|
||||
params.businessType,
|
||||
uploadDescriptors(params.uploads),
|
||||
]);
|
||||
try {
|
||||
const result = await runNtv2UploadOperation(params, (reason, put) => {
|
||||
failureReason = reason;
|
||||
if (put !== undefined) didPut = put;
|
||||
});
|
||||
moduleLog.trace(
|
||||
'highway_media_terminal label=%j outcome=completed reason=%s uploads=%d elapsedMs=%d',
|
||||
label,
|
||||
didPut ? 'put_complete' : 'fast_upload',
|
||||
params.uploads.length,
|
||||
Date.now() - startedAt,
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
moduleLog.trace(() => [
|
||||
'highway_media_terminal label=%j outcome=failed reason=%s uploads=%d error=%j elapsedMs=%d',
|
||||
label,
|
||||
failureReason,
|
||||
params.uploads.length,
|
||||
mediaErrorText(error),
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function runNtv2UploadOperation(
|
||||
params: NtV2UploadParams,
|
||||
setState: (failureReason: string, didPut?: boolean) => void,
|
||||
): Promise<NTV2UploadRespBody> {
|
||||
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
|
||||
const label = params.label ?? 'media';
|
||||
const raw = bridge.identity?.uin;
|
||||
@@ -160,24 +232,38 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
|
||||
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
|
||||
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
|
||||
|
||||
setState('request_failed');
|
||||
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
|
||||
log.trace(() => [
|
||||
'highway_media_branch branch=oidb_response success=%s gotResponse=%s errorCode=%d errorMessage=%j responseBytes=%d',
|
||||
result.success,
|
||||
result.gotResponse,
|
||||
result.errorCode,
|
||||
result.errorMessage ?? '',
|
||||
result.responseData?.byteLength ?? 0,
|
||||
]);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(result.errorMessage || `${label} upload request failed`);
|
||||
}
|
||||
|
||||
setState('response_decode_failed');
|
||||
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
|
||||
if (!resp) throw new Error(`failed to decode ${label} upload response`);
|
||||
if (resp.errorCode && resp.errorCode !== 0) {
|
||||
setState('oidb_rejected');
|
||||
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
|
||||
}
|
||||
|
||||
const uploadBody = resp.body;
|
||||
setState('response_invalid');
|
||||
if (!uploadBody) throw new Error(`${label} upload response body missing`);
|
||||
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
|
||||
setState('business_rejected');
|
||||
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
|
||||
}
|
||||
const upload = uploadBody.upload;
|
||||
if (!upload) throw new Error(`${label} upload response body missing`);
|
||||
if (!upload.msgInfo) throw new Error('upload response missing msgInfo');
|
||||
return upload;
|
||||
};
|
||||
|
||||
@@ -186,12 +272,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
|
||||
// retry shouldn't re-fetch it either.
|
||||
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
|
||||
const getSession = async () => {
|
||||
setState('session_failed');
|
||||
session ??= await fetchHighwaySession(bridge);
|
||||
return session;
|
||||
};
|
||||
|
||||
// Run whatever PUTs the given `upload` response asks for.
|
||||
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
|
||||
const msgInfo = upload.msgInfo;
|
||||
if (!msgInfo) throw new Error('upload response missing msgInfo');
|
||||
let didPut = false;
|
||||
for (const sub of uploads) {
|
||||
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
|
||||
@@ -201,26 +290,49 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
|
||||
// keying the checks below on `bytes.length` would wrongly treat it as a
|
||||
// fast-only / empty sub-file.
|
||||
const subSize = sub.fileSource ? sub.fileSource.fileSize : sub.bytes.length;
|
||||
// No uKey: the server fast-pathed this sub-file (or msgInfo is absent
|
||||
// entirely) — it already holds (or claims to hold) the resource, so
|
||||
// there are no bytes to push for it.
|
||||
if (!uKey || !upload.msgInfo) {
|
||||
if (!uKey && upload.msgInfo && subSize > 0) {
|
||||
// No uKey: the server fast-pathed this sub-file — it already holds
|
||||
// (or claims to hold) the resource, so there are no bytes to push.
|
||||
if (!uKey) {
|
||||
if (subSize > 0) {
|
||||
log.trace(
|
||||
'highway_media_branch branch=fast_upload source=%j cmdId=%d size=%d',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
subSize,
|
||||
);
|
||||
log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (subSize === 0) {
|
||||
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
|
||||
log.trace(
|
||||
'highway_media_branch branch=empty_source source=%j cmdId=%d hasFastOnlyError=%s',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
Boolean(sub.fastOnlyError),
|
||||
);
|
||||
if (sub.fastOnlyError) {
|
||||
setState('source_unavailable');
|
||||
throw new Error(sub.fastOnlyError);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!target) continue;
|
||||
|
||||
log.trace(
|
||||
'highway_media_branch branch=put_required source=%j cmdId=%d size=%d uKey=%j storage=%s',
|
||||
String(sub.source),
|
||||
sub.cmdId,
|
||||
subSize,
|
||||
uKey,
|
||||
sub.fileSource ? 'disk' : 'buffer',
|
||||
);
|
||||
setState('extend_build_failed');
|
||||
const extend = buildHighwayExtend(
|
||||
uKey,
|
||||
upload.msgInfo,
|
||||
msgInfo,
|
||||
target.ipv4s ?? [],
|
||||
sub.sha1,
|
||||
sub.subFileIndex ?? 0,
|
||||
@@ -231,14 +343,17 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
|
||||
// session-fetch failure on the first PUT would leak the open handle.
|
||||
const putSession = await getSession();
|
||||
// uploadHighwayHttp owns the ChunkSource and closes it exactly once.
|
||||
setState('source_open_failed');
|
||||
const chunkSource = sub.fileSource
|
||||
? await FileChunkSource.open(sub.fileSource.filePath, sub.fileSource.fileSize)
|
||||
: new BufferChunkSource(sub.bytes);
|
||||
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, subSize, String(sub.source));
|
||||
const t0 = Date.now();
|
||||
setState('put_failed');
|
||||
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
setState('unexpected_failure', true);
|
||||
}
|
||||
|
||||
if (!didPut) {
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import {
|
||||
createLogger,
|
||||
getLogLevel,
|
||||
renderTraceBytes,
|
||||
runWithTraceRequest,
|
||||
} from '@snowluma/common/logger';
|
||||
import { renderParamsVerbose } from '@snowluma/common/log-summary';
|
||||
|
||||
const log = createLogger('Protocol.Http');
|
||||
|
||||
type RequestBody = string | Buffer | Uint8Array | Record<string, unknown> | undefined;
|
||||
|
||||
@@ -29,6 +38,81 @@ interface HttpRequestContext {
|
||||
deadlineAt?: number;
|
||||
}
|
||||
|
||||
type HttpTerminalReason =
|
||||
| 'deadline'
|
||||
| 'non_2xx'
|
||||
| 'parse_failure'
|
||||
| 'redirect_failure'
|
||||
| 'request_invalid'
|
||||
| 'response_aborted'
|
||||
| 'response_too_large'
|
||||
| 'transport_failure';
|
||||
|
||||
type HttpOperationOutcome = 'failed' | 'timeout' | 'cancelled';
|
||||
|
||||
interface HttpFailureClassification {
|
||||
outcome: HttpOperationOutcome;
|
||||
reason: HttpTerminalReason;
|
||||
}
|
||||
|
||||
const httpFailures = new WeakMap<Error, HttpFailureClassification>();
|
||||
|
||||
type CookieTerminalReason =
|
||||
| 'response_complete'
|
||||
| 'redirect_limit'
|
||||
| 'redirect_failure'
|
||||
| 'deadline'
|
||||
| 'transport_failure';
|
||||
|
||||
interface CookieCollectionResult {
|
||||
reason: CookieTerminalReason;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
interface HttpTraceOperation {
|
||||
readonly startedAt: number;
|
||||
readonly method: string;
|
||||
readonly url: string;
|
||||
terminal: boolean;
|
||||
}
|
||||
|
||||
function errorObject(error: unknown): Error {
|
||||
return error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
|
||||
function errorText(error: unknown): string {
|
||||
return errorObject(error).message;
|
||||
}
|
||||
|
||||
function fail(
|
||||
outcome: HttpOperationOutcome,
|
||||
reason: HttpTerminalReason,
|
||||
error: unknown,
|
||||
): Error {
|
||||
const result = errorObject(error);
|
||||
if (!httpFailures.has(result)) httpFailures.set(result, { outcome, reason });
|
||||
return result;
|
||||
}
|
||||
|
||||
function traceTerminal(
|
||||
trace: HttpTraceOperation,
|
||||
outcome: 'completed' | HttpOperationOutcome,
|
||||
reason: 'response_complete' | HttpTerminalReason,
|
||||
error?: unknown,
|
||||
): void {
|
||||
if (trace.terminal) return;
|
||||
trace.terminal = true;
|
||||
log.trace(() => [
|
||||
'http_terminal method=%j url=%j outcome=%s reason=%s%s elapsedMs=%d',
|
||||
trace.method,
|
||||
trace.url,
|
||||
outcome,
|
||||
reason,
|
||||
error === undefined ? '' : ` error=${JSON.stringify(errorText(error))}`,
|
||||
Date.now() - trace.startedAt,
|
||||
]);
|
||||
}
|
||||
|
||||
const SENSITIVE_REDIRECT_HEADERS = new Set([
|
||||
'authorization',
|
||||
'cookie',
|
||||
@@ -58,33 +142,130 @@ export class RequestUtil {
|
||||
// qzone.qq.com) — without the ceiling that would hang every cookie-backed web
|
||||
// action forever (the essential cookies are already set by the first hop).
|
||||
static async HttpsGetCookies(url: string, depth = 0): Promise<{ [key: string]: string; }> {
|
||||
const startedAt = Date.now();
|
||||
return runWithTraceRequest(async () => {
|
||||
const cookies: Record<string, string> = {};
|
||||
log.trace('http_cookie_start url=%j depth=%d', url, depth);
|
||||
let result: CookieCollectionResult;
|
||||
try {
|
||||
result = await this.collectCookies(url, depth, cookies);
|
||||
} catch (error) {
|
||||
result = { reason: 'transport_failure', error: errorObject(error) };
|
||||
}
|
||||
log.trace(() => [
|
||||
'http_cookie_terminal url=%j outcome=completed reason=%s failOpen=%s cookies=%s%s elapsedMs=%d',
|
||||
url,
|
||||
result.reason,
|
||||
result.reason !== 'response_complete',
|
||||
renderParamsVerbose(cookies),
|
||||
result.error === undefined ? '' : ` error=${JSON.stringify(errorText(result.error))}`,
|
||||
Date.now() - startedAt,
|
||||
]);
|
||||
return cookies;
|
||||
});
|
||||
}
|
||||
|
||||
private static collectCookies(
|
||||
url: string,
|
||||
depth: number,
|
||||
cookies: Record<string, string>,
|
||||
): Promise<CookieCollectionResult> {
|
||||
const client = url.startsWith('https') ? https : http;
|
||||
return new Promise((resolve) => {
|
||||
const cookies: { [key: string]: string; } = {};
|
||||
let settled = false;
|
||||
const done = (extra?: { [key: string]: string; }) => {
|
||||
let traceResponseDeadline: (() => void) | undefined;
|
||||
const done = (reason: CookieTerminalReason, error?: unknown) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(extra ? { ...cookies, ...extra } : cookies);
|
||||
resolve({
|
||||
reason,
|
||||
...(error === undefined ? {} : { error: errorObject(error) }),
|
||||
});
|
||||
};
|
||||
const req = client.get(url, (res) => {
|
||||
if (res.headers['set-cookie']) {
|
||||
this.extractCookies(res.headers['set-cookie'], cookies);
|
||||
}
|
||||
res.on('data', () => { }); // 必须消耗流
|
||||
log.trace(() => [
|
||||
'http_cookie_response url=%j status=%s headers=%s cookies=%s',
|
||||
url,
|
||||
res.statusCode ?? 'unknown',
|
||||
renderParamsVerbose(res.headers),
|
||||
renderParamsVerbose(cookies),
|
||||
]);
|
||||
const traceChunks: Buffer[] | null = getLogLevel() === 'trace' ? [] : null;
|
||||
let traceResponseBytes = 0;
|
||||
let bodyTraced = false;
|
||||
const traceBody = (state: 'complete' | 'aborted' | 'error' | 'deadline') => {
|
||||
if (bodyTraced) return;
|
||||
bodyTraced = true;
|
||||
if (traceChunks === null) return;
|
||||
const body = Buffer.concat(traceChunks, traceResponseBytes);
|
||||
log.trace(() => [
|
||||
'http_cookie_body url=%j state=%s bodyBytes=%d bodyHex=%s body=%j',
|
||||
url,
|
||||
state,
|
||||
traceResponseBytes,
|
||||
renderTraceBytes(body),
|
||||
body.toString(),
|
||||
]);
|
||||
};
|
||||
traceResponseDeadline = () => traceBody('deadline');
|
||||
res.on('data', (chunk: string | Buffer) => {
|
||||
if (traceChunks === null) return;
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
traceResponseBytes += bytes.length;
|
||||
traceChunks.push(bytes);
|
||||
});
|
||||
res.once('aborted', () => {
|
||||
traceBody('aborted');
|
||||
done('transport_failure', new Error('cookie response aborted before completion'));
|
||||
});
|
||||
res.once('error', (error: Error) => {
|
||||
traceBody('error');
|
||||
done('transport_failure', error);
|
||||
});
|
||||
res.on('end', () => {
|
||||
traceBody('complete');
|
||||
const location = res.headers.location;
|
||||
if ((res.statusCode === 301 || res.statusCode === 302) && location && depth < 5) {
|
||||
this.HttpsGetCookies(new URL(location, url).href, depth + 1)
|
||||
.then((rc) => done(rc))
|
||||
.catch(() => done());
|
||||
} else {
|
||||
done();
|
||||
if ((res.statusCode === 301 || res.statusCode === 302) && location) {
|
||||
if (depth >= 5) {
|
||||
done('redirect_limit');
|
||||
return;
|
||||
}
|
||||
let redirectUrl: string;
|
||||
try {
|
||||
redirectUrl = new URL(location, url).href;
|
||||
} catch {
|
||||
done('redirect_failure');
|
||||
return;
|
||||
}
|
||||
log.trace(() => [
|
||||
'http_cookie_branch branch=redirect status=%d from=%j to=%j cookies=%s remainingRedirects=%d',
|
||||
res.statusCode,
|
||||
url,
|
||||
redirectUrl,
|
||||
renderParamsVerbose(cookies),
|
||||
5 - depth,
|
||||
]);
|
||||
this.collectCookies(redirectUrl, depth + 1, cookies)
|
||||
.then((result) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(result);
|
||||
})
|
||||
.catch((error) => done('transport_failure', error));
|
||||
return;
|
||||
}
|
||||
done('response_complete');
|
||||
});
|
||||
});
|
||||
req.setTimeout(8000, () => { req.destroy(); done(); });
|
||||
req.on('error', () => done());
|
||||
req.setTimeout(8000, () => {
|
||||
traceResponseDeadline?.();
|
||||
req.destroy();
|
||||
done('deadline');
|
||||
});
|
||||
req.on('error', (error) => done('transport_failure', error));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,40 +286,94 @@ export class RequestUtil {
|
||||
[key: string]: string;
|
||||
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5,
|
||||
responseLimits: HttpResponseLimits = {}): Promise<T> {
|
||||
validateLimit('timeoutMs', responseLimits.timeoutMs);
|
||||
validateLimit('maxResponseBytes', responseLimits.maxResponseBytes);
|
||||
|
||||
return this.request<T>({
|
||||
const methodName = method.toUpperCase();
|
||||
const trace: HttpTraceOperation = {
|
||||
startedAt: Date.now(),
|
||||
method: methodName,
|
||||
url,
|
||||
method,
|
||||
data,
|
||||
headers,
|
||||
isJsonRet,
|
||||
isArgJson,
|
||||
maxRedirects,
|
||||
responseLimits,
|
||||
deadlineAt: responseLimits.timeoutMs === undefined
|
||||
? undefined
|
||||
: Date.now() + responseLimits.timeoutMs,
|
||||
terminal: false,
|
||||
};
|
||||
|
||||
return runWithTraceRequest(async () => {
|
||||
log.trace(() => [
|
||||
'http_start method=%j url=%j headers=%s data=%s responseType=%s timeoutMs=%s maxResponseBytes=%s',
|
||||
methodName,
|
||||
url,
|
||||
renderParamsVerbose(headers),
|
||||
renderParamsVerbose(data),
|
||||
isJsonRet ? 'json' : 'text',
|
||||
responseLimits.timeoutMs ?? 'none',
|
||||
responseLimits.maxResponseBytes ?? 'none',
|
||||
]);
|
||||
|
||||
try {
|
||||
try {
|
||||
validateLimit('timeoutMs', responseLimits.timeoutMs);
|
||||
validateLimit('maxResponseBytes', responseLimits.maxResponseBytes);
|
||||
} catch (error) {
|
||||
throw fail('failed', 'request_invalid', error);
|
||||
}
|
||||
const value = await this.request<T>({
|
||||
url,
|
||||
method: methodName,
|
||||
data,
|
||||
headers,
|
||||
isJsonRet,
|
||||
isArgJson,
|
||||
maxRedirects,
|
||||
responseLimits,
|
||||
deadlineAt: responseLimits.timeoutMs === undefined
|
||||
? undefined
|
||||
: Date.now() + responseLimits.timeoutMs,
|
||||
});
|
||||
traceTerminal(trace, 'completed', 'response_complete');
|
||||
return value;
|
||||
} catch (error: unknown) {
|
||||
const result = errorObject(error);
|
||||
const classification = httpFailures.get(result) ?? {
|
||||
outcome: 'failed' as const,
|
||||
reason: 'transport_failure' as const,
|
||||
};
|
||||
traceTerminal(
|
||||
trace,
|
||||
classification.outcome,
|
||||
classification.reason,
|
||||
result,
|
||||
);
|
||||
throw result;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static async request<T>(context: HttpRequestContext): Promise<T> {
|
||||
const option = new URL(context.url);
|
||||
let option: URL;
|
||||
try {
|
||||
option = new URL(context.url);
|
||||
} catch (error) {
|
||||
throw fail('failed', 'request_invalid', error);
|
||||
}
|
||||
const protocol = option.protocol === 'https:'
|
||||
? https
|
||||
: option.protocol === 'http:'
|
||||
? http
|
||||
: undefined;
|
||||
if (!protocol) {
|
||||
throw new Error(`unsupported request protocol: ${option.protocol}`);
|
||||
throw fail(
|
||||
'failed',
|
||||
'request_invalid',
|
||||
new Error(`unsupported request protocol: ${option.protocol}`),
|
||||
);
|
||||
}
|
||||
|
||||
const remainingTimeoutMs = context.deadlineAt === undefined
|
||||
? undefined
|
||||
: context.deadlineAt - Date.now();
|
||||
if (remainingTimeoutMs !== undefined && remainingTimeoutMs <= 0) {
|
||||
throw new Error(`request timed out after ${context.responseLimits.timeoutMs} ms`);
|
||||
throw fail(
|
||||
'timeout',
|
||||
'deadline',
|
||||
new Error(`request timed out after ${context.responseLimits.timeoutMs} ms`),
|
||||
);
|
||||
}
|
||||
|
||||
const options = {
|
||||
@@ -152,6 +387,9 @@ export class RequestUtil {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let traceResponseFailure: ((
|
||||
state: 'aborted' | 'deadline' | 'error' | 'too_large',
|
||||
) => void) | undefined;
|
||||
const clearDeadline = () => {
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
};
|
||||
@@ -174,107 +412,232 @@ export class RequestUtil {
|
||||
next.then(resolve).catch(reject);
|
||||
};
|
||||
|
||||
const req = protocol.request(options, (res: http.IncomingMessage) => {
|
||||
const closeCurrent = () => {
|
||||
res.destroy();
|
||||
req.destroy();
|
||||
};
|
||||
res.once('error', (error: Error) => rejectOnce(error));
|
||||
let req: http.ClientRequest;
|
||||
try {
|
||||
req = protocol.request(options, (res: http.IncomingMessage) => {
|
||||
const statusCode = res.statusCode ?? 0;
|
||||
const closeCurrent = () => {
|
||||
res.destroy();
|
||||
req.destroy();
|
||||
};
|
||||
res.once('error', (error: Error) => {
|
||||
traceResponseFailure?.('error');
|
||||
rejectOnce(fail('failed', 'transport_failure', error));
|
||||
});
|
||||
res.once('aborted', () => {
|
||||
traceResponseFailure?.('aborted');
|
||||
rejectOnce(fail(
|
||||
'cancelled',
|
||||
'response_aborted',
|
||||
new Error('response aborted before completion'),
|
||||
));
|
||||
});
|
||||
|
||||
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
|
||||
if (context.maxRedirects <= 0) {
|
||||
rejectOnce(new Error('Too many redirects'));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
if ((statusCode === 301 || statusCode === 302 || statusCode === 307 || statusCode === 308) && res.headers.location) {
|
||||
log.trace(() => [
|
||||
'http_response status=%d url=%j headers=%s bodyState=not_read',
|
||||
statusCode,
|
||||
context.url,
|
||||
renderParamsVerbose(res.headers),
|
||||
]);
|
||||
if (context.maxRedirects <= 0) {
|
||||
rejectOnce(fail('failed', 'redirect_failure', new Error('Too many redirects')));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
|
||||
let redirectUrl: URL;
|
||||
try {
|
||||
redirectUrl = new URL(res.headers.location, option);
|
||||
} catch (error) {
|
||||
rejectOnce(new Error('invalid redirect location', { cause: error }));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
|
||||
rejectOnce(new Error(`unsupported redirect protocol: ${redirectUrl.protocol}`));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
if (option.origin !== redirectUrl.origin
|
||||
let redirectUrl: URL;
|
||||
try {
|
||||
redirectUrl = new URL(res.headers.location, option);
|
||||
} catch (error) {
|
||||
rejectOnce(fail(
|
||||
'failed',
|
||||
'redirect_failure',
|
||||
new Error('invalid redirect location', { cause: error }),
|
||||
));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
|
||||
rejectOnce(fail(
|
||||
'failed',
|
||||
'redirect_failure',
|
||||
new Error(`unsupported redirect protocol: ${redirectUrl.protocol}`),
|
||||
));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
if (option.origin !== redirectUrl.origin
|
||||
&& context.method.toUpperCase() !== 'GET'
|
||||
&& context.method.toUpperCase() !== 'HEAD') {
|
||||
rejectOnce(new Error(
|
||||
`cross-origin redirect cannot forward method ${context.method.toUpperCase()}`,
|
||||
rejectOnce(fail(
|
||||
'failed',
|
||||
'redirect_failure',
|
||||
new Error(
|
||||
`cross-origin redirect cannot forward method ${context.method.toUpperCase()}`,
|
||||
),
|
||||
));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
|
||||
const redirectHeaders = headersForRedirect(context.headers, option, redirectUrl);
|
||||
log.trace(() => [
|
||||
'http_branch branch=redirect status=%d from=%j to=%j nextHeaders=%s remainingRedirects=%d',
|
||||
statusCode,
|
||||
context.url,
|
||||
redirectUrl.href,
|
||||
renderParamsVerbose(redirectHeaders),
|
||||
context.maxRedirects - 1,
|
||||
]);
|
||||
handOff(this.request<T>({
|
||||
...context,
|
||||
url: redirectUrl.href,
|
||||
headers: redirectHeaders,
|
||||
maxRedirects: context.maxRedirects - 1,
|
||||
}));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
log.trace(() => [
|
||||
'http_response status=%d url=%j headers=%s bodyState=not_read',
|
||||
statusCode,
|
||||
context.url,
|
||||
renderParamsVerbose(res.headers),
|
||||
]);
|
||||
rejectOnce(fail(
|
||||
'failed',
|
||||
'non_2xx',
|
||||
new Error(`Unexpected status code: ${res.statusCode}`),
|
||||
));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
|
||||
handOff(this.request<T>({
|
||||
...context,
|
||||
url: redirectUrl.href,
|
||||
headers: headersForRedirect(context.headers, option, redirectUrl),
|
||||
maxRedirects: context.maxRedirects - 1,
|
||||
}));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
|
||||
rejectOnce(new Error(`Unexpected status code: ${res.statusCode}`));
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
let responseBytes = 0;
|
||||
res.on('data', (chunk: string | Buffer) => {
|
||||
if (settled) return;
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
responseBytes += bytes.length;
|
||||
if (context.responseLimits.maxResponseBytes !== undefined
|
||||
const chunks: Buffer[] = [];
|
||||
let responseBytes = 0;
|
||||
let failureBodyTraced = false;
|
||||
traceResponseFailure = (state) => {
|
||||
if (failureBodyTraced) return;
|
||||
failureBodyTraced = true;
|
||||
log.trace(() => {
|
||||
const observedBody = Buffer.concat(chunks, responseBytes);
|
||||
return [
|
||||
'http_response status=%d url=%j headers=%s bodyState=%s bodyBytes=%d bodyHex=%s body=%j',
|
||||
statusCode,
|
||||
context.url,
|
||||
renderParamsVerbose(res.headers),
|
||||
state,
|
||||
responseBytes,
|
||||
renderTraceBytes(observedBody),
|
||||
observedBody.toString(),
|
||||
];
|
||||
});
|
||||
};
|
||||
res.on('data', (chunk: string | Buffer) => {
|
||||
if (settled) return;
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
responseBytes += bytes.length;
|
||||
chunks.push(bytes);
|
||||
if (context.responseLimits.maxResponseBytes !== undefined
|
||||
&& responseBytes > context.responseLimits.maxResponseBytes) {
|
||||
const error = new Error(
|
||||
`response body exceeds ${context.responseLimits.maxResponseBytes} bytes`,
|
||||
);
|
||||
rejectOnce(error);
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
chunks.push(bytes);
|
||||
});
|
||||
|
||||
res.on('end', () => {
|
||||
if (settled) return;
|
||||
const responseBody = Buffer.concat(chunks, responseBytes).toString();
|
||||
try {
|
||||
if (context.isJsonRet) {
|
||||
resolveOnce(JSON.parse(responseBody) as T);
|
||||
} else {
|
||||
resolveOnce(responseBody as T);
|
||||
traceResponseFailure?.('too_large');
|
||||
const error = fail(
|
||||
'failed',
|
||||
'response_too_large',
|
||||
new Error(
|
||||
`response body exceeds ${context.responseLimits.maxResponseBytes} bytes`,
|
||||
),
|
||||
);
|
||||
rejectOnce(error);
|
||||
closeCurrent();
|
||||
return;
|
||||
}
|
||||
} catch (parseError: unknown) {
|
||||
rejectOnce(new Error(parseError instanceof Error ? parseError.message : String(parseError)));
|
||||
}
|
||||
});
|
||||
|
||||
res.on('end', () => {
|
||||
if (settled) return;
|
||||
failureBodyTraced = true;
|
||||
const responseBuffer = Buffer.concat(chunks, responseBytes);
|
||||
const responseBody = responseBuffer.toString();
|
||||
log.trace(() => [
|
||||
'http_response status=%d url=%j headers=%s bodyBytes=%d bodyHex=%s body=%j',
|
||||
statusCode,
|
||||
context.url,
|
||||
renderParamsVerbose(res.headers),
|
||||
responseBytes,
|
||||
renderTraceBytes(responseBuffer),
|
||||
responseBody,
|
||||
]);
|
||||
try {
|
||||
if (context.isJsonRet) {
|
||||
const parsed = JSON.parse(responseBody) as T;
|
||||
log.trace(() => [
|
||||
'http_branch branch=parse_completed responseType=json result=%s',
|
||||
renderParamsVerbose(parsed),
|
||||
]);
|
||||
resolveOnce(parsed);
|
||||
} else {
|
||||
log.trace('http_branch branch=parse_completed responseType=text');
|
||||
resolveOnce(responseBody as T);
|
||||
}
|
||||
} catch (parseError: unknown) {
|
||||
log.trace(() => [
|
||||
'http_branch branch=parse_failed responseType=json error=%j',
|
||||
errorText(parseError),
|
||||
]);
|
||||
rejectOnce(fail('failed', 'parse_failure', parseError));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
rejectOnce(fail('failed', 'request_invalid', error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (remainingTimeoutMs !== undefined) {
|
||||
timeout = setTimeout(() => {
|
||||
traceResponseFailure?.('deadline');
|
||||
const error = new Error(
|
||||
`request timed out after ${context.responseLimits.timeoutMs} ms`,
|
||||
);
|
||||
rejectOnce(error);
|
||||
rejectOnce(fail('timeout', 'deadline', error));
|
||||
req.destroy();
|
||||
}, remainingTimeoutMs);
|
||||
}
|
||||
|
||||
req.on('error', (error: Error) => rejectOnce(error));
|
||||
if (context.method === 'POST' || context.method === 'PUT' || context.method === 'PATCH') {
|
||||
req.write(context.isArgJson ? JSON.stringify(context.data) : context.data);
|
||||
req.on('error', (error: Error) => rejectOnce(
|
||||
fail('failed', 'transport_failure', error),
|
||||
));
|
||||
try {
|
||||
if (context.method === 'POST' || context.method === 'PUT' || context.method === 'PATCH') {
|
||||
const requestBody = context.isArgJson
|
||||
? JSON.stringify(context.data)
|
||||
: context.data;
|
||||
if (typeof requestBody === 'string'
|
||||
|| Buffer.isBuffer(requestBody)
|
||||
|| requestBody instanceof Uint8Array) {
|
||||
log.trace(() => {
|
||||
const requestBytes = typeof requestBody === 'string'
|
||||
? Buffer.from(requestBody)
|
||||
: requestBody;
|
||||
return [
|
||||
'http_branch branch=request_body url=%j requestBytes=%d requestHex=%s',
|
||||
context.url,
|
||||
requestBytes.byteLength,
|
||||
renderTraceBytes(requestBytes),
|
||||
];
|
||||
});
|
||||
}
|
||||
req.write(requestBody);
|
||||
}
|
||||
req.end();
|
||||
} catch (error) {
|
||||
rejectOnce(fail('failed', 'request_invalid', error));
|
||||
req.destroy();
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import http from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { RequestUtil } from '@snowluma/protocol/web/request-util';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
const servers = new Set<http.Server>();
|
||||
|
||||
async function serve(
|
||||
@@ -19,6 +27,8 @@ async function serve(
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.useRealTimers();
|
||||
await Promise.all([...servers].map(async (server) => {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
@@ -26,19 +36,427 @@ afterEach(async () => {
|
||||
}));
|
||||
});
|
||||
|
||||
describe('RequestUtil bounded text responses', () => {
|
||||
it('rejects a response once it exceeds the byte limit', async () => {
|
||||
const { url } = await serve((_req, res) => {
|
||||
res.end('x'.repeat(65));
|
||||
});
|
||||
function httpTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Protocol.Http');
|
||||
}
|
||||
|
||||
await expect(RequestUtil.HttpGetText(
|
||||
url,
|
||||
'GET',
|
||||
undefined,
|
||||
{},
|
||||
{ maxResponseBytes: 64 },
|
||||
)).rejects.toThrow('response body exceeds 64 bytes');
|
||||
describe('RequestUtil TRACE lifecycle', () => {
|
||||
it('records complete request and parsed response data under one request context', async () => {
|
||||
const { url } = await serve(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe('{"message":"request-secret"}');
|
||||
res.setHeader('X-Response-Token', 'response-secret-header');
|
||||
res.end('{"ok":true,"token":"response-secret-body"}');
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpGetJson(
|
||||
`${url}/write?access_token=url-secret`,
|
||||
'POST',
|
||||
{ message: 'request-secret' },
|
||||
{
|
||||
Authorization: 'Bearer request-secret-header',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
)).resolves.toEqual({ ok: true, token: 'response-secret-body' });
|
||||
|
||||
const trace = httpTrace(entries);
|
||||
expect(trace.length).toBeGreaterThanOrEqual(4);
|
||||
expect(trace.every((entry) => entry.req !== undefined && entry.req === trace[0]!.req)).toBe(true);
|
||||
expect(trace.map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('http_start method="POST"'),
|
||||
expect.stringContaining('access_token=url-secret'),
|
||||
expect.stringContaining('request-secret-header'),
|
||||
expect.stringContaining('request-secret'),
|
||||
expect.stringContaining('http_response status=200'),
|
||||
expect.stringContaining('response-secret-header'),
|
||||
expect.stringContaining('response-secret-body'),
|
||||
expect.stringContaining('http_branch branch=parse_completed'),
|
||||
expect.stringMatching(/^http_terminal method="POST" .* outcome=completed reason=response_complete elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(trace.filter((entry) => entry.message.startsWith('http_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records exact request and response bytes for binary HTTP data', async () => {
|
||||
const requestBytes = Uint8Array.from([0x00, 0xff, 0x80, 0x41]);
|
||||
const responseBytes = Buffer.from([0xde, 0xad, 0xbe, 0xef, 0x00]);
|
||||
const { url } = await serve(async (req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks)).toEqual(Buffer.from(requestBytes));
|
||||
res.end(responseBytes);
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpGetText(
|
||||
url,
|
||||
'POST',
|
||||
requestBytes,
|
||||
{ 'Content-Type': 'application/octet-stream' },
|
||||
)).resolves.toBe(responseBytes.toString());
|
||||
|
||||
const messages = httpTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('requestBytes=4 requestHex=00ff8041'),
|
||||
expect.stringContaining('bodyBytes=5 bodyHex=deadbeef00'),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records redirect input changes and one non-2xx terminal without waiting for the body', async () => {
|
||||
const target = await serve((_req, res) => {
|
||||
res.writeHead(403, { 'X-Diagnostic': 'denied' });
|
||||
res.flushHeaders();
|
||||
res.write('body that never ends');
|
||||
});
|
||||
const source = await serve((_req, res) => {
|
||||
res.writeHead(302, { location: target.url });
|
||||
res.end();
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpGetText(
|
||||
source.url,
|
||||
'GET',
|
||||
undefined,
|
||||
{ Cookie: 'uin=redirect-secret' },
|
||||
)).rejects.toThrow('Unexpected status code: 403');
|
||||
|
||||
const messages = httpTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('http_branch branch=redirect status=302'),
|
||||
expect.stringContaining(`to=${JSON.stringify(`${target.url}/`)}`),
|
||||
expect.stringContaining('http_response status=403'),
|
||||
expect.stringContaining('bodyState=not_read'),
|
||||
expect.stringMatching(/^http_terminal method="GET" .* outcome=failed reason=non_2xx .*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('http_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
'not a valid URL',
|
||||
'file:///tmp/not-a-web-request',
|
||||
])('classifies invalid initial request URL %j without falling back to transport or redirect failure', async (url) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpGetText(url)).rejects.toThrow();
|
||||
const terminals = httpTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('http_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_invalid');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['timeoutMs', { timeoutMs: 0 }],
|
||||
['maxResponseBytes', { maxResponseBytes: 0 }],
|
||||
] as const)('traces invalid %s before rejecting the request', async (_name, limits) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpGetText(
|
||||
'http://127.0.0.1/',
|
||||
'GET',
|
||||
undefined,
|
||||
{},
|
||||
limits,
|
||||
)).rejects.toThrow('must be a positive safe integer');
|
||||
const trace = httpTrace(entries);
|
||||
expect(trace.some((entry) => entry.message.startsWith('http_start '))).toBe(true);
|
||||
const terminals = trace.filter((entry) => entry.message.startsWith('http_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_invalid');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'method token',
|
||||
run: () => RequestUtil.HttpGetText('http://127.0.0.1:1/', 'BAD METHOD'),
|
||||
},
|
||||
{
|
||||
name: 'header value',
|
||||
run: () => RequestUtil.HttpGetText(
|
||||
'http://127.0.0.1:1/',
|
||||
'GET',
|
||||
undefined,
|
||||
{ 'X-Invalid': 'line one\nline two' },
|
||||
),
|
||||
},
|
||||
{
|
||||
name: 'circular JSON body',
|
||||
run: () => {
|
||||
const body: Record<string, unknown> = {};
|
||||
body.self = body;
|
||||
return RequestUtil.HttpGetJson('http://127.0.0.1:1/', 'POST', body);
|
||||
},
|
||||
},
|
||||
])('classifies an invalid local $name as request_invalid', async ({ run }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(run()).rejects.toThrow();
|
||||
const terminals = httpTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('http_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_invalid');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'parse failure',
|
||||
run: async () => {
|
||||
const { url } = await serve((_req, res) => res.end('{invalid-json'));
|
||||
return RequestUtil.HttpGetJson(url);
|
||||
},
|
||||
reason: 'parse_failure',
|
||||
outcome: 'failed',
|
||||
bodyState: undefined,
|
||||
},
|
||||
{
|
||||
name: 'timeout',
|
||||
run: async () => {
|
||||
const { url } = await serve((_req, res) => {
|
||||
res.writeHead(200);
|
||||
res.write('partial');
|
||||
});
|
||||
return RequestUtil.HttpGetText(url, 'GET', undefined, {}, { timeoutMs: 30 });
|
||||
},
|
||||
reason: 'deadline',
|
||||
outcome: 'timeout',
|
||||
bodyState: 'deadline',
|
||||
},
|
||||
{
|
||||
name: 'transport failure',
|
||||
run: async () => {
|
||||
const { url } = await serve((req) => req.socket.destroy());
|
||||
return RequestUtil.HttpGetText(url);
|
||||
},
|
||||
reason: 'transport_failure',
|
||||
outcome: 'failed',
|
||||
bodyState: undefined,
|
||||
},
|
||||
{
|
||||
name: 'response cancellation',
|
||||
run: async () => {
|
||||
const { url } = await serve((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Length': '100' });
|
||||
res.flushHeaders();
|
||||
res.write('partial');
|
||||
setImmediate(() => res.destroy());
|
||||
});
|
||||
return RequestUtil.HttpGetText(url, 'GET', undefined, {}, { timeoutMs: 250 });
|
||||
},
|
||||
reason: 'response_aborted',
|
||||
outcome: 'cancelled',
|
||||
bodyState: 'aborted',
|
||||
},
|
||||
])('records a unique $name terminal', async ({ run, reason, outcome, bodyState }) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(run()).rejects.toThrow();
|
||||
const terminals = httpTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('http_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain(`outcome=${outcome} reason=${reason}`);
|
||||
if (bodyState !== undefined) {
|
||||
expect(httpTrace(entries).map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
`bodyState=${bodyState} bodyBytes=7 bodyHex=7061727469616c body="partial"`,
|
||||
),
|
||||
]));
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('RequestUtil cookie redirect TRACE lifecycle', () => {
|
||||
it('records collected cookies and a completed terminal across redirects', async () => {
|
||||
const { url } = await serve((req, res) => {
|
||||
if (req.url === '/start') {
|
||||
res.writeHead(302, {
|
||||
location: '/finish',
|
||||
'Set-Cookie': 'p_skey=first-secret; Path=/',
|
||||
});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
res.writeHead(200, { 'Set-Cookie': 'skey=second-secret; Path=/' });
|
||||
res.end('ok');
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpsGetCookies(`${url}/start`)).resolves.toEqual({
|
||||
p_skey: 'first-secret',
|
||||
skey: 'second-secret',
|
||||
});
|
||||
const trace = httpTrace(entries);
|
||||
expect(trace.every((entry) => entry.req !== undefined && entry.req === trace[0]!.req)).toBe(true);
|
||||
expect(trace.map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('http_cookie_start'),
|
||||
expect.stringContaining('branch=redirect'),
|
||||
expect.stringContaining('first-secret'),
|
||||
expect.stringContaining('second-secret'),
|
||||
expect.stringContaining('bodyBytes=2 bodyHex=6f6b body="ok"'),
|
||||
expect.stringMatching(/^http_cookie_terminal .* outcome=completed reason=response_complete .*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(trace.filter((entry) => entry.message.startsWith('http_cookie_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('fails open when a cookie response aborts after headers', async () => {
|
||||
const { url } = await serve((_req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Length': '100',
|
||||
'Set-Cookie': 'p_skey=partial-secret; Path=/',
|
||||
});
|
||||
res.flushHeaders();
|
||||
res.write('partial');
|
||||
setImmediate(() => res.destroy());
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpsGetCookies(url)).resolves.toEqual({
|
||||
p_skey: 'partial-secret',
|
||||
});
|
||||
const terminals = httpTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('http_cookie_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain(
|
||||
'outcome=completed reason=transport_failure failOpen=true',
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('traces partial cookie response bytes before a fail-open deadline terminal', async () => {
|
||||
const { url } = await serve((_req, res) => {
|
||||
res.writeHead(200, {
|
||||
'Content-Length': '100',
|
||||
'Set-Cookie': 'p_skey=partial-secret; Path=/',
|
||||
});
|
||||
res.flushHeaders();
|
||||
res.write('partial');
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpsGetCookies(url)).resolves.toEqual({
|
||||
p_skey: 'partial-secret',
|
||||
});
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
const messages = httpTrace(entries).map((entry) => entry.message);
|
||||
const bodyIndex = messages.findIndex((message) =>
|
||||
message.includes('http_cookie_body ')
|
||||
&& message.includes('bodyBytes=7 bodyHex=7061727469616c body="partial"'));
|
||||
const terminalIndex = messages.findIndex((message) =>
|
||||
message.includes('http_cookie_terminal ')
|
||||
&& message.includes('reason=deadline failOpen=true'));
|
||||
expect(bodyIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(terminalIndex).toBeGreaterThan(bodyIndex);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
it('records a fail-open transport terminal while returning cookies collected earlier', async () => {
|
||||
const { url } = await serve((req, res) => {
|
||||
if (req.url === '/start') {
|
||||
res.writeHead(302, {
|
||||
location: '/broken',
|
||||
'Set-Cookie': 'p_skey=collected-secret; Path=/',
|
||||
});
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
req.socket.destroy(new Error('fixture cookie transport reset'));
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpsGetCookies(`${url}/start`)).resolves.toEqual({
|
||||
p_skey: 'collected-secret',
|
||||
});
|
||||
const terminals = httpTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('http_cookie_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain(
|
||||
'outcome=completed reason=transport_failure failOpen=true',
|
||||
);
|
||||
expect(terminals[0]!.message).toContain('collected-secret');
|
||||
expect(terminals[0]!.message).toContain('socket hang up');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('RequestUtil bounded text responses', () => {
|
||||
it('rejects a response once it exceeds the byte limit and traces every observed byte', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
const body = 'x'.repeat(65);
|
||||
const { url } = await serve((_req, res) => {
|
||||
res.end(body);
|
||||
});
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(RequestUtil.HttpGetText(
|
||||
url,
|
||||
'GET',
|
||||
undefined,
|
||||
{},
|
||||
{ maxResponseBytes: 64 },
|
||||
)).rejects.toThrow('response body exceeds 64 bytes');
|
||||
|
||||
expect(httpTrace(entries).map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
`bodyState=too_large bodyBytes=65 bodyHex=${'78'.repeat(65)}`,
|
||||
),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects a request that does not complete before its deadline', async () => {
|
||||
|
||||
Reference in new issue
Block a user