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

+274 -48
View File
@@ -8,7 +8,12 @@ import type {
ReqDataHighwayHead,
RespDataHighwayHead,
} from '@snowluma/proto-defs/highway';
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
getLogLevel,
renderTraceBytes,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import net from 'net';
import { promises as fsp } from 'fs';
@@ -52,47 +57,109 @@ function ipv4ToString(value: number): string {
return `${value & 0xFF}.${(value >> 8) & 0xFF}.${(value >> 16) & 0xFF}.${(value >> 24) & 0xFF}`;
}
export async function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
const request = protobuf_encode<HttpConn0x6FF501Request>({
httpConn: {
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
serviceTypes: [1, 5, 10, 21],
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
},
});
type HighwayPutFailureReason =
| 'control_decode_failed'
| 'server_rejected'
| 'source_close_failed'
| 'source_read_failed'
| 'transport_exhausted';
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'HttpConn request failed');
interface HighwayPutTraceState {
startedAt: number;
uploadedBytes: number;
connectCount: number;
failureReason?: HighwayPutFailureReason;
error?: unknown;
}
class HighwayResponseReadError extends Error {
constructor(message: string, readonly responseBody?: Uint8Array) {
super(message);
this.name = 'HighwayResponseReadError';
}
}
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
throw new Error('HttpConn response missing sig_session');
}
function highwayErrorText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
const session: HighwaySession = {
sigSession: resp.httpConn.sigSession as Uint8Array,
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
host: 'htdata3.qq.com',
port: 80,
};
export function fetchHighwaySession(bridge: BridgeContext): Promise<HighwaySession> {
const startedAt = Date.now();
return runWithTraceRequest(async () => {
const request = protobuf_encode<HttpConn0x6FF501Request>({
httpConn: {
field1: 0, field2: 0, field3: 16, field4: 1, field6: 3,
serviceTypes: [1, 5, 10, 21],
field9: 2, field10: 9, field11: 8, ver: '1.0.1',
},
});
log.trace(
'highway_session_start serviceCmd=%j requestBytes=%d',
'HttpConn.0x6ff_501',
request.byteLength,
);
for (const si of resp.httpConn.serverInfos ?? []) {
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
for (const addr of si.serverAddrs) {
const ip = addr.ip ?? 0;
const port = addr.port ?? 0;
if (ip && port) {
session.host = ipv4ToString(ip);
session.port = port;
let failureReason = 'request_failed';
try {
const result = await bridge.sendRawPacket('HttpConn.0x6ff_501', request);
log.trace(
'highway_session_branch branch=control_response success=%s gotResponse=%s errorCode=%d errorMessage=%j responseBytes=%d',
result.success,
result.gotResponse,
result.errorCode,
result.errorMessage ?? '',
result.responseData?.byteLength ?? 0,
);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || 'HttpConn request failed');
}
}
}
log.trace('session %s:%d sig=%dB', session.host, session.port, (session.sigSession as Uint8Array).length);
return session;
failureReason = 'response_decode_failed';
const resp = protobuf_decode<HttpConn0x6FF501Response>(result.responseData);
failureReason = 'response_invalid';
if (!resp?.httpConn) throw new Error('HttpConn response body missing');
if (!resp.httpConn.sigSession || (resp.httpConn.sigSession as Uint8Array).length === 0) {
throw new Error('HttpConn response missing sig_session');
}
const session: HighwaySession = {
sigSession: resp.httpConn.sigSession as Uint8Array,
sessionKey: (resp.httpConn.sessionKey as Uint8Array) ?? new Uint8Array(0),
host: 'htdata3.qq.com',
port: 80,
};
for (const si of resp.httpConn.serverInfos ?? []) {
if ((si.serviceType ?? 0) !== 1 || !si.serverAddrs?.length) continue;
for (const addr of si.serverAddrs) {
const ip = addr.ip ?? 0;
const port = addr.port ?? 0;
if (ip && port) {
session.host = ipv4ToString(ip);
session.port = port;
}
}
}
log.trace(
'highway_session_terminal outcome=completed reason=session_ready host=%j port=%d sigBytes=%d sessionKeyBytes=%d elapsedMs=%d',
session.host,
session.port,
session.sigSession.byteLength,
session.sessionKey.byteLength,
Date.now() - startedAt,
);
return session;
} catch (error) {
log.trace(() => [
'highway_session_terminal outcome=failed reason=%s error=%j elapsedMs=%d',
failureReason,
highwayErrorText(error),
Date.now() - startedAt,
]);
throw error;
}
});
}
function makeHighwayHead(
@@ -192,12 +259,21 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
let totalNeeded = 0;
let settled = false;
const partialResponseBody = (): Uint8Array | undefined => {
if (headerEnd < 0 || getLogLevel() !== 'trace') return undefined;
const buf = Buffer.concat(chunks);
return new Uint8Array(buf.subarray(headerEnd));
};
// Reset on every inbound chunk; fire if the peer goes silent mid-response.
let idleTimer: ReturnType<typeof setTimeout> | null = null;
const armIdle = () => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(
() => finish(() => reject(new Error('highway response read timeout (peer idle)'))),
() => finish(() => reject(new HighwayResponseReadError(
'highway response read timeout (peer idle)',
partialResponseBody(),
))),
HIGHWAY_READ_IDLE_MS,
);
};
@@ -232,7 +308,12 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))));
}
};
const onError = (err: Error) => finish(() => reject(err));
const onError = (err: Error) => finish(() => {
const responseBody = partialResponseBody();
reject(responseBody === undefined
? err
: new HighwayResponseReadError(err.message, responseBody));
});
const onClose = () => finish(() => {
const buf = Buffer.concat(chunks);
// A fully-received body would already have resolved in onData; reaching
@@ -251,9 +332,12 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
if (headerEnd >= 0 && contentLength === 0) {
resolve(new Uint8Array(buf.subarray(headerEnd)));
} else {
reject(new Error(
reject(new HighwayResponseReadError(
`connection closed before full response (received=${buf.length}B, ` +
`headerSeen=${headerEnd >= 0}${headerEnd >= 0 ? `, need=${totalNeeded}` : ''})`,
headerEnd >= 0 && getLogLevel() === 'trace'
? new Uint8Array(buf.subarray(headerEnd))
: undefined,
));
}
});
@@ -332,9 +416,64 @@ export class FileChunkSource implements ChunkSource {
close(): Promise<void> { return this.fh.close(); }
}
export async function uploadHighwayHttp(
export function uploadHighwayHttp(
bridge: BridgeContext, session: HighwaySession, commandId: number,
source: ChunkSource, fileMd5: Uint8Array, extend: Uint8Array,
): Promise<void> {
const state: HighwayPutTraceState = {
startedAt: Date.now(),
uploadedBytes: 0,
connectCount: 0,
};
return runWithTraceRequest(async () => {
log.trace(() => [
'highway_put_start cmdId=%d uin=%j host=%j port=%d totalBytes=%d fileMd5=%s extendBytes=%d',
commandId,
bridge.identity.uin,
session.host,
session.port,
source.size,
renderTraceBytes(fileMd5),
extend.byteLength,
]);
try {
await uploadHighwayHttpOperation(
bridge,
session,
commandId,
source,
fileMd5,
extend,
state,
);
log.trace(
'highway_put_terminal cmdId=%d outcome=completed reason=upload_complete totalBytes=%d uploadedBytes=%d connections=%d elapsedMs=%d',
commandId,
source.size,
state.uploadedBytes,
state.connectCount,
Date.now() - state.startedAt,
);
} catch (error) {
log.trace(() => [
'highway_put_terminal cmdId=%d outcome=failed reason=%s totalBytes=%d uploadedBytes=%d connections=%d error=%j elapsedMs=%d',
commandId,
state.failureReason ?? 'unexpected_failure',
source.size,
state.uploadedBytes,
state.connectCount,
highwayErrorText(state.error ?? error),
Date.now() - state.startedAt,
]);
throw error;
}
});
}
async function uploadHighwayHttpOperation(
bridge: BridgeContext, session: HighwaySession, commandId: number,
source: ChunkSource, fileMd5: Uint8Array, extend: Uint8Array,
trace: HighwayPutTraceState,
): Promise<void> {
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
const totalSize = source.size;
@@ -367,6 +506,7 @@ export async function uploadHighwayHttp(
// disk (FileChunkSource); either way one chunk is read/held at a time. We
// own the source and close it exactly once in the `finally` below.
let succeeded = false;
let sourceCloseFailure: { error: unknown } | undefined;
let socket: net.Socket | null = null;
let connectCount = 0;
const dropSocket = (): void => {
@@ -376,12 +516,27 @@ export async function uploadHighwayHttp(
let offset = 0;
while (offset < totalSize) {
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, totalSize - offset);
const chunk = await source.read(offset, chunkSize);
let chunk: Uint8Array;
try {
chunk = await source.read(offset, chunkSize);
} catch (error) {
trace.failureReason = 'source_read_failed';
trace.error = error;
throw error;
}
log.trace('highway_put_branch branch=chunk_read offset=%d bytes=%d', offset, chunkSize);
const chunkMd5 = computeMd5(chunk);
const head = makeHighwayHead(
bridge.identity.uin, commandId, totalSize, offset, chunkSize,
chunkMd5, fileMd5, session.sigSession, extend,
);
log.trace(() => [
'highway_put_branch branch=chunk_control_request offset=%d bytes=%d headBytes=%d headHex=%s',
offset,
chunkSize,
head.byteLength,
renderTraceBytes(head),
]);
const frame = packHighwayFrame(head, chunk);
// Send this block, reusing the live connection when there is one. On any
@@ -394,27 +549,84 @@ export async function uploadHighwayHttp(
if (!socket) {
socket = await tcpConnect(session.host, session.port);
connectCount += 1;
trace.connectCount = connectCount;
log.trace(
'highway_put_branch branch=%s offset=%d attempt=%d connection=%d',
connectCount === 1 ? 'connect' : 'reconnect',
offset,
attempt,
connectCount,
);
}
log.trace(
'highway_put_branch branch=chunk_attempt offset=%d bytes=%d attempt=%d connection=%d',
offset,
chunkSize,
attempt,
connectCount,
);
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
break;
} catch (err) {
if (err instanceof HighwayResponseReadError && err.responseBody) {
log.trace(() => [
'highway_put_branch branch=chunk_control_response_partial offset=%d attempt=%d responseBytes=%d responseHex=%s',
offset,
attempt,
err.responseBody!.byteLength,
renderTraceBytes(err.responseBody!),
]);
}
dropSocket();
if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) {
throw new Error(
trace.failureReason = 'transport_exhausted';
const exhausted = new Error(
`highway upload transport failed after ${attempt} attempts ` +
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`,
);
trace.error = exhausted;
throw exhausted;
}
log.trace('chunk offset=%d attempt %d failed (%s), reconnecting', offset, attempt, String(err));
log.trace(
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d error=%j',
offset,
chunkSize,
attempt,
highwayErrorText(err),
);
await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt);
}
}
// Unreachable: the retry loop only exits via break (responseBody set) or
// throw — the guard just narrows the type for the compiler.
if (!responseBody) throw new Error('highway upload: missing response');
const { head: respHead } = unpackHighwayFrame(responseBody);
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
if (!responseBody) {
trace.failureReason = 'transport_exhausted';
trace.error = new Error('highway upload: missing response');
throw trace.error;
}
log.trace(() => [
'highway_put_branch branch=chunk_control_response offset=%d bytes=%d responseBytes=%d responseHex=%s',
offset,
chunkSize,
responseBody.byteLength,
renderTraceBytes(responseBody),
]);
let resp: RespDataHighwayHead;
try {
const { head: respHead } = unpackHighwayFrame(responseBody);
resp = protobuf_decode<RespDataHighwayHead>(respHead);
log.trace(
'highway_put_branch branch=chunk_control_decoded offset=%d errorCode=%d segRetCode=%d',
offset,
resp?.errorCode ?? 0,
resp?.msgSegHead?.retCode ?? 0,
);
} catch (error) {
trace.failureReason = 'control_decode_failed';
trace.error = error;
throw error;
}
if (resp?.errorCode && resp.errorCode !== 0) {
// Surface every diagnostic the highway response carries so
// user reports of `error_code=921` and friends include the
@@ -424,12 +636,14 @@ export async function uploadHighwayHttp(
// limit.
const segRetCode = resp.msgSegHead?.retCode ?? 0;
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
throw new Error(
trace.failureReason = 'server_rejected';
trace.error = new Error(
`highway upload error_code=${resp.errorCode}` +
` (cmdId=${commandId} chunk=${chunkSize}/${totalSize}` +
` offset=${offset} segRetCode=${segRetCode}` +
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
);
throw trace.error;
}
// If the peer half-closed after sending its response, the socket can no
@@ -440,7 +654,12 @@ export async function uploadHighwayHttp(
}
offset += chunkSize;
log.trace('uploaded %d/%d bytes', offset, totalSize);
trace.uploadedBytes = offset;
log.trace(
'highway_put_branch branch=chunk_completed offset=%d totalBytes=%d',
offset,
totalSize,
);
}
succeeded = true;
if (totalSize > 0) {
@@ -454,7 +673,14 @@ export async function uploadHighwayHttp(
try {
await source.close();
} catch (closeErr) {
if (succeeded) throw closeErr;
if (succeeded) {
sourceCloseFailure = { error: closeErr };
}
}
}
if (sourceCloseFailure) {
trace.failureReason = 'source_close_failed';
trace.error = sourceCloseFailure.error;
throw sourceCloseFailure.error;
}
}
+124 -9
View File
@@ -1,4 +1,8 @@
import { createLogger } from '@snowluma/common/logger';
import {
createLogger,
renderTraceBytes,
runWithTraceRequest,
} from '@snowluma/common/logger';
import type {
EncodableMediaMsgInfo,
HighwayMsgInfoBody,
@@ -106,6 +110,27 @@ export function hexToBytes(hex: string): Uint8Array {
return out;
}
function sha1TraceValue(value: Uint8Array | Uint8Array[]): string {
const values = Array.isArray(value) ? value : [value];
return `[${values.map((item) => renderTraceBytes(item)).join(',')}]`;
}
function uploadDescriptors(uploads: MediaSubFileUpload[]): string {
return `[${uploads.map((sub) => [
`source:${JSON.stringify(String(sub.source))}`,
`cmdId:${sub.cmdId}`,
`size:${sub.fileSource ? sub.fileSource.fileSize : sub.bytes.byteLength}`,
`storage:${JSON.stringify(sub.fileSource ? 'disk' : 'buffer')}`,
`md5:${renderTraceBytes(sub.md5)}`,
`sha1:${sha1TraceValue(sub.sha1)}`,
`subFileIndex:${sub.subFileIndex ?? 0}`,
].join(',')).join(';')}]`;
}
function mediaErrorText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
// ─────────────── main entrypoint ───────────────
/**
@@ -116,7 +141,54 @@ export function hexToBytes(hex: string): Uint8Array {
* Sessions are cached across sub-file uploads — video does two PUTs but
* only fetches the Highway session once.
*/
export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
export function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2UploadRespBody> {
const startedAt = Date.now();
const label = params.label ?? 'media';
let failureReason = 'unexpected_failure';
let didPut = false;
return runWithTraceRequest(async () => {
moduleLog.trace(() => [
'highway_media_start label=%j scope=%s target=%j oidbCmd=%d serviceCmd=%j requestId=%d businessType=%d uploads=%s',
label,
params.isGroup ? 'group' : 'private',
String(params.targetIdOrUid),
params.oidbCmd,
params.serviceCmd,
params.requestId,
params.businessType,
uploadDescriptors(params.uploads),
]);
try {
const result = await runNtv2UploadOperation(params, (reason, put) => {
failureReason = reason;
if (put !== undefined) didPut = put;
});
moduleLog.trace(
'highway_media_terminal label=%j outcome=completed reason=%s uploads=%d elapsedMs=%d',
label,
didPut ? 'put_complete' : 'fast_upload',
params.uploads.length,
Date.now() - startedAt,
);
return result;
} catch (error) {
moduleLog.trace(() => [
'highway_media_terminal label=%j outcome=failed reason=%s uploads=%d error=%j elapsedMs=%d',
label,
failureReason,
params.uploads.length,
mediaErrorText(error),
Date.now() - startedAt,
]);
throw error;
}
});
}
async function runNtv2UploadOperation(
params: NtV2UploadParams,
setState: (failureReason: string, didPut?: boolean) => void,
): Promise<NTV2UploadRespBody> {
const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params;
const label = params.label ?? 'media';
const raw = bridge.identity?.uin;
@@ -160,24 +232,38 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
const env = makeOidbEnvelope<NTV2UploadRichMediaReq>(oidbCmd, 100, body, true);
const requestBytes = protobuf_encode<OidbBase<NTV2UploadRichMediaReq>>(env);
setState('request_failed');
const result = await bridge.sendRawPacket(serviceCmd, requestBytes);
log.trace(() => [
'highway_media_branch branch=oidb_response success=%s gotResponse=%s errorCode=%d errorMessage=%j responseBytes=%d',
result.success,
result.gotResponse,
result.errorCode,
result.errorMessage ?? '',
result.responseData?.byteLength ?? 0,
]);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(result.errorMessage || `${label} upload request failed`);
}
setState('response_decode_failed');
const resp = protobuf_decode<OidbBase<NTV2UploadRichMediaResp>>(result.responseData);
if (!resp) throw new Error(`failed to decode ${label} upload response`);
if (resp.errorCode && resp.errorCode !== 0) {
setState('oidb_rejected');
throw new Error(`OIDB error ${resp.errorCode}: ${resp.errorMsg ?? ''}`);
}
const uploadBody = resp.body;
setState('response_invalid');
if (!uploadBody) throw new Error(`${label} upload response body missing`);
if (uploadBody.respHead?.retCode && uploadBody.respHead.retCode !== 0) {
setState('business_rejected');
throw new Error(uploadBody.respHead.message ?? `${label} upload failed`);
}
const upload = uploadBody.upload;
if (!upload) throw new Error(`${label} upload response body missing`);
if (!upload.msgInfo) throw new Error('upload response missing msgInfo');
return upload;
};
@@ -186,12 +272,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
// retry shouldn't re-fetch it either.
let session: Awaited<ReturnType<typeof fetchHighwaySession>> | null = null;
const getSession = async () => {
setState('session_failed');
session ??= await fetchHighwaySession(bridge);
return session;
};
// Run whatever PUTs the given `upload` response asks for.
const runPuts = async (upload: NTV2UploadRespBody): Promise<void> => {
const msgInfo = upload.msgInfo;
if (!msgInfo) throw new Error('upload response missing msgInfo');
let didPut = false;
for (const sub of uploads) {
const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source];
@@ -201,26 +290,49 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
// keying the checks below on `bytes.length` would wrongly treat it as a
// fast-only / empty sub-file.
const subSize = sub.fileSource ? sub.fileSource.fileSize : sub.bytes.length;
// No uKey: the server fast-pathed this sub-file (or msgInfo is absent
// entirely) — it already holds (or claims to hold) the resource, so
// there are no bytes to push for it.
if (!uKey || !upload.msgInfo) {
if (!uKey && upload.msgInfo && subSize > 0) {
// No uKey: the server fast-pathed this sub-file — it already holds
// (or claims to hold) the resource, so there are no bytes to push.
if (!uKey) {
if (subSize > 0) {
log.trace(
'highway_media_branch branch=fast_upload source=%j cmdId=%d size=%d',
String(sub.source),
sub.cmdId,
subSize,
);
log.debug('%s fast-upload hit for sub=%s (server reusing cached resource)', label, String(sub.source));
}
continue;
}
if (subSize === 0) {
if (sub.fastOnlyError) throw new Error(sub.fastOnlyError);
log.trace(
'highway_media_branch branch=empty_source source=%j cmdId=%d hasFastOnlyError=%s',
String(sub.source),
sub.cmdId,
Boolean(sub.fastOnlyError),
);
if (sub.fastOnlyError) {
setState('source_unavailable');
throw new Error(sub.fastOnlyError);
}
continue;
}
if (!target) continue;
log.trace(
'highway_media_branch branch=put_required source=%j cmdId=%d size=%d uKey=%j storage=%s',
String(sub.source),
sub.cmdId,
subSize,
uKey,
sub.fileSource ? 'disk' : 'buffer',
);
setState('extend_build_failed');
const extend = buildHighwayExtend(
uKey,
upload.msgInfo,
msgInfo,
target.ipv4s ?? [],
sub.sha1,
sub.subFileIndex ?? 0,
@@ -231,14 +343,17 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise<NTV2Uploa
// session-fetch failure on the first PUT would leak the open handle.
const putSession = await getSession();
// uploadHighwayHttp owns the ChunkSource and closes it exactly once.
setState('source_open_failed');
const chunkSource = sub.fileSource
? await FileChunkSource.open(sub.fileSource.filePath, sub.fileSource.fileSize)
: new BufferChunkSource(sub.bytes);
log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, subSize, String(sub.source));
const t0 = Date.now();
setState('put_failed');
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
log.debug('%s PUT done in %dms', label, Date.now() - t0);
didPut = true;
setState('unexpected_failure', true);
}
if (!didPut) {
+470 -107
View File
@@ -1,5 +1,14 @@
import http from 'node:http';
import https from 'node:https';
import {
createLogger,
getLogLevel,
renderTraceBytes,
runWithTraceRequest,
} from '@snowluma/common/logger';
import { renderParamsVerbose } from '@snowluma/common/log-summary';
const log = createLogger('Protocol.Http');
type RequestBody = string | Buffer | Uint8Array | Record<string, unknown> | undefined;
@@ -29,6 +38,81 @@ interface HttpRequestContext {
deadlineAt?: number;
}
type HttpTerminalReason =
| 'deadline'
| 'non_2xx'
| 'parse_failure'
| 'redirect_failure'
| 'request_invalid'
| 'response_aborted'
| 'response_too_large'
| 'transport_failure';
type HttpOperationOutcome = 'failed' | 'timeout' | 'cancelled';
interface HttpFailureClassification {
outcome: HttpOperationOutcome;
reason: HttpTerminalReason;
}
const httpFailures = new WeakMap<Error, HttpFailureClassification>();
type CookieTerminalReason =
| 'response_complete'
| 'redirect_limit'
| 'redirect_failure'
| 'deadline'
| 'transport_failure';
interface CookieCollectionResult {
reason: CookieTerminalReason;
error?: Error;
}
interface HttpTraceOperation {
readonly startedAt: number;
readonly method: string;
readonly url: string;
terminal: boolean;
}
function errorObject(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
function errorText(error: unknown): string {
return errorObject(error).message;
}
function fail(
outcome: HttpOperationOutcome,
reason: HttpTerminalReason,
error: unknown,
): Error {
const result = errorObject(error);
if (!httpFailures.has(result)) httpFailures.set(result, { outcome, reason });
return result;
}
function traceTerminal(
trace: HttpTraceOperation,
outcome: 'completed' | HttpOperationOutcome,
reason: 'response_complete' | HttpTerminalReason,
error?: unknown,
): void {
if (trace.terminal) return;
trace.terminal = true;
log.trace(() => [
'http_terminal method=%j url=%j outcome=%s reason=%s%s elapsedMs=%d',
trace.method,
trace.url,
outcome,
reason,
error === undefined ? '' : ` error=${JSON.stringify(errorText(error))}`,
Date.now() - trace.startedAt,
]);
}
const SENSITIVE_REDIRECT_HEADERS = new Set([
'authorization',
'cookie',
@@ -58,33 +142,130 @@ export class RequestUtil {
// qzone.qq.com) — without the ceiling that would hang every cookie-backed web
// action forever (the essential cookies are already set by the first hop).
static async HttpsGetCookies(url: string, depth = 0): Promise<{ [key: string]: string; }> {
const startedAt = Date.now();
return runWithTraceRequest(async () => {
const cookies: Record<string, string> = {};
log.trace('http_cookie_start url=%j depth=%d', url, depth);
let result: CookieCollectionResult;
try {
result = await this.collectCookies(url, depth, cookies);
} catch (error) {
result = { reason: 'transport_failure', error: errorObject(error) };
}
log.trace(() => [
'http_cookie_terminal url=%j outcome=completed reason=%s failOpen=%s cookies=%s%s elapsedMs=%d',
url,
result.reason,
result.reason !== 'response_complete',
renderParamsVerbose(cookies),
result.error === undefined ? '' : ` error=${JSON.stringify(errorText(result.error))}`,
Date.now() - startedAt,
]);
return cookies;
});
}
private static collectCookies(
url: string,
depth: number,
cookies: Record<string, string>,
): Promise<CookieCollectionResult> {
const client = url.startsWith('https') ? https : http;
return new Promise((resolve) => {
const cookies: { [key: string]: string; } = {};
let settled = false;
const done = (extra?: { [key: string]: string; }) => {
let traceResponseDeadline: (() => void) | undefined;
const done = (reason: CookieTerminalReason, error?: unknown) => {
if (settled) return;
settled = true;
resolve(extra ? { ...cookies, ...extra } : cookies);
resolve({
reason,
...(error === undefined ? {} : { error: errorObject(error) }),
});
};
const req = client.get(url, (res) => {
if (res.headers['set-cookie']) {
this.extractCookies(res.headers['set-cookie'], cookies);
}
res.on('data', () => { }); // 必须消耗流
log.trace(() => [
'http_cookie_response url=%j status=%s headers=%s cookies=%s',
url,
res.statusCode ?? 'unknown',
renderParamsVerbose(res.headers),
renderParamsVerbose(cookies),
]);
const traceChunks: Buffer[] | null = getLogLevel() === 'trace' ? [] : null;
let traceResponseBytes = 0;
let bodyTraced = false;
const traceBody = (state: 'complete' | 'aborted' | 'error' | 'deadline') => {
if (bodyTraced) return;
bodyTraced = true;
if (traceChunks === null) return;
const body = Buffer.concat(traceChunks, traceResponseBytes);
log.trace(() => [
'http_cookie_body url=%j state=%s bodyBytes=%d bodyHex=%s body=%j',
url,
state,
traceResponseBytes,
renderTraceBytes(body),
body.toString(),
]);
};
traceResponseDeadline = () => traceBody('deadline');
res.on('data', (chunk: string | Buffer) => {
if (traceChunks === null) return;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
traceResponseBytes += bytes.length;
traceChunks.push(bytes);
});
res.once('aborted', () => {
traceBody('aborted');
done('transport_failure', new Error('cookie response aborted before completion'));
});
res.once('error', (error: Error) => {
traceBody('error');
done('transport_failure', error);
});
res.on('end', () => {
traceBody('complete');
const location = res.headers.location;
if ((res.statusCode === 301 || res.statusCode === 302) && location && depth < 5) {
this.HttpsGetCookies(new URL(location, url).href, depth + 1)
.then((rc) => done(rc))
.catch(() => done());
} else {
done();
if ((res.statusCode === 301 || res.statusCode === 302) && location) {
if (depth >= 5) {
done('redirect_limit');
return;
}
let redirectUrl: string;
try {
redirectUrl = new URL(location, url).href;
} catch {
done('redirect_failure');
return;
}
log.trace(() => [
'http_cookie_branch branch=redirect status=%d from=%j to=%j cookies=%s remainingRedirects=%d',
res.statusCode,
url,
redirectUrl,
renderParamsVerbose(cookies),
5 - depth,
]);
this.collectCookies(redirectUrl, depth + 1, cookies)
.then((result) => {
if (settled) return;
settled = true;
resolve(result);
})
.catch((error) => done('transport_failure', error));
return;
}
done('response_complete');
});
});
req.setTimeout(8000, () => { req.destroy(); done(); });
req.on('error', () => done());
req.setTimeout(8000, () => {
traceResponseDeadline?.();
req.destroy();
done('deadline');
});
req.on('error', (error) => done('transport_failure', error));
});
}
@@ -105,40 +286,94 @@ export class RequestUtil {
[key: string]: string;
} = {}, isJsonRet: boolean = true, isArgJson: boolean = true, maxRedirects: number = 5,
responseLimits: HttpResponseLimits = {}): Promise<T> {
validateLimit('timeoutMs', responseLimits.timeoutMs);
validateLimit('maxResponseBytes', responseLimits.maxResponseBytes);
return this.request<T>({
const methodName = method.toUpperCase();
const trace: HttpTraceOperation = {
startedAt: Date.now(),
method: methodName,
url,
method,
data,
headers,
isJsonRet,
isArgJson,
maxRedirects,
responseLimits,
deadlineAt: responseLimits.timeoutMs === undefined
? undefined
: Date.now() + responseLimits.timeoutMs,
terminal: false,
};
return runWithTraceRequest(async () => {
log.trace(() => [
'http_start method=%j url=%j headers=%s data=%s responseType=%s timeoutMs=%s maxResponseBytes=%s',
methodName,
url,
renderParamsVerbose(headers),
renderParamsVerbose(data),
isJsonRet ? 'json' : 'text',
responseLimits.timeoutMs ?? 'none',
responseLimits.maxResponseBytes ?? 'none',
]);
try {
try {
validateLimit('timeoutMs', responseLimits.timeoutMs);
validateLimit('maxResponseBytes', responseLimits.maxResponseBytes);
} catch (error) {
throw fail('failed', 'request_invalid', error);
}
const value = await this.request<T>({
url,
method: methodName,
data,
headers,
isJsonRet,
isArgJson,
maxRedirects,
responseLimits,
deadlineAt: responseLimits.timeoutMs === undefined
? undefined
: Date.now() + responseLimits.timeoutMs,
});
traceTerminal(trace, 'completed', 'response_complete');
return value;
} catch (error: unknown) {
const result = errorObject(error);
const classification = httpFailures.get(result) ?? {
outcome: 'failed' as const,
reason: 'transport_failure' as const,
};
traceTerminal(
trace,
classification.outcome,
classification.reason,
result,
);
throw result;
}
});
}
private static async request<T>(context: HttpRequestContext): Promise<T> {
const option = new URL(context.url);
let option: URL;
try {
option = new URL(context.url);
} catch (error) {
throw fail('failed', 'request_invalid', error);
}
const protocol = option.protocol === 'https:'
? https
: option.protocol === 'http:'
? http
: undefined;
if (!protocol) {
throw new Error(`unsupported request protocol: ${option.protocol}`);
throw fail(
'failed',
'request_invalid',
new Error(`unsupported request protocol: ${option.protocol}`),
);
}
const remainingTimeoutMs = context.deadlineAt === undefined
? undefined
: context.deadlineAt - Date.now();
if (remainingTimeoutMs !== undefined && remainingTimeoutMs <= 0) {
throw new Error(`request timed out after ${context.responseLimits.timeoutMs} ms`);
throw fail(
'timeout',
'deadline',
new Error(`request timed out after ${context.responseLimits.timeoutMs} ms`),
);
}
const options = {
@@ -152,6 +387,9 @@ export class RequestUtil {
return new Promise((resolve, reject) => {
let settled = false;
let timeout: NodeJS.Timeout | undefined;
let traceResponseFailure: ((
state: 'aborted' | 'deadline' | 'error' | 'too_large',
) => void) | undefined;
const clearDeadline = () => {
if (timeout !== undefined) clearTimeout(timeout);
};
@@ -174,107 +412,232 @@ export class RequestUtil {
next.then(resolve).catch(reject);
};
const req = protocol.request(options, (res: http.IncomingMessage) => {
const closeCurrent = () => {
res.destroy();
req.destroy();
};
res.once('error', (error: Error) => rejectOnce(error));
let req: http.ClientRequest;
try {
req = protocol.request(options, (res: http.IncomingMessage) => {
const statusCode = res.statusCode ?? 0;
const closeCurrent = () => {
res.destroy();
req.destroy();
};
res.once('error', (error: Error) => {
traceResponseFailure?.('error');
rejectOnce(fail('failed', 'transport_failure', error));
});
res.once('aborted', () => {
traceResponseFailure?.('aborted');
rejectOnce(fail(
'cancelled',
'response_aborted',
new Error('response aborted before completion'),
));
});
if ((res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307 || res.statusCode === 308) && res.headers.location) {
if (context.maxRedirects <= 0) {
rejectOnce(new Error('Too many redirects'));
closeCurrent();
return;
}
if ((statusCode === 301 || statusCode === 302 || statusCode === 307 || statusCode === 308) && res.headers.location) {
log.trace(() => [
'http_response status=%d url=%j headers=%s bodyState=not_read',
statusCode,
context.url,
renderParamsVerbose(res.headers),
]);
if (context.maxRedirects <= 0) {
rejectOnce(fail('failed', 'redirect_failure', new Error('Too many redirects')));
closeCurrent();
return;
}
let redirectUrl: URL;
try {
redirectUrl = new URL(res.headers.location, option);
} catch (error) {
rejectOnce(new Error('invalid redirect location', { cause: error }));
closeCurrent();
return;
}
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
rejectOnce(new Error(`unsupported redirect protocol: ${redirectUrl.protocol}`));
closeCurrent();
return;
}
if (option.origin !== redirectUrl.origin
let redirectUrl: URL;
try {
redirectUrl = new URL(res.headers.location, option);
} catch (error) {
rejectOnce(fail(
'failed',
'redirect_failure',
new Error('invalid redirect location', { cause: error }),
));
closeCurrent();
return;
}
if (redirectUrl.protocol !== 'http:' && redirectUrl.protocol !== 'https:') {
rejectOnce(fail(
'failed',
'redirect_failure',
new Error(`unsupported redirect protocol: ${redirectUrl.protocol}`),
));
closeCurrent();
return;
}
if (option.origin !== redirectUrl.origin
&& context.method.toUpperCase() !== 'GET'
&& context.method.toUpperCase() !== 'HEAD') {
rejectOnce(new Error(
`cross-origin redirect cannot forward method ${context.method.toUpperCase()}`,
rejectOnce(fail(
'failed',
'redirect_failure',
new Error(
`cross-origin redirect cannot forward method ${context.method.toUpperCase()}`,
),
));
closeCurrent();
return;
}
const redirectHeaders = headersForRedirect(context.headers, option, redirectUrl);
log.trace(() => [
'http_branch branch=redirect status=%d from=%j to=%j nextHeaders=%s remainingRedirects=%d',
statusCode,
context.url,
redirectUrl.href,
renderParamsVerbose(redirectHeaders),
context.maxRedirects - 1,
]);
handOff(this.request<T>({
...context,
url: redirectUrl.href,
headers: redirectHeaders,
maxRedirects: context.maxRedirects - 1,
}));
closeCurrent();
return;
}
if (statusCode < 200 || statusCode >= 300) {
log.trace(() => [
'http_response status=%d url=%j headers=%s bodyState=not_read',
statusCode,
context.url,
renderParamsVerbose(res.headers),
]);
rejectOnce(fail(
'failed',
'non_2xx',
new Error(`Unexpected status code: ${res.statusCode}`),
));
closeCurrent();
return;
}
handOff(this.request<T>({
...context,
url: redirectUrl.href,
headers: headersForRedirect(context.headers, option, redirectUrl),
maxRedirects: context.maxRedirects - 1,
}));
closeCurrent();
return;
}
if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
rejectOnce(new Error(`Unexpected status code: ${res.statusCode}`));
closeCurrent();
return;
}
const chunks: Buffer[] = [];
let responseBytes = 0;
res.on('data', (chunk: string | Buffer) => {
if (settled) return;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
responseBytes += bytes.length;
if (context.responseLimits.maxResponseBytes !== undefined
const chunks: Buffer[] = [];
let responseBytes = 0;
let failureBodyTraced = false;
traceResponseFailure = (state) => {
if (failureBodyTraced) return;
failureBodyTraced = true;
log.trace(() => {
const observedBody = Buffer.concat(chunks, responseBytes);
return [
'http_response status=%d url=%j headers=%s bodyState=%s bodyBytes=%d bodyHex=%s body=%j',
statusCode,
context.url,
renderParamsVerbose(res.headers),
state,
responseBytes,
renderTraceBytes(observedBody),
observedBody.toString(),
];
});
};
res.on('data', (chunk: string | Buffer) => {
if (settled) return;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
responseBytes += bytes.length;
chunks.push(bytes);
if (context.responseLimits.maxResponseBytes !== undefined
&& responseBytes > context.responseLimits.maxResponseBytes) {
const error = new Error(
`response body exceeds ${context.responseLimits.maxResponseBytes} bytes`,
);
rejectOnce(error);
closeCurrent();
return;
}
chunks.push(bytes);
});
res.on('end', () => {
if (settled) return;
const responseBody = Buffer.concat(chunks, responseBytes).toString();
try {
if (context.isJsonRet) {
resolveOnce(JSON.parse(responseBody) as T);
} else {
resolveOnce(responseBody as T);
traceResponseFailure?.('too_large');
const error = fail(
'failed',
'response_too_large',
new Error(
`response body exceeds ${context.responseLimits.maxResponseBytes} bytes`,
),
);
rejectOnce(error);
closeCurrent();
return;
}
} catch (parseError: unknown) {
rejectOnce(new Error(parseError instanceof Error ? parseError.message : String(parseError)));
}
});
res.on('end', () => {
if (settled) return;
failureBodyTraced = true;
const responseBuffer = Buffer.concat(chunks, responseBytes);
const responseBody = responseBuffer.toString();
log.trace(() => [
'http_response status=%d url=%j headers=%s bodyBytes=%d bodyHex=%s body=%j',
statusCode,
context.url,
renderParamsVerbose(res.headers),
responseBytes,
renderTraceBytes(responseBuffer),
responseBody,
]);
try {
if (context.isJsonRet) {
const parsed = JSON.parse(responseBody) as T;
log.trace(() => [
'http_branch branch=parse_completed responseType=json result=%s',
renderParamsVerbose(parsed),
]);
resolveOnce(parsed);
} else {
log.trace('http_branch branch=parse_completed responseType=text');
resolveOnce(responseBody as T);
}
} catch (parseError: unknown) {
log.trace(() => [
'http_branch branch=parse_failed responseType=json error=%j',
errorText(parseError),
]);
rejectOnce(fail('failed', 'parse_failure', parseError));
}
});
});
});
} catch (error) {
rejectOnce(fail('failed', 'request_invalid', error));
return;
}
if (remainingTimeoutMs !== undefined) {
timeout = setTimeout(() => {
traceResponseFailure?.('deadline');
const error = new Error(
`request timed out after ${context.responseLimits.timeoutMs} ms`,
);
rejectOnce(error);
rejectOnce(fail('timeout', 'deadline', error));
req.destroy();
}, remainingTimeoutMs);
}
req.on('error', (error: Error) => rejectOnce(error));
if (context.method === 'POST' || context.method === 'PUT' || context.method === 'PATCH') {
req.write(context.isArgJson ? JSON.stringify(context.data) : context.data);
req.on('error', (error: Error) => rejectOnce(
fail('failed', 'transport_failure', error),
));
try {
if (context.method === 'POST' || context.method === 'PUT' || context.method === 'PATCH') {
const requestBody = context.isArgJson
? JSON.stringify(context.data)
: context.data;
if (typeof requestBody === 'string'
|| Buffer.isBuffer(requestBody)
|| requestBody instanceof Uint8Array) {
log.trace(() => {
const requestBytes = typeof requestBody === 'string'
? Buffer.from(requestBody)
: requestBody;
return [
'http_branch branch=request_body url=%j requestBytes=%d requestHex=%s',
context.url,
requestBytes.byteLength,
renderTraceBytes(requestBytes),
];
});
}
req.write(requestBody);
}
req.end();
} catch (error) {
rejectOnce(fail('failed', 'request_invalid', error));
req.destroy();
}
req.end();
});
}