feat(logging): complete runtime trace diagnostics

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

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

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

No files matched your search

+48 -6
View File
@@ -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,
+98 -8
View File
@@ -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);
+4 -1
View File
@@ -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)) {
+297
View File
@@ -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;
}
});
}
+5 -1
View File
@@ -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 () => {
+148 -1
View File
@@ -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();
}
});
});