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,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
|
||||
|
||||
Reference in new issue
Block a user