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

+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) {