/** * Records local server traffic under `/logs//`. * `requests.jsonl` stores one record per HTTP exchange or raw connection. `bodies/` holds the * payloads and readable versions of decoded BLK bodies. Each exchange also produces a console line. */ import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs'; import type { IncomingHttpHeaders } from 'node:http'; import { join } from 'node:path'; import type { ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; import type { FirstBytesInfo } from './first-bytes.ts'; export interface MatchingLogEntry { readonly direction: 'in' | 'out'; /** First byte of the message (0x1a request, 0x1b answer, other: notification). */ readonly kind: number; readonly summary: string; readonly unhandled: boolean; readonly text: string; } export class TrafficLog { readonly folder: string; readonly #linesPath: string; readonly #bodiesFolder: string; #sequence = 0; constructor(dataFolder: string) { this.folder = join(dataFolder, 'logs', new Date().toISOString().replace(/[:.]/g, '-')); this.#linesPath = join(this.folder, 'requests.jsonl'); this.#bodiesFolder = join(this.folder, 'bodies'); mkdirSync(this.#bodiesFolder, { recursive: true }); } exchange(request: ServiceRequest, service: string, response: ServiceResponse, connectionId: number): void { const id = this.#next(); const notes = response.logNotes ?? {}; const files = { request: this.#writeBody(id, 'req.bin', notes.redactedRequestBody ?? request.body), requestText: this.#writeBody(id, 'req.txt', notes.requestText), response: notes.omitResponseBody ? null : this.#writeBody(id, 'resp.bin', response.body), responseText: this.#writeBody(id, 'resp.txt', notes.responseText), }; this.#append({ id, time: new Date().toISOString(), kind: 'http', connection: connectionId, method: request.method, host: request.originalHost ?? null, path: request.path, query: request.query.toString(), headers: plainHeaders(request.headers), requestBytes: request.body.length, service, summary: notes.summary ?? null, unhandled: notes.unhandled ?? false, status: response.status, responseBytes: byteLength(response.body), files, }); const flag = notes.unhandled ? ' [UNHANDLED]' : ''; console.log(`#${id} ${request.method} ${request.originalHost ?? '(no host)'}${request.path} -> ${service}` + `${notes.summary ? ` ${notes.summary}` : ''} = ${response.status}${flag}`); } connectionOpened(connectionId: number, remotePort: number | undefined): void { this.#append({ id: this.#next(), time: new Date().toISOString(), kind: 'connection-open', connection: connectionId, remotePort: remotePort ?? null }); } connectionClosed(connectionId: number, bytesRead: number, bytesWritten: number): void { this.#append({ id: this.#next(), time: new Date().toISOString(), kind: 'connection-close', connection: connectionId, bytesRead, bytesWritten }); } nonHttpConnection(connectionId: number, info: FirstBytesInfo, error: string): void { const id = this.#next(); const { kind, ...details } = info; this.#append({ id, time: new Date().toISOString(), kind: `non-http-${kind}`, connection: connectionId, ...details, parserError: error }); console.log(`#${id} non-HTTP connection (${info.kind}${info.serverName ? `, asks for ${info.serverName}` : ''}): ${info.textHead}`); } /** One message of the matching protocol; the text is already redacted by the sender. */ matchingMessage(connectionId: number, entry: MatchingLogEntry): void { const id = this.#next(); const text = this.#writeBody(id, `matching-${entry.direction}.json`, entry.text); this.#append({ id, time: new Date().toISOString(), kind: 'matching', connection: connectionId, direction: entry.direction, messageKind: entry.kind, summary: entry.summary, unhandled: entry.unhandled, files: { text } }); const flag = entry.unhandled ? ' [UNHANDLED]' : ''; console.log(`#${id} matching ${entry.direction === 'in' ? '<-' : '->'} ${entry.summary}${flag}`); } matchingError(connectionId: number, message: string): void { const id = this.#next(); this.#append({ id, time: new Date().toISOString(), kind: 'matching-error', connection: connectionId, message }); console.log(`#${id} matching connection ${connectionId} closed: ${message}`); } webSocket(connectionId: number, request: ServiceRequest): void { const id = this.#next(); this.#append({ id, time: new Date().toISOString(), kind: 'websocket', connection: connectionId, host: request.originalHost ?? null, path: request.path, query: request.query.toString(), headers: plainHeaders(request.headers) }); console.log(`#${id} WebSocket ${request.originalHost ?? '(no host)'}${request.path} (refused)`); } #next(): number { this.#sequence += 1; return this.#sequence; } #append(line: object): void { appendFileSync(this.#linesPath, JSON.stringify(line) + '\n'); } #writeBody(id: number, suffix: string, content: Uint8Array | string | undefined): string | null { if (content === undefined || byteLength(content) === 0) return null; const name = `${String(id).padStart(6, '0')}.${suffix}`; writeFileSync(join(this.#bodiesFolder, name), content); return name; } } function byteLength(body: Uint8Array | string | undefined): number { if (body === undefined) return 0; return typeof body === 'string' ? Buffer.byteLength(body) : body.length; } function plainHeaders(headers: IncomingHttpHeaders): Record { const result: Record = {}; for (const [name, value] of Object.entries(headers)) { if (value !== undefined) result[name] = Array.isArray(value) ? value.join(', ') : value; } return result; }