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
@@ -28,6 +28,12 @@ function makeSender() {
|
||||
};
|
||||
}
|
||||
|
||||
function runtimeTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'Bridge.Runtime',
|
||||
);
|
||||
}
|
||||
|
||||
function packet(pid: number, uin: string): PacketInfo {
|
||||
return {
|
||||
pid,
|
||||
@@ -51,6 +57,78 @@ describe('BridgeManager PID ownership', () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('traces binding, account replacement, detach, and session closure under semantic contexts', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
manager.onHookLogin(202, '10001', makeSender().client);
|
||||
manager.onHookLogin(101, '20002', makeSender().client);
|
||||
manager.onPidDisconnected(202);
|
||||
manager.onPidDisconnected(101);
|
||||
manager.onPidDisconnected(101);
|
||||
|
||||
const trace = runtimeTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('bridge_binding_')
|
||||
|| entry.message.startsWith('bridge_detach_'));
|
||||
expect(trace.map((entry) => entry.message)).toEqual([
|
||||
'bridge_binding_start pid=101 uin="10001" source=login previousUin=null',
|
||||
'bridge_binding_branch pid=101 uin="10001" branch=session_created',
|
||||
expect.stringMatching(/^bridge_binding_terminal pid=101 uin="10001" source=login outcome=completed reason=bound created=true activePid=101 elapsedMs=\d+$/),
|
||||
'bridge_binding_start pid=202 uin="10001" source=login previousUin=null',
|
||||
expect.stringMatching(/^bridge_binding_terminal pid=202 uin="10001" source=login outcome=completed reason=bound created=false activePid=202 elapsedMs=\d+$/),
|
||||
'bridge_binding_start pid=101 uin="20002" source=login previousUin="10001"',
|
||||
'bridge_binding_branch pid=101 uin="20002" branch=account_rebind previousUin="10001"',
|
||||
'bridge_binding_branch pid=101 uin="20002" branch=previous_session_retained previousUin="10001" activePid=202',
|
||||
'bridge_binding_branch pid=101 uin="20002" branch=session_created',
|
||||
expect.stringMatching(/^bridge_binding_terminal pid=101 uin="20002" source=login outcome=completed reason=rebound created=true activePid=101 elapsedMs=\d+$/),
|
||||
'bridge_detach_start pid=202 uin="10001"',
|
||||
'bridge_detach_branch pid=202 uin="10001" branch=session_closed',
|
||||
expect.stringMatching(/^bridge_detach_terminal pid=202 uin="10001" outcome=completed reason=session_closed activePid=null elapsedMs=\d+$/),
|
||||
'bridge_detach_start pid=101 uin="20002"',
|
||||
'bridge_detach_branch pid=101 uin="20002" branch=session_closed',
|
||||
expect.stringMatching(/^bridge_detach_terminal pid=101 uin="20002" outcome=completed reason=session_closed activePid=null elapsedMs=\d+$/),
|
||||
]);
|
||||
|
||||
const starts = trace.filter((entry) => entry.message.includes('_start '));
|
||||
const terminals = trace.filter((entry) => entry.message.includes('_terminal '));
|
||||
expect(starts).toHaveLength(5);
|
||||
expect(terminals).toHaveLength(5);
|
||||
for (const start of starts) {
|
||||
expect(terminals.some((terminal) => terminal.req === start.req)).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records ownership invariant failures as the unique detach terminal', () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
manager.getSession('10001')!.bridge.detachPid(101);
|
||||
expect(() => manager.onPidDisconnected(101)).toThrowError(
|
||||
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
|
||||
);
|
||||
|
||||
const detach = runtimeTrace(entries).filter(
|
||||
(entry) => entry.message.startsWith('bridge_detach_'),
|
||||
);
|
||||
expect(detach.map((entry) => entry.message)).toEqual([
|
||||
'bridge_detach_start pid=101 uin="10001"',
|
||||
expect.stringMatching(/^bridge_detach_terminal pid=101 uin="10001" outcome=failed reason=invariant_violation error="BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID" elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(detach[0]!.req).toBe(detach[1]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records complete incoming packet bytes under one top-level TRACE request', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const entries: LogEntry[] = [];
|
||||
@@ -230,6 +308,43 @@ describe('BridgeManager PID ownership', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('traces material sender selection, fallback, and no-sender drops without polling noise', async () => {
|
||||
const manager = new BridgeManager();
|
||||
const first = makeSender();
|
||||
const second = makeSender();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
manager.onHookLogin(101, '10001', first.client);
|
||||
manager.onHookLogin(202, '10001', second.client);
|
||||
manager.onPacket(packet(202, '10001'));
|
||||
manager.onPidDisconnected(202);
|
||||
const bridge = manager.getSession('10001')!.bridge;
|
||||
manager.onPidDisconnected(101);
|
||||
await bridge.sendRawPacket('Test.NoSender', new Uint8Array([0x00, 0xff]));
|
||||
|
||||
const sender = runtimeTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('bridge_sender_fact ')
|
||||
|| entry.message.startsWith('bridge_send_'));
|
||||
expect(sender.map((entry) => entry.message)).toEqual([
|
||||
'bridge_sender_fact event=selected uin="10001" pid=101 previousPid=null',
|
||||
'bridge_sender_fact event=selected uin="10001" pid=202 previousPid=101',
|
||||
'bridge_sender_fact event=fallback uin="10001" detachedPid=202 fallbackPid=101',
|
||||
'bridge_send_start serviceCmd="Test.NoSender" uin="10001" activePid=null timeoutMs=15000 length=2 body=00ff',
|
||||
expect.stringMatching(/^bridge_send_terminal serviceCmd="Test\.NoSender" uin="10001" activePid=null outcome=dropped reason=no_sender length=2 body=00ff elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(sender[2]!.req).toBe(
|
||||
runtimeTrace(entries).find((entry) =>
|
||||
entry.message.startsWith('bridge_detach_start pid=202 '))!.req,
|
||||
);
|
||||
expect(sender[3]!.req).toEqual(expect.any(Number));
|
||||
expect(sender[4]!.req).toBe(sender[3]!.req);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports an account healthy while any attached PID still receives packets', () => {
|
||||
const manager = new BridgeManager();
|
||||
manager.onHookLogin(101, '10001', makeSender().client);
|
||||
|
||||
@@ -12,6 +12,14 @@
|
||||
// - closeafter:每个响应后半关闭(readableEnded/emit close)→ 退化成每块
|
||||
// 一连接,但仍全部成功。
|
||||
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import type { HttpConn0x6FF501Response } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
@@ -41,6 +49,10 @@ function buildErrorCodeFrame(): Buffer {
|
||||
return frame;
|
||||
}
|
||||
|
||||
function buildMalformedHighwayResponseFrame(): Buffer {
|
||||
return Buffer.from([0x28, 0, 0, 0, 5, 0, 0, 0, 0, 0x08, 0x01, 0x29]);
|
||||
}
|
||||
|
||||
function httpWrap(frame: Buffer): Buffer {
|
||||
const headers = ['HTTP/1.1 200 OK', `Content-Length: ${frame.length}`, '', ''].join('\r\n');
|
||||
return Buffer.concat([Buffer.from(headers, 'ascii'), frame]);
|
||||
@@ -62,6 +74,7 @@ class FakeSocket extends EventEmitter {
|
||||
private readonly mode: ServerMode,
|
||||
private readonly failOnPost = -1,
|
||||
private readonly truncateOnPost = -1,
|
||||
private readonly errorAfterPartialOnPost = -1,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
@@ -102,6 +115,15 @@ class FakeSocket extends EventEmitter {
|
||||
this.emit('close');
|
||||
return;
|
||||
}
|
||||
if (thisPost === this.errorAfterPartialOnPost) {
|
||||
const full = httpWrap(this.responseFrame);
|
||||
this.emit('data', full.subarray(0, full.length - 3));
|
||||
this.writable = false;
|
||||
this.readableEnded = true;
|
||||
this.emit('error', new Error('ECONNRESET after partial response'));
|
||||
this.emit('close');
|
||||
return;
|
||||
}
|
||||
if (thisPost === this.truncateOnPost) {
|
||||
// Send the HTTP header + only part of the declared body, then FIN —
|
||||
// a truncated response. Dropping the last 3 body bytes keeps the
|
||||
@@ -144,6 +166,7 @@ vi.mock('net', () => ({
|
||||
}));
|
||||
|
||||
import {
|
||||
fetchHighwaySession,
|
||||
uploadHighwayHttp,
|
||||
BufferChunkSource,
|
||||
type ChunkSource,
|
||||
@@ -152,6 +175,11 @@ import {
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function highwayTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
|
||||
}
|
||||
|
||||
function makeBridge(): BridgeContext {
|
||||
return { identity: { uin: '10001' } as unknown } as unknown as BridgeContext;
|
||||
@@ -200,8 +228,272 @@ class RecordingChunkSource implements ChunkSource {
|
||||
}
|
||||
}
|
||||
|
||||
describe('fetchHighwaySession trace lifecycle', () => {
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('records session metadata without duplicating packet control bytes', async () => {
|
||||
const responseData = protobuf_encode<HttpConn0x6FF501Response>({
|
||||
httpConn: {
|
||||
sigSession: new Uint8Array([0xAA, 0xBB]),
|
||||
sessionKey: new Uint8Array([0xCC]),
|
||||
serverInfos: [{
|
||||
serviceType: 1,
|
||||
serverAddrs: [{ ip: 0x04030201, port: 8080 }],
|
||||
}],
|
||||
},
|
||||
});
|
||||
const sendRawPacket = vi.fn<
|
||||
(cmd: string, body: Uint8Array) => Promise<{
|
||||
success: boolean;
|
||||
gotResponse: boolean;
|
||||
errorCode: number;
|
||||
errorMessage: string;
|
||||
responseData: Buffer;
|
||||
}>
|
||||
>(async () => ({
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(responseData),
|
||||
}));
|
||||
const bridge = {
|
||||
identity: { uin: '10001' },
|
||||
sendRawPacket,
|
||||
} as unknown as BridgeContext;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
expect([...session.sigSession]).toEqual([0xAA, 0xBB]);
|
||||
expect([...session.sessionKey]).toEqual([0xCC]);
|
||||
expect(session.host).toBe('1.2.3.4');
|
||||
expect(session.port).toBe(8080);
|
||||
const requestBytes = sendRawPacket.mock.calls[0]![1] as Uint8Array;
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
`highway_session_start serviceCmd="HttpConn.0x6ff_501" requestBytes=${requestBytes.byteLength}`,
|
||||
expect.stringContaining(`branch=control_response success=true gotResponse=true errorCode=0 errorMessage="" responseBytes=${responseData.byteLength}`),
|
||||
expect.stringMatching(/^highway_session_terminal outcome=completed reason=session_ready host="1\.2\.3\.4" port=8080 sigBytes=2 sessionKeyBytes=1 elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.join('\n')).not.toContain('requestHex=');
|
||||
expect(messages.join('\n')).not.toContain('responseHex=');
|
||||
expect(messages.filter((message) => message.startsWith('highway_session_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records a thrown control request as one failed terminal', async () => {
|
||||
const bridge = {
|
||||
identity: { uin: '10001' },
|
||||
sendRawPacket: vi.fn(async () => { throw new Error('fixture session pipe failure'); }),
|
||||
} as unknown as BridgeContext;
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(fetchHighwaySession(bridge)).rejects.toThrow('fixture session pipe failure');
|
||||
const terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_session_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('records complete chunk control lifecycle without copying source bytes', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const sourceBytes = new Uint8Array([0xDE, 0xAD, 0xBE, 0xEF]);
|
||||
const fileMd5 = new Uint8Array([0x00, 0xFF, 0x10, 0x20]);
|
||||
const extend = new Uint8Array([0xCA, 0xFE]);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
new BufferChunkSource(sourceBytes),
|
||||
fileMd5,
|
||||
extend,
|
||||
);
|
||||
|
||||
const trace = highwayTrace(entries);
|
||||
expect(trace.every((entry) => entry.req !== undefined && entry.req === trace[0]!.req)).toBe(true);
|
||||
const messages = trace.map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('highway_put_start cmdId=1004'),
|
||||
expect.stringContaining('totalBytes=4'),
|
||||
expect.stringContaining('fileMd5=00ff1020'),
|
||||
expect.stringContaining('extendBytes=2'),
|
||||
expect.stringContaining('branch=chunk_read offset=0 bytes=4'),
|
||||
expect.stringMatching(/^highway_put_branch branch=chunk_control_request offset=0 bytes=4 headBytes=\d+ headHex=[0-9a-f]+$/),
|
||||
expect.stringContaining('branch=chunk_attempt offset=0 bytes=4 attempt=1'),
|
||||
expect.stringContaining('branch=chunk_control_response offset=0'),
|
||||
expect.stringContaining('branch=chunk_control_decoded offset=0 errorCode=0'),
|
||||
expect.stringMatching(/^highway_put_terminal cmdId=1004 outcome=completed reason=upload_complete totalBytes=4 uploadedBytes=4 connections=1 elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.join('\n')).not.toContain('deadbeef');
|
||||
expect(messages.filter((message) => message.startsWith('highway_put_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records reconnect at the same offset and one successful terminal', async () => {
|
||||
installFactory((idx) => idx === 0
|
||||
? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', 1)
|
||||
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
new BufferChunkSource(new Uint8Array([1, 2, 3])),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(0),
|
||||
);
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('branch=chunk_retry offset=0 bytes=3 attempt=1'),
|
||||
expect.stringContaining('branch=reconnect offset=0 attempt=2 connection=2'),
|
||||
expect.stringContaining('outcome=completed reason=upload_complete'),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('highway_put_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records definitive server rejection as one failed terminal', async () => {
|
||||
installFactory(() => new FakeSocket(buildErrorCodeFrame(), 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(),
|
||||
makeSession(),
|
||||
1004,
|
||||
new BufferChunkSource(new Uint8Array([1])),
|
||||
new Uint8Array(16),
|
||||
new Uint8Array(0),
|
||||
)).rejects.toThrow(/error_code=921/);
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('branch=chunk_control_response offset=0'),
|
||||
expect.stringContaining('errorCode=921'),
|
||||
expect.stringContaining('outcome=failed reason=server_rejected'),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('highway_put_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records malformed control bytes before the decode failure terminal', async () => {
|
||||
const malformed = buildMalformedHighwayResponseFrame();
|
||||
installFactory(() => new FakeSocket(malformed, 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array([1])),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow();
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toContainEqual(expect.stringContaining(
|
||||
`responseBytes=${malformed.byteLength} responseHex=${malformed.toString('hex')}`,
|
||||
));
|
||||
const terminals = messages.filter((message) => message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]).toContain('outcome=failed reason=control_decode_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records transport exhaustion after exactly three attempts', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', 1));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array([1])),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow(/transport failed after 3 attempts/);
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages.filter((message) => message.includes('branch=chunk_attempt offset=0'))).toHaveLength(3);
|
||||
expect(messages.filter((message) => message.includes('branch=chunk_retry offset=0'))).toHaveLength(2);
|
||||
const terminals = messages.filter((message) => message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]).toContain('outcome=failed reason=transport_exhausted');
|
||||
expect(terminals[0]).toContain('connections=3');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records source read and close failures with truthful unique terminals', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
const readFailure: ChunkSource = {
|
||||
size: 1,
|
||||
read: vi.fn(async () => { throw new Error('fixture read failed'); }),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, readFailure,
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow('fixture read failed');
|
||||
let terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=source_read_failed');
|
||||
|
||||
entries.length = 0;
|
||||
const closeFailure: ChunkSource = {
|
||||
size: 0,
|
||||
read: vi.fn(async () => new Uint8Array(0)),
|
||||
close: vi.fn(async () => { throw new Error('fixture close failed'); }),
|
||||
};
|
||||
await expect(uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, closeFailure,
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
)).rejects.toThrow('fixture close failed');
|
||||
terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_put_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=source_close_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
it('reuses ONE connection for a multi-block payload when keep-alive holds', async () => {
|
||||
installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'));
|
||||
@@ -258,22 +550,87 @@ describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => {
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('reconnects and re-sends the block when a response body is truncated mid-stream', async () => {
|
||||
it('reconnects and preserves partial control-response bytes when a body is truncated', async () => {
|
||||
// Peer FINs after the HTTP header but before the highway body is complete.
|
||||
// That truncation must be treated as a retryable transport failure (reject
|
||||
// in readHttpResponseBody), NOT resolved as a partial frame — otherwise
|
||||
// unpackHighwayFrame throws OUTSIDE the retry loop and fails the upload.
|
||||
const frame = buildEmptyHighwayResponseFrame();
|
||||
installFactory((idx) =>
|
||||
idx === 0
|
||||
? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', -1, /* truncateOnPost */ 1)
|
||||
: new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'),
|
||||
? new FakeSocket(frame, 'keepalive', -1, /* truncateOnPost */ 1)
|
||||
: new FakeSocket(frame, 'keepalive'),
|
||||
);
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
// conn #0 truncated block 0 → reconnect (#1) re-sends it and finishes.
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
const partial = frame.subarray(0, frame.length - 3);
|
||||
expect(highwayTrace(entries).map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
`branch=chunk_control_response_partial offset=0 attempt=1 responseBytes=${partial.byteLength} responseHex=${partial.toString('hex')}`,
|
||||
),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reconnects and preserves partial control-response bytes when the socket errors', async () => {
|
||||
const frame = buildEmptyHighwayResponseFrame();
|
||||
installFactory((idx) =>
|
||||
idx === 0
|
||||
? new FakeSocket(frame, 'keepalive', -1, -1, 1)
|
||||
: new FakeSocket(frame, 'keepalive'),
|
||||
);
|
||||
// conn #0 truncated block 0 → reconnect (#1) re-sends it and finishes.
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE))),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
const partial = frame.subarray(0, frame.length - 3);
|
||||
expect(highwayTrace(entries).map((entry) => entry.message)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(
|
||||
`branch=chunk_control_response_partial offset=0 attempt=1 responseBytes=${partial.byteLength} responseHex=${partial.toString('hex')}`,
|
||||
),
|
||||
]));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not preserve diagnostic response copies while TRACE is disabled', async () => {
|
||||
const frame = buildEmptyHighwayResponseFrame();
|
||||
installFactory((idx) =>
|
||||
idx === 0
|
||||
? new FakeSocket(frame, 'keepalive', -1, -1, 1)
|
||||
: new FakeSocket(frame, 'keepalive'),
|
||||
);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('info');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004,
|
||||
new BufferChunkSource(new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE))),
|
||||
new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
expect(highwayTrace(entries)).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reads every offset exactly once, in order, and closes the source once (data safety)', async () => {
|
||||
|
||||
@@ -5,8 +5,14 @@
|
||||
// The OIDB response is built with real protobuf encoding so we exercise
|
||||
// the actual decode path inside the pipeline.
|
||||
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
@@ -28,6 +34,12 @@ import {
|
||||
type MediaSubFileUpload,
|
||||
} from '@snowluma/protocol/highway/pipeline';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function highwayTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter((entry) => entry.level === 'trace' && entry.scope === 'Highway');
|
||||
}
|
||||
|
||||
interface FakeUploadResponse {
|
||||
upload?: {
|
||||
uKey?: string;
|
||||
@@ -108,6 +120,122 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
vi.mocked(highway.buildHighwayExtend).mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
it('records fast-upload selection and one completed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } },
|
||||
}),
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await runNtv2Upload(baseParams({
|
||||
bridge,
|
||||
label: 'image',
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1003,
|
||||
bytes: new Uint8Array([0xDE, 0xAD]),
|
||||
md5: new Uint8Array([0x00, 0xFF]),
|
||||
sha1: new Uint8Array([0x10, 0x20]),
|
||||
}],
|
||||
}));
|
||||
const trace = highwayTrace(entries);
|
||||
expect(trace.every((entry) => entry.req !== undefined && entry.req === trace[0]!.req)).toBe(true);
|
||||
const messages = trace.map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^highway_media_start label="image" .*businessType=1 .*source:"top",cmdId:1003,size:2,storage:"buffer",md5:00ff,sha1:\[1020\]/),
|
||||
expect.stringContaining('branch=fast_upload'),
|
||||
expect.stringMatching(/^highway_media_terminal label="image" outcome=completed reason=fast_upload .*elapsedMs=\d+$/),
|
||||
]));
|
||||
expect(messages.join('\n')).not.toContain('dead');
|
||||
expect(messages.filter((message) => message.startsWith('highway_media_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records required PUT and one failed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
upload: {
|
||||
uKey: 'ukey-secret',
|
||||
msgInfo: { msgInfoBody: [], extBizInfo: {} },
|
||||
},
|
||||
}),
|
||||
});
|
||||
vi.mocked(highway.uploadHighwayHttp).mockRejectedValueOnce(
|
||||
new Error('fixture PUT failed'),
|
||||
);
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({
|
||||
bridge,
|
||||
label: 'video',
|
||||
uploads: [{
|
||||
source: 'top',
|
||||
cmdId: 1001,
|
||||
bytes: new Uint8Array([1]),
|
||||
md5: new Uint8Array([2]),
|
||||
sha1: new Uint8Array([3]),
|
||||
}],
|
||||
}))).rejects.toThrow('fixture PUT failed');
|
||||
const messages = highwayTrace(entries).map((entry) => entry.message);
|
||||
expect(messages).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('branch=put_required source="top" cmdId=1001 size=1'),
|
||||
expect.stringContaining('uKey="ukey-secret"'),
|
||||
expect.stringContaining('outcome=failed reason=put_failed'),
|
||||
]));
|
||||
expect(messages.filter((message) => message.startsWith('highway_media_terminal '))).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records OIDB rejection as one failed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({}, { errorCode: 42, errorMsg: 'boom' }),
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
|
||||
.rejects.toThrow('OIDB error 42');
|
||||
const terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_media_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=oidb_rejected');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies a thrown OIDB transport call as request_failed', async () => {
|
||||
const bridge = makeBridge();
|
||||
bridge.sendRawPacket.mockRejectedValueOnce(new Error('fixture OIDB pipe failure'));
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
|
||||
.rejects.toThrow('fixture OIDB pipe failure');
|
||||
const terminals = highwayTrace(entries)
|
||||
.filter((entry) => entry.message.startsWith('highway_media_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=request_failed');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('builds an NTV2 request body and dispatches to the configured serviceCmd', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({ upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } } }),
|
||||
@@ -155,6 +283,25 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
expect(upload.msgInfo?.msgInfoBody).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('rejects a successful envelope that is missing msgInfo with one failed terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({ upload: { uKey: 'fake-ukey' } }),
|
||||
});
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
try {
|
||||
await expect(runNtv2Upload(baseParams({ bridge, label: 'image' })))
|
||||
.rejects.toThrow(/upload response missing msgInfo/);
|
||||
const terminals = highwayTrace(entries).filter((entry) =>
|
||||
entry.message.startsWith('highway_media_terminal '));
|
||||
expect(terminals).toHaveLength(1);
|
||||
expect(terminals[0]!.message).toContain('outcome=failed reason=response_invalid');
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('throws on transport failure', async () => {
|
||||
const bridge = makeBridge({ success: false, errorMessage: 'pipe broken', responseData: null });
|
||||
await expect(runNtv2Upload(baseParams({ bridge })))
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { StateBus } from '../src/webui/state-bus';
|
||||
import { startConnectionDiffLoop } from '../src/webui/connection-diff-loop';
|
||||
import { comparableConnectionSnapshot } from '../src/webui/connection-snapshot';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
describe('startConnectionDiffLoop', () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('does NOT publish when the snapshot is stable tick after tick', () => {
|
||||
const bus = new StateBus();
|
||||
@@ -22,6 +33,108 @@ describe('startConnectionDiffLoop', () => {
|
||||
handle.dispose();
|
||||
});
|
||||
|
||||
it('traces only changed snapshot publication under one semantic context', () => {
|
||||
const bus = new StateBus();
|
||||
const entries: LogEntry[] = [];
|
||||
let snap: unknown = [{ uin: '1', adapters: [] }];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => snap,
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(500);
|
||||
vi.advanceTimersByTime(1_500);
|
||||
expect(entries.filter((entry) => entry.scope === 'WebUI.Connections')).toEqual([]);
|
||||
|
||||
snap = [{ uin: '1', adapters: [{ kind: 'ws', status: 'connected' }] }];
|
||||
vi.advanceTimersByTime(500);
|
||||
vi.advanceTimersByTime(1_000);
|
||||
|
||||
const trace = entries.filter((entry) =>
|
||||
entry.level === 'trace' && entry.scope === 'WebUI.Connections');
|
||||
expect(trace.map((entry) => entry.message)).toEqual([
|
||||
'connection_diff_start snapshot=[{uin:"1",adapters:[{kind:"ws",status:"connected"}]}]',
|
||||
'connection_diff_branch branch=publish resource=connections',
|
||||
expect.stringMatching(/^connection_diff_terminal outcome=completed reason=published elapsedMs=\d+$/),
|
||||
]);
|
||||
expect(trace.map((entry) => entry.req)).toEqual([
|
||||
expect.any(Number),
|
||||
trace[0]!.req,
|
||||
trace[0]!.req,
|
||||
]);
|
||||
} finally {
|
||||
handle.dispose();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('routes snapshot and projector failures through the common logger without repeated noise', () => {
|
||||
const bus = new StateBus();
|
||||
const entries: LogEntry[] = [];
|
||||
const getSnapshot = vi.fn(() => { throw new Error('snapshot boom'); });
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const snapshotHandle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot,
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(2_000);
|
||||
expect(entries.filter((entry) =>
|
||||
entry.scope === 'WebUI.Connections'
|
||||
&& entry.message.includes('reason=snapshot_failed'))).toHaveLength(1);
|
||||
} finally {
|
||||
snapshotHandle.dispose();
|
||||
}
|
||||
|
||||
const projectorHandle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => [{ uin: '1' }],
|
||||
pickComparable: () => { throw new Error('projector boom'); },
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(2_000);
|
||||
const failures = entries.filter((entry) =>
|
||||
entry.scope === 'WebUI.Connections'
|
||||
&& entry.message.includes('reason=projector_failed'));
|
||||
expect(failures).toHaveLength(1);
|
||||
expect(failures[0]!.message).toMatch(
|
||||
/^connection_diff_terminal outcome=failed reason=projector_failed error="projector boom" elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
projectorHandle.dispose();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps one-shot projector failures visible when TRACE is disabled', () => {
|
||||
const bus = new StateBus();
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('info');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const handle = startConnectionDiffLoop({
|
||||
bus,
|
||||
getSnapshot: () => [{ uin: '1' }],
|
||||
pickComparable: () => { throw new Error('projector boom'); },
|
||||
intervalMs: 500,
|
||||
});
|
||||
try {
|
||||
vi.advanceTimersByTime(2_000);
|
||||
expect(entries.filter((entry) =>
|
||||
entry.level === 'error'
|
||||
&& entry.scope === 'WebUI.Connections'
|
||||
&& entry.message.includes('projector boom'))).toHaveLength(1);
|
||||
} finally {
|
||||
handle.dispose();
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('first tick baselines the snapshot (no publish); only the second tick with a different value publishes', () => {
|
||||
const bus = new StateBus();
|
||||
const seen: string[] = [];
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
import {
|
||||
getLogLevel,
|
||||
setLogLevel,
|
||||
subscribeLogs,
|
||||
type LogEntry,
|
||||
} from '@snowluma/common/logger';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { traceAuthenticatedWebuiMutation } from '../src/webui/mutation-trace';
|
||||
|
||||
const previousLogLevel = getLogLevel();
|
||||
|
||||
function mutationTrace(entries: LogEntry[]): LogEntry[] {
|
||||
return entries.filter(
|
||||
(entry) => entry.level === 'trace' && entry.scope === 'WebUI.Mutation',
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForTerminal(entries: LogEntry[]): Promise<LogEntry[]> {
|
||||
await vi.waitFor(() => {
|
||||
expect(mutationTrace(entries).some(
|
||||
(entry) => entry.message.startsWith('webui_mutation_terminal '),
|
||||
)).toBe(true);
|
||||
});
|
||||
return mutationTrace(entries);
|
||||
}
|
||||
|
||||
describe('traceAuthenticatedWebuiMutation', () => {
|
||||
afterEach(() => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
it('traces a successful JSON write with complete request and response data', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const requestBody = '{"logLevel":"trace"}';
|
||||
const responseBody = '{"success":true}';
|
||||
const request = new Request('http://127.0.0.1/api/system/settings?source=test', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: 'Bearer exact-token',
|
||||
'content-type': 'application/json',
|
||||
'x-request-detail': 'complete',
|
||||
},
|
||||
body: requestBody,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(request, async () => new Response(
|
||||
responseBody,
|
||||
{
|
||||
status: 201,
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'x-response-detail': 'complete',
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(await response.text()).toBe(responseBody);
|
||||
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace).toHaveLength(4);
|
||||
expect(trace[0]!.message).toContain('webui_mutation_start method="POST"');
|
||||
expect(trace[0]!.message).toContain(
|
||||
'url="http://127.0.0.1/api/system/settings?source=test"',
|
||||
);
|
||||
expect(trace[0]!.message).toContain('authorization');
|
||||
expect(trace[0]!.message).toContain('Bearer exact-token');
|
||||
expect(trace[0]!.message).toContain('x-request-detail');
|
||||
expect(trace[1]!.message).toContain('branch=request_body');
|
||||
expect(trace[1]!.message).toContain(`text=${JSON.stringify(requestBody)}`);
|
||||
expect(trace[1]!.message).toContain(
|
||||
`body=${Buffer.from(requestBody).toString('hex')}`,
|
||||
);
|
||||
expect(trace[2]!.message).toContain('branch=response status=201');
|
||||
expect(trace[2]!.message).toContain('x-response-detail');
|
||||
expect(trace[2]!.message).toContain(`text=${JSON.stringify(responseBody)}`);
|
||||
expect(trace[2]!.message).toContain(
|
||||
`body=${Buffer.from(responseBody).toString('hex')}`,
|
||||
);
|
||||
expect(trace[3]!.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=completed reason=response_completed status=201 elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.every((entry) => entry.req === trace[0]!.req)).toBe(true);
|
||||
expect(trace[0]!.req).toEqual(expect.any(Number));
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('traces non-2xx and binary bodies without consuming the response', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const requestBytes = Uint8Array.from([0x00, 0xff, 0x80, 0x41]);
|
||||
const responseBytes = Uint8Array.from([0xde, 0xad, 0xbe, 0xef, 0x00]);
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/system/backup/import', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
body: requestBytes,
|
||||
}),
|
||||
async () => new Response(responseBytes, {
|
||||
status: 422,
|
||||
headers: { 'content-type': 'application/octet-stream' },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(new Uint8Array(await response.arrayBuffer())).toEqual(responseBytes);
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.find((entry) => entry.message.includes('branch=request_body'))?.message)
|
||||
.toContain('length=4');
|
||||
expect(trace.find((entry) => entry.message.includes('branch=request_body'))?.message)
|
||||
.toContain('body=00ff8041');
|
||||
expect(trace.find((entry) => entry.message.includes('branch=response'))?.message)
|
||||
.toContain('body=deadbeef00');
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=http_status status=422 elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.filter((entry) => entry.message.startsWith('webui_mutation_terminal ')))
|
||||
.toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('traces a thrown handler with one failed terminal and preserves the error', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const failure = new Error('write exploded');
|
||||
|
||||
try {
|
||||
await expect(traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/global-config', {
|
||||
method: 'POST',
|
||||
body: 'complete request',
|
||||
}),
|
||||
async () => { throw failure; },
|
||||
)).rejects.toBe(failure);
|
||||
|
||||
const trace = mutationTrace(entries);
|
||||
expect(trace.some((entry) =>
|
||||
entry.message.includes('branch=request_body')
|
||||
&& entry.message.includes('body=636f6d706c6574652072657175657374'))).toBe(true);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=handler_threw error="write exploded" elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.filter((entry) => entry.message.startsWith('webui_mutation_terminal ')))
|
||||
.toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('classifies handler cancellation and timeout from their error provenance', async () => {
|
||||
setLogLevel('trace');
|
||||
|
||||
for (const [name, outcome, reason] of [
|
||||
['AbortError', 'cancelled', 'handler_cancelled'],
|
||||
['TimeoutError', 'timeout', 'handler_timeout'],
|
||||
] as const) {
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const failure = new DOMException(`${name} detail`, name);
|
||||
try {
|
||||
await expect(traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/processes/42/load', { method: 'POST' }),
|
||||
async () => { throw failure; },
|
||||
)).rejects.toBe(failure);
|
||||
expect(mutationTrace(entries).at(-1)?.message).toMatch(
|
||||
new RegExp(`^webui_mutation_terminal outcome=${outcome} reason=${reason} error="${name} detail" elapsedMs=\\d+$`),
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('bypasses cloning and logging when TRACE is disabled', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('info');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request('http://127.0.0.1/api/system/settings', {
|
||||
method: 'POST',
|
||||
body: 'must remain unread',
|
||||
});
|
||||
const clone = vi.spyOn(request, 'clone');
|
||||
const next = vi.fn(async () => new Response('ok'));
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(request, next);
|
||||
expect(await response.text()).toBe('ok');
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect(clone).not.toHaveBeenCalled();
|
||||
expect(entries).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not clone the streamed upload request body', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request('http://127.0.0.1/api/debug/upload?filename=large.bin', {
|
||||
method: 'POST',
|
||||
body: Uint8Array.from([0x00, 0xff]),
|
||||
});
|
||||
const clone = vi.spyOn(request, 'clone');
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
request,
|
||||
async () => new Response('{"status":"ok"}', {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
expect(await response.json()).toEqual({ status: 'ok' });
|
||||
expect(clone).not.toHaveBeenCalled();
|
||||
await waitForTerminal(entries);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports an aborted streamed upload as cancelled even when the route returns 400', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const abort = new AbortController();
|
||||
const request = new Request('http://127.0.0.1/api/debug/upload?filename=cancelled.bin', {
|
||||
method: 'POST',
|
||||
body: Uint8Array.from([0x01]),
|
||||
signal: abort.signal,
|
||||
});
|
||||
|
||||
try {
|
||||
abort.abort();
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
request,
|
||||
async () => new Response('{"status":"failed"}', { status: 400 }),
|
||||
);
|
||||
expect(response.status).toBe(400);
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=cancelled reason=request_cancelled status=400 elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a non-abort streamed upload rejection as an HTTP failure', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request('http://127.0.0.1/api/debug/upload?filename=too-large.bin', {
|
||||
method: 'POST',
|
||||
body: Uint8Array.from([0x01]),
|
||||
});
|
||||
|
||||
try {
|
||||
await traceAuthenticatedWebuiMutation(
|
||||
request,
|
||||
async () => new Response('{"status":"failed"}', { status: 400 }),
|
||||
);
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=http_status status=400 elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not pull a streaming response ahead of the client', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
let pulls = 0;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
pull(controller) {
|
||||
pulls += 1;
|
||||
controller.enqueue(Uint8Array.from([pulls]));
|
||||
if (pulls === 2) controller.close();
|
||||
},
|
||||
}, { highWaterMark: 0 });
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/debug/invoke-stream', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
async () => new Response(stream),
|
||||
);
|
||||
|
||||
await Promise.resolve();
|
||||
expect(pulls).toBe(0);
|
||||
expect(new Uint8Array(await response.arrayBuffer()))
|
||||
.toEqual(Uint8Array.from([0x01, 0x02]));
|
||||
await waitForTerminal(entries);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('returns a streaming response before its body completes and traces completion later', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
let controller!: ReadableStreamDefaultController<Uint8Array>;
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(value) {
|
||||
controller = value;
|
||||
value.enqueue(Uint8Array.from([0x01, 0x02]));
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/debug/invoke-stream', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
async () => new Response(stream, { status: 200 }),
|
||||
);
|
||||
|
||||
expect(response.body).not.toBeNull();
|
||||
expect(mutationTrace(entries).some(
|
||||
(entry) => entry.message.startsWith('webui_mutation_terminal '),
|
||||
)).toBe(false);
|
||||
|
||||
controller.enqueue(Uint8Array.from([0x03, 0x04]));
|
||||
controller.close();
|
||||
expect(new Uint8Array(await response.arrayBuffer()))
|
||||
.toEqual(Uint8Array.from([0x01, 0x02, 0x03, 0x04]));
|
||||
|
||||
const trace = await waitForTerminal(entries);
|
||||
const responseChunks = trace.filter((entry) =>
|
||||
entry.message.includes('branch=response_chunk'));
|
||||
expect(responseChunks.map((entry) => entry.message)).toEqual([
|
||||
'webui_mutation_branch branch=response_chunk offset=0 length=2 body=0102',
|
||||
'webui_mutation_branch branch=response_chunk offset=2 length=2 body=0304',
|
||||
]);
|
||||
expect(trace.every((entry) => entry.req === trace[0]!.req)).toBe(true);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=completed reason=response_completed status=200 elapsedMs=\d+$/,
|
||||
);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('records one failed terminal when the traced response body cannot be read', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const streamFailure = new Error('response stream exploded');
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(Uint8Array.from([0xaa]));
|
||||
controller.error(streamFailure);
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await traceAuthenticatedWebuiMutation(
|
||||
new Request('http://127.0.0.1/api/debug/invoke-stream', {
|
||||
method: 'POST',
|
||||
body: '{}',
|
||||
}),
|
||||
async () => new Response(stream),
|
||||
);
|
||||
await expect(response.arrayBuffer()).rejects.toBe(streamFailure);
|
||||
|
||||
const trace = await waitForTerminal(entries);
|
||||
expect(trace.some((entry) =>
|
||||
entry.message.includes('branch=request_body')
|
||||
&& entry.message.includes('body=7b7d'))).toBe(true);
|
||||
expect(trace.at(-1)?.message).toMatch(
|
||||
/^webui_mutation_terminal outcome=failed reason=body_read_failed status=200 error="response stream exploded" elapsedMs=\d+$/,
|
||||
);
|
||||
expect(trace.filter((entry) => entry.message.startsWith('webui_mutation_terminal ')))
|
||||
.toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
['GET', '/api/config/12345'],
|
||||
['HEAD', '/api/config/12345'],
|
||||
['OPTIONS', '/api/config/12345'],
|
||||
['POST', '/api/auth/check-strength'],
|
||||
['POST', '/api/logs/level'],
|
||||
])('keeps %s %s outside mutation TRACE', async (method, pathname) => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const request = new Request(`http://127.0.0.1${pathname}`, { method });
|
||||
const clone = vi.spyOn(request, 'clone');
|
||||
|
||||
try {
|
||||
await traceAuthenticatedWebuiMutation(request, async () => new Response(null, { status: 204 }));
|
||||
expect(clone).not.toHaveBeenCalled();
|
||||
expect(mutationTrace(entries)).toEqual([]);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user