From 5324e2f01469a8f258195165280b1bcf94b666c7 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 5 Jul 2026 02:29:13 +0800 Subject: [PATCH] refactor(highway): introduce ChunkSource for uploadHighwayHttp (phase 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prep for streaming large media uploads from disk instead of buffering the whole file in RAM. Add a `ChunkSource` abstraction — `BufferChunkSource` (in-memory, byte-for-byte the old path) and `FileChunkSource` (disk-backed, reads exact-length chunks via a FileHandle, loops on short reads, throws on unexpected EOF) — and change `uploadHighwayHttp` to consume a `ChunkSource` instead of a `Uint8Array`. The uploader now owns the source and closes it once in `finally` (best-effort; never masks a primary upload error). Pure structural refactor: no streaming is wired yet. All five call sites (pipeline runPuts, group + private file upload, personal + group avatar) wrap their bytes in `BufferChunkSource`, so behavior is unchanged. Adds a byte-oracle test proving FileChunkSource ≡ BufferChunkSource across block boundaries, plus short-read/EOF/empty-input coverage. --- packages/core/src/bridge/apis/group-file.ts | 6 +- packages/core/src/bridge/apis/profile.ts | 6 +- .../core/tests/actions/group-file.test.ts | 1 + packages/core/tests/actions/profile.test.ts | 1 + .../core/tests/highway/chunk-source.test.ts | 103 +++++++++ .../core/tests/highway/highway-client.test.ts | 15 +- .../core/tests/highway/multi-image.test.ts | 7 +- packages/core/tests/highway/pipeline.test.ts | 1 + .../core/tests/observability-logs.test.ts | 1 + .../protocol/src/highway/highway-client.ts | 214 ++++++++++++------ packages/protocol/src/highway/pipeline.ts | 4 +- 11 files changed, 276 insertions(+), 83 deletions(-) create mode 100644 packages/core/tests/highway/chunk-source.test.ts diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index c792f29d..a374bcb5 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -1,7 +1,7 @@ import { toHexUpper } from '@snowluma/common/hex'; import { createLogger } from '@snowluma/common/logger'; import type { FileUploadExt } from '@snowluma/proto-defs/highway'; -import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; +import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils'; import { protobuf_encode } from '@snowluma/proton'; import type { Bridge } from '../bridge'; @@ -330,7 +330,7 @@ export class GroupFileApi { ); const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext); + await uploadHighwayHttp(bridge, session, 71, new BufferChunkSource(loaded.bytes), hashes.md5, ext); } // Stage 3: file is on the server, now publish it as a chat message. @@ -490,7 +490,7 @@ export class GroupFileApi { ); const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext); + await uploadHighwayHttp(bridge, session, 95, new BufferChunkSource(loaded.bytes), hashes.md5, ext); } // Stage 3: publish the file as a c2c chat message. C2C files use diff --git a/packages/core/src/bridge/apis/profile.ts b/packages/core/src/bridge/apis/profile.ts index 694c9557..0cc1a608 100644 --- a/packages/core/src/bridge/apis/profile.ts +++ b/packages/core/src/bridge/apis/profile.ts @@ -10,7 +10,7 @@ import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/d import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face'; import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face'; import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face'; -import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; +import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway'; import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils'; import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like'; import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list'; @@ -93,7 +93,7 @@ export class ProfileApi { const hashes = computeHashes(loaded.bytes); const session = await fetchHighwaySession(bridge); - await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0)); + await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0)); } /** @@ -120,7 +120,7 @@ export class ProfileApi { field5: 3, field6: 1, }); - await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra); + await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra); } // ─────────────── queries on me / my contacts ─────────────── diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index d44c4368..042eb6eb 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -26,6 +26,7 @@ import type { vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({})), uploadHighwayHttp: vi.fn(async () => undefined), + BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} }, })); vi.mock('@snowluma/protocol/highway/utils', () => ({ diff --git a/packages/core/tests/actions/profile.test.ts b/packages/core/tests/actions/profile.test.ts index f33901b1..2b45c1d9 100644 --- a/packages/core/tests/actions/profile.test.ts +++ b/packages/core/tests/actions/profile.test.ts @@ -28,6 +28,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', async () => { vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({})), uploadHighwayHttp: vi.fn(async () => undefined), + BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} }, })); vi.mock('@snowluma/protocol/highway/utils', () => ({ diff --git a/packages/core/tests/highway/chunk-source.test.ts b/packages/core/tests/highway/chunk-source.test.ts new file mode 100644 index 00000000..7a7cd223 --- /dev/null +++ b/packages/core/tests/highway/chunk-source.test.ts @@ -0,0 +1,103 @@ +// ChunkSource is the buffer-or-disk abstraction the highway PUT loop reads +// through (#stream-upload). The whole streaming refactor rests on one +// invariant: a FileChunkSource must yield BYTE-FOR-BYTE the same chunks as a +// BufferChunkSource over the same file, at every (offset, length) the uploader +// asks for. These tests are that byte-oracle. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { promises as fsp } from 'fs'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { randomUUID } from 'crypto'; +import { BufferChunkSource, FileChunkSource } from '@snowluma/protocol/highway'; + +// Mirrors highway-client's HIGHWAY_BLOCK_SIZE chunk walk without the network: +// step through [0,size) in `block` strides, last chunk short by construction. +async function collectChunks(src: { size: number; read(o: number, l: number): Promise }, block: number) { + const chunks: Uint8Array[] = []; + let offset = 0; + while (offset < src.size) { + const len = Math.min(block, src.size - offset); + chunks.push(new Uint8Array(await src.read(offset, len))); + offset += len; + } + return chunks; +} + +describe('ChunkSource — FileChunkSource ≡ BufferChunkSource', () => { + let dir: string; + beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-chunk-')); }); + afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); }); + + // Sizes chosen around block boundaries: exact multiple, +1, -1, tiny, empty. + for (const [label, size, block] of [ + ['empty', 0, 7], + ['tiny (< block)', 5, 7], + ['exact multiple', 21, 7], + ['one past a boundary', 22, 7], + ['one before a boundary', 20, 7], + ['single full block', 7, 7], + ] as const) { + it(`${label}: chunks + size are byte-identical (size=${size}, block=${block})`, async () => { + const data = new Uint8Array(size); + for (let i = 0; i < size; i++) data[i] = (i * 31 + 7) & 0xff; + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, data); + + const buf = new BufferChunkSource(data); + const fch = await FileChunkSource.open(file, size); + try { + expect(fch.size).toBe(buf.size); + expect(fch.size).toBe(size); + const a = await collectChunks(buf, block); + const b = await collectChunks(fch, block); + expect(b.length).toBe(a.length); + for (let i = 0; i < a.length; i++) { + expect(Buffer.from(b[i]!).equals(Buffer.from(a[i]!))).toBe(true); + } + // Reassembled stream equals the original bytes exactly. + expect(Buffer.concat(b.map((c) => Buffer.from(c))).equals(Buffer.from(data))).toBe(true); + } finally { + await fch.close(); + } + }); + } + + it('FileChunkSource.read returns EXACTLY the requested length (no short read leaks)', async () => { + const data = new Uint8Array(1000).map((_, i) => (i * 13) & 0xff); + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, data); + const fch = await FileChunkSource.open(file, data.length); + try { + for (const [off, len] of [[0, 1], [0, 1000], [37, 200], [999, 1], [500, 500]] as const) { + const got = await fch.read(off, len); + expect(got.length).toBe(len); + expect(Buffer.from(got).equals(Buffer.from(data.subarray(off, off + len)))).toBe(true); + } + } finally { + await fch.close(); + } + }); + + it('FileChunkSource.read throws on unexpected EOF (request past end)', async () => { + const data = new Uint8Array(10); + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, data); + const fch = await FileChunkSource.open(file, 10); + try { + await expect(fch.read(5, 20)).rejects.toThrow(/unexpected EOF/); + } finally { + await fch.close(); + } + }); + + it('BufferChunkSource.close and FileChunkSource.close both resolve (idempotent contract)', async () => { + const buf = new BufferChunkSource(new Uint8Array(3)); + await expect(buf.close()).resolves.toBeUndefined(); + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, new Uint8Array(3)); + const fch = await FileChunkSource.open(file, 3); + await expect(fch.close()).resolves.toBeUndefined(); + }); +}); diff --git a/packages/core/tests/highway/highway-client.test.ts b/packages/core/tests/highway/highway-client.test.ts index 68490fe1..e3b85043 100644 --- a/packages/core/tests/highway/highway-client.test.ts +++ b/packages/core/tests/highway/highway-client.test.ts @@ -88,7 +88,7 @@ vi.mock('net', () => ({ createConnection: createConnectionMock, })); -import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway'; +import { uploadHighwayHttp, BufferChunkSource, type HighwaySession } from '@snowluma/protocol/highway'; import type { BridgeContext } from '@snowluma/protocol/bridge-context'; const HIGHWAY_BLOCK_SIZE = 1024 * 1024; @@ -130,7 +130,7 @@ describe('uploadHighwayHttp connection lifecycle', () => { // 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。 const bytes = new Uint8Array(512 * 1024); await uploadHighwayHttp( - makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0), + makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), ); expect(createConnectionMock).toHaveBeenCalledTimes(1); expect(createdSockets[0]!.destroyed).toBe(true); @@ -142,7 +142,7 @@ describe('uploadHighwayHttp connection lifecycle', () => { // 关闭,新实现必须为每个 chunk 各开一个 socket。 const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE)); await uploadHighwayHttp( - makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0), + makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), ); expect(createConnectionMock).toHaveBeenCalledTimes(2); expect(createdSockets).toHaveLength(2); @@ -154,8 +154,15 @@ describe('uploadHighwayHttp connection lifecycle', () => { it('opens N connections for N chunks (3 chunks here)', async () => { const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); await uploadHighwayHttp( - makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0), + makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), ); expect(createConnectionMock).toHaveBeenCalledTimes(3); }); + + it('a zero-length source opens ZERO connections (empty-input invariant)', async () => { + await uploadHighwayHttp( + makeBridge(), makeSession(), 1003, new BufferChunkSource(new Uint8Array(0)), new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).not.toHaveBeenCalled(); + }); }); diff --git a/packages/core/tests/highway/multi-image.test.ts b/packages/core/tests/highway/multi-image.test.ts index 4c075e0f..493a5a2e 100644 --- a/packages/core/tests/highway/multi-image.test.ts +++ b/packages/core/tests/highway/multi-image.test.ts @@ -153,9 +153,12 @@ describe('runNtv2Upload — two images in one message (sequential)', () => { // The PUT receives image-2's bytes, image-2's md5, and the // image-2-derived extend (NOT image-1's data). - const [, , cmdId, putBytes, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!; + const [, , cmdId, putSource, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!; expect(cmdId).toBe(1004); - expect(putBytes).toBe(image2Bytes); + // The PUT source is a ChunkSource wrapping image-2's bytes — verify it + // yields image-2 exactly (not image-1) through its public read(). + expect(putSource.size).toBe(image2Bytes.length); + expect(Buffer.from(await putSource.read(0, putSource.size)).equals(Buffer.from(image2Bytes))).toBe(true); expect(putMd5).toBe(image2Md5); // Decode the extend bytes; uKey + fileUuid must come from image-2's diff --git a/packages/core/tests/highway/pipeline.test.ts b/packages/core/tests/highway/pipeline.test.ts index 0023d68d..558b923c 100644 --- a/packages/core/tests/highway/pipeline.test.ts +++ b/packages/core/tests/highway/pipeline.test.ts @@ -12,6 +12,7 @@ vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), uploadHighwayHttp: vi.fn(async () => undefined), buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), + BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} }, PRIVATE_IMAGE_CMD_ID: 1003, GROUP_IMAGE_CMD_ID: 1004, })); diff --git a/packages/core/tests/observability-logs.test.ts b/packages/core/tests/observability-logs.test.ts index 7310b9d0..918f7c9e 100644 --- a/packages/core/tests/observability-logs.test.ts +++ b/packages/core/tests/observability-logs.test.ts @@ -17,6 +17,7 @@ vi.mock('@snowluma/protocol/highway', () => ({ fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), uploadHighwayHttp: vi.fn(async () => undefined), buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), + BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} }, PRIVATE_IMAGE_CMD_ID: 1003, GROUP_IMAGE_CMD_ID: 1004, })); diff --git a/packages/protocol/src/highway/highway-client.ts b/packages/protocol/src/highway/highway-client.ts index 98bdf173..d5d38b3f 100644 --- a/packages/protocol/src/highway/highway-client.ts +++ b/packages/protocol/src/highway/highway-client.ts @@ -11,6 +11,7 @@ import type { import { createLogger } from '@snowluma/common/logger'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import net from 'net'; +import { promises as fsp } from 'fs'; import type { BridgeContext } from '../bridge-context'; import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils'; @@ -240,11 +241,70 @@ async function httpPostFrame( return readHttpResponseBody(socket); } +// ─────────────── ChunkSource: buffer-or-disk input for highway PUTs ─────────────── + +/** + * Abstracts where the upload bytes come from so `uploadHighwayHttp` can PUT + * either an in-memory buffer (image / ptt / thumb / avatar — small) or a file + * on disk (large video / group file — streamed 1 MiB at a time, never fully + * buffered). `read(offset, length)` MUST return exactly `length` bytes. The + * uploader owns the source and calls `close()` exactly once. + */ +export interface ChunkSource { + readonly size: number; + read(offset: number, length: number): Promise; + close(): Promise; +} + +/** In-memory source — byte-for-byte the pre-refactor behavior. `close()` no-op. */ +export class BufferChunkSource implements ChunkSource { + constructor(private readonly bytes: Uint8Array) {} + get size(): number { return this.bytes.length; } + read(offset: number, length: number): Promise { + return Promise.resolve(this.bytes.subarray(offset, offset + length)); + } + close(): Promise { return Promise.resolve(); } +} + +/** + * Disk-backed source. Reads from an open `FileHandle` at explicit offsets, so a + * multi-GiB upload never holds more than one chunk in memory. `read` loops until + * it has exactly `length` bytes — `FileHandle.read` may legally short-read — and + * throws on unexpected EOF (callers only ever request ranges within `size`). + */ +export class FileChunkSource implements ChunkSource { + private constructor(private readonly fh: fsp.FileHandle, readonly size: number) {} + + static async open(filePath: string, size: number): Promise { + const fh = await fsp.open(filePath, 'r'); + return new FileChunkSource(fh, size); + } + + async read(offset: number, length: number): Promise { + const buf = Buffer.allocUnsafe(length); + let got = 0; + while (got < length) { + const { bytesRead } = await this.fh.read(buf, got, length - got, offset + got); + if (bytesRead === 0) { + throw new Error( + `FileChunkSource: unexpected EOF at ${offset + got} ` + + `(wanted ${length}, got ${got}, size=${this.size})`, + ); + } + got += bytesRead; + } + return buf; + } + + close(): Promise { return this.fh.close(); } +} + export async function uploadHighwayHttp( bridge: BridgeContext, session: HighwaySession, commandId: number, - bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array, + source: ChunkSource, fileMd5: Uint8Array, extend: Uint8Array, ): Promise { const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`; + const totalSize = source.size; // 每个 chunk 一个独立的 TCP 连接。 // @@ -261,75 +321,91 @@ export async function uploadHighwayHttp( // - 单个 1 MB chunk 的传输时间远大于 TCP 建连开销; // - QQ 服务端反正也不希望客户端长时间占用连接; // - 与 NapCat / Lagrange 在大文件上传时的连接生命周期一致。 - let offset = 0; - while (offset < bytes.length) { - const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset); - const chunk = bytes.subarray(offset, offset + chunkSize); - const chunkMd5 = computeMd5(chunk); - const head = makeHighwayHead( - bridge.identity.uin, commandId, bytes.length, offset, chunkSize, - chunkMd5, fileMd5, session.sigSession, extend, - ); - const frame = packHighwayFrame(head, chunk); - - // Retry the connect + POST for this chunk on transient transport errors - // (peer FIN before response, ECONNRESET, connect refused/timeout). Each - // attempt uses a fresh connection; re-sending the same offset range is - // idempotent on the server. - let responseBody: Uint8Array | undefined; - for (let attempt = 1; ; attempt++) { - let socket: net.Socket; - try { - socket = await tcpConnect(session.host, session.port); - } catch (err) { - if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { - throw new Error( - `highway connect failed after ${attempt} attempts ` + - `(cmdId=${commandId} offset=${offset}/${bytes.length}): ${String(err)}`, - ); - } - await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); - continue; - } - try { - responseBody = await httpPostFrame(socket, session.host, pathStr, frame); - break; - } catch (err) { - if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { - throw new Error( - `highway upload transport failed after ${attempt} attempts ` + - `(cmdId=${commandId} chunk=${chunkSize}/${bytes.length} offset=${offset}): ${String(err)}`, - ); - } - log.trace('chunk offset=%d attempt %d failed (%s), retrying', offset, attempt, String(err)); - await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); - } finally { - socket.destroy(); - } - } - - // 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(respHead); - if (resp?.errorCode && resp.errorCode !== 0) { - // Surface every diagnostic the highway response carries so - // user reports of `error_code=921` and friends include the - // server-side context (segHead.retCode, chunk size, file md5) - // — without these we can't tell apart a malformed-payload - // reject, a session-ticket mismatch, or a per-account rate- - // limit. - const segRetCode = resp.msgSegHead?.retCode ?? 0; - const fileMd5Hex = Buffer.from(fileMd5).toString('hex'); - throw new Error( - `highway upload error_code=${resp.errorCode}` + - ` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` + - ` offset=${offset} segRetCode=${segRetCode}` + - ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, + // + // `source` may buffer the whole file (BufferChunkSource) or stream it from + // 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; + try { + let offset = 0; + while (offset < totalSize) { + const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, totalSize - offset); + const chunk = await source.read(offset, chunkSize); + const chunkMd5 = computeMd5(chunk); + const head = makeHighwayHead( + bridge.identity.uin, commandId, totalSize, offset, chunkSize, + chunkMd5, fileMd5, session.sigSession, extend, ); + const frame = packHighwayFrame(head, chunk); + + // Retry the connect + POST for this chunk on transient transport errors + // (peer FIN before response, ECONNRESET, connect refused/timeout). Each + // attempt uses a fresh connection; re-sending the same offset range is + // idempotent on the server. + let responseBody: Uint8Array | undefined; + for (let attempt = 1; ; attempt++) { + let socket: net.Socket; + try { + socket = await tcpConnect(session.host, session.port); + } catch (err) { + if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { + throw new Error( + `highway connect failed after ${attempt} attempts ` + + `(cmdId=${commandId} offset=${offset}/${totalSize}): ${String(err)}`, + ); + } + await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); + continue; + } + try { + responseBody = await httpPostFrame(socket, session.host, pathStr, frame); + break; + } catch (err) { + if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { + throw new Error( + `highway upload transport failed after ${attempt} attempts ` + + `(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`, + ); + } + log.trace('chunk offset=%d attempt %d failed (%s), retrying', offset, attempt, String(err)); + await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); + } finally { + socket.destroy(); + } + } + + // 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(respHead); + if (resp?.errorCode && resp.errorCode !== 0) { + // Surface every diagnostic the highway response carries so + // user reports of `error_code=921` and friends include the + // server-side context (segHead.retCode, chunk size, file md5) + // — without these we can't tell apart a malformed-payload + // reject, a session-ticket mismatch, or a per-account rate- + // limit. + const segRetCode = resp.msgSegHead?.retCode ?? 0; + const fileMd5Hex = Buffer.from(fileMd5).toString('hex'); + throw new Error( + `highway upload error_code=${resp.errorCode}` + + ` (cmdId=${commandId} chunk=${chunkSize}/${totalSize}` + + ` offset=${offset} segRetCode=${segRetCode}` + + ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, + ); + } + offset += chunkSize; + log.trace('uploaded %d/%d bytes', offset, totalSize); + } + succeeded = true; + } finally { + // Best-effort close — never mask a primary upload error. A close failure + // is only surfaced when the upload itself succeeded. + try { + await source.close(); + } catch (closeErr) { + if (succeeded) throw closeErr; } - offset += chunkSize; - log.trace('uploaded %d/%d bytes', offset, bytes.length); } } diff --git a/packages/protocol/src/highway/pipeline.ts b/packages/protocol/src/highway/pipeline.ts index a2e20e80..40cba10b 100644 --- a/packages/protocol/src/highway/pipeline.ts +++ b/packages/protocol/src/highway/pipeline.ts @@ -13,7 +13,7 @@ import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import crypto from 'crypto'; import type { BridgeContext } from '../bridge-context'; import { makeOidbEnvelope } from '../bridge-oidb'; -import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; +import { BufferChunkSource, buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; const moduleLog = createLogger('Highway'); @@ -217,7 +217,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise