From 679f3b5b9f39b31a5d4f7187a0f51f2979c0d61f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Thu, 13 Aug 2026 00:20:40 +0800 Subject: [PATCH] fix(highway): delay-retry 102902 instead of aborting the upload (#352) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit upload_group_file of ~2 GiB files failed after a highway idle timeout because the next decoded error_code=102902 was treated as a fatal server reject. QQ's own BDH client (multi_uploader.cc NeedDelayRetry) treats 102902 / 302902 as backpressure: wait, switch sender, and re-PUT the same offset. Mirror that — drop the socket, wait 250 ms, increment retryTimes, and retry the chunk up to 8 times. Definitive codes such as 921 still fail immediately. Fixes #352 --- .../core/tests/highway/highway-client.test.ts | 91 +++++++- .../protocol/src/highway/highway-client.ts | 194 +++++++++++------- 2 files changed, 204 insertions(+), 81 deletions(-) diff --git a/packages/core/tests/highway/highway-client.test.ts b/packages/core/tests/highway/highway-client.test.ts index fca8bc3d..d187658f 100644 --- a/packages/core/tests/highway/highway-client.test.ts +++ b/packages/core/tests/highway/highway-client.test.ts @@ -2,10 +2,12 @@ // // 方案 3(#211):单连接、按 offset 顺序、流水线上传,跨 chunk 复用同一个 // TCP 连接(HTTP keep-alive)。要点: -// - 顺序发送 → 天然保序,避开 QQ highway 对乱序块的 error_code=102902; +// - 顺序发送 → 减少 QQ highway 对重叠块的 NeedDelayRetry(error_code=102902); // - 复用连接 → TCP 拥塞窗口全程保持,省掉每块新建连接的 slow-start。 // 边缘节点可能在响应后 FIN(#118);此时自适应地丢弃 socket + 重连 + 重发 // 同一块(重发幂等),最坏退化成“每块一连接”,不比旧实现差,且仍然保序。 +// 102902 / 302902 不是致命拒绝(#352):官方 BDH 走 NeedDelayRetry,延迟后 +// 换连接重发同一 offset。 // // 本测试用两种 mock 服务端行为锁定这套自适应逻辑: // - keepalive:每个 POST 回一个响应,连接保持 → 整个文件 1 个连接; @@ -36,10 +38,21 @@ function buildEmptyHighwayResponseFrame(): Buffer { return frame; } -// errorCode 帧:RespDataHighwayHead.field3 (errorCode) = 921。tag(field3, -// varint)=0x18,varint(921)=0x99 0x07。定义即拒绝(不重试)。 -function buildErrorCodeFrame(): Buffer { - const head = Buffer.from([0x18, 0x99, 0x07]); +function encodeVarint(n: number): number[] { + const bytes: number[] = []; + let value = n >>> 0; + while (value > 0x7f) { + bytes.push((value & 0x7f) | 0x80); + value >>>= 7; + } + bytes.push(value); + return bytes; +} + +// errorCode 帧:RespDataHighwayHead.field3 (errorCode)。tag(field3, varint)=0x18。 +// 921 是定义即拒绝;102902 / 302902 是 QQ BDH 的 NeedDelayRetry(#352)。 +function buildErrorCodeFrame(errorCode = 921): Buffer { + const head = Buffer.from([0x18, ...encodeVarint(errorCode)]); const frame = Buffer.alloc(9 + head.length + 1); frame[0] = 0x28; frame.writeUInt32BE(head.length, 1); @@ -75,6 +88,7 @@ class FakeSocket extends EventEmitter { private readonly failOnPost = -1, private readonly truncateOnPost = -1, private readonly errorAfterPartialOnPost = -1, + private readonly frameOnPost: Readonly> = {}, ) { super(); } @@ -135,7 +149,7 @@ class FakeSocket extends EventEmitter { this.emit('close'); return; } - this.emit('data', httpWrap(this.responseFrame)); + this.emit('data', httpWrap(this.frameOnPost[thisPost] ?? this.responseFrame)); if (this.mode === 'closeafter') { this.readableEnded = true; this.writable = false; @@ -660,4 +674,69 @@ describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => { // Definitive reject on block 0 → stop immediately, don't PUT later blocks. expect(source.reads.length).toBeLessThan(3); }); + + it('delay-retries 102902 on the same offset, then completes (#352)', async () => { + // QQ BDH NeedDelayRetry: 102902 is backpressure, not a fatal reject. + // Official client delays, switches sender, and re-PUTs the same piece. + installFactory((idx) => idx === 0 + ? new FakeSocket(buildErrorCodeFrame(102902), 'keepalive') + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const entries: LogEntry[] = []; + setLogLevel('trace'); + const unsubscribe = subscribeLogs((entry) => entries.push(entry)); + try { + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); + await uploadHighwayHttp( + makeBridge(), makeSession(), 71, new BufferChunkSource(bytes), + new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).toHaveBeenCalledTimes(2); + const messages = highwayTrace(entries).map((entry) => entry.message); + expect(messages).toEqual(expect.arrayContaining([ + expect.stringContaining('branch=chunk_delay_retry offset=0'), + expect.stringContaining('errorCode=102902'), + expect.stringContaining('outcome=completed reason=upload_complete'), + ])); + } finally { + unsubscribe(); + } + }); + + it('delay-retries 302902 the same way as 102902', async () => { + installFactory((idx) => idx === 0 + ? new FakeSocket(buildErrorCodeFrame(302902), 'keepalive') + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + await uploadHighwayHttp( + makeBridge(), makeSession(), 71, + new BufferChunkSource(new Uint8Array(512 * 1024)), + new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).toHaveBeenCalledTimes(2); + }); + + it('delay-retries 102902 on a later in-order block after keep-alive was already warm (#352 shape)', async () => { + // Mirrors the report: sequential upload is healthy, then a later offset + // returns 102902. Recovery must re-PUT that offset, not abort the file. + installFactory((idx) => idx === 0 + ? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', -1, -1, -1, { + 3: buildErrorCodeFrame(102902), + }) + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks + await uploadHighwayHttp( + makeBridge(), makeSession(), 71, new BufferChunkSource(bytes), + new Uint8Array(16), new Uint8Array(0), + ); + expect(createConnectionMock).toHaveBeenCalledTimes(2); + }); + + it('exhausts delay-retries when 102902 keeps coming back', async () => { + installFactory(() => new FakeSocket(buildErrorCodeFrame(102902), 'keepalive')); + await expect(uploadHighwayHttp( + makeBridge(), makeSession(), 71, + new BufferChunkSource(new Uint8Array(16)), + new Uint8Array(16), new Uint8Array(0), + )).rejects.toThrow(/error_code=102902/); + expect(createConnectionMock.mock.calls.length).toBeGreaterThan(1); + }); }); diff --git a/packages/protocol/src/highway/highway-client.ts b/packages/protocol/src/highway/highway-client.ts index 0650d444..9cca0d72 100644 --- a/packages/protocol/src/highway/highway-client.ts +++ b/packages/protocol/src/highway/highway-client.ts @@ -28,10 +28,20 @@ const HIGHWAY_BLOCK_SIZE = 1024 * 1024; // one-shot TCP connections; QQ's highway edge nodes (and proxies/NAT on the // path) sporadically FIN a fresh connection before responding, so a single // transient close among a 48 MB file's ~48 chunks must not abort the whole -// upload (issue #118). Only transport failures retry — a decoded highway -// error_code is a definitive server reject and is never retried. +// upload (issue #118). Transport failures retry. Most decoded highway +// error_codes are definitive rejects and are never retried — except +// 102902 / 302902, which QQ's own BDH client treats as NeedDelayRetry +// (issue #352; wrapper.node multi_uploader.cc). const HIGHWAY_MAX_CHUNK_ATTEMPTS = 3; const HIGHWAY_RETRY_BASE_MS = 300; +const HIGHWAY_DELAY_RETRY_CODES = new Set([102902, 302902]); +// Official DelayTryNext clamps server uDelayTime to [250, 1200] ms and +// gives up after 33 consecutive delay-retries. We don't currently parse +// uDelayTime out of the highway response, so use the 250 ms floor; 8 +// consecutive delay-retries is enough to ride out the backpressure that +// #352 hits on multi-GiB PUTs without stalling a chunk for ~8 s. +const HIGHWAY_DELAY_RETRY_MS = 250; +const HIGHWAY_MAX_DELAY_RETRIES = 8; // Idle read timeout for a highway response. tcpConnect() clears the socket's // own timeout once connected, so a peer that accepts the connection but then @@ -165,10 +175,11 @@ export function fetchHighwaySession(bridge: BridgeContext): Promise({ msgBaseHead: { - version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes: 0, + version: 1, uin, command: 'PicUp.DataUp', seq: 0, retryTimes, appId: HIGHWAY_APP_ID, dataFlag: 16, commandId, }, msgSegHead: { @@ -482,10 +493,11 @@ async function uploadHighwayHttpOperation( // // Blocks are PUT in STRICT offset order over ONE persistent connection, // reused across chunks via HTTP keep-alive. Two properties matter: - // - In order: QQ's highway server reassembles by offset but REJECTS a - // block that arrives after a later one (error_code=102902) — parallel or - // out-of-order PUTs do not work (proven on a real endpoint). Sequential - // send guarantees in-order arrival. + // - In order: QQ's highway server wants blocks in offset order. Parallel + // PUTs were observed to return error_code=102902 (~20% on a live + // account). That code is NeedDelayRetry in the official BDH client, + // not a fatal "out of order" reject — but sequential send still keeps + // the server from having to delay-retry overlapping pieces. // - One warm connection: reusing the socket keeps the TCP congestion // window open across the whole file instead of paying slow-start on a // fresh connection for every 1 MiB block. That per-block cold start was @@ -497,10 +509,13 @@ async function uploadHighwayHttpOperation( // half-closed after a response, we drop it, reconnect, and re-send the SAME // block (re-PUTting an offset is idempotent). Worst case — a server that // closes after every response — degrades to one connection per block: no - // worse than the #118 behavior, and still strictly in order (so never - // error_code=102902). `connectCount` is logged so a real run reveals which - // regime we hit (1 connection = keep-alive honored; ~chunkCount = closed - // every time). + // worse than the #118 behavior, and still strictly in order. + // + // 102902 / 302902 are a separate recovery path (issue #352): drop the + // socket (official client switches sender IP), wait DelayTryNext's 250 ms + // floor, and re-PUT the same offset. `connectCount` is logged so a real + // run reveals which regime we hit (1 connection = keep-alive honored; + // ~chunkCount = closed every time). // // `source` may buffer the whole file (BufferChunkSource) or stream it from // disk (FileChunkSource); either way one chunk is read/held at a time. We @@ -526,25 +541,41 @@ async function uploadHighwayHttpOperation( } 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); + const rejectServer = (errorCode: number, segRetCode: number): never => { + const fileMd5Hex = Buffer.from(fileMd5).toString('hex'); + trace.failureReason = 'server_rejected'; + trace.error = new Error( + `highway upload error_code=${errorCode}` + + ` (cmdId=${commandId} chunk=${chunkSize}/${totalSize}` + + ` offset=${offset} segRetCode=${segRetCode}` + + ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, + ); + throw trace.error; + }; // Send this block, reusing the live connection when there is one. On any // transport failure (peer FIN between chunks, ECONNRESET, connect // refused/timeout) drop the socket, reconnect, and retry THIS block — // re-sending the same offset range is idempotent on the server. + // 102902 / 302902 take a separate delay-retry path (issue #352). let responseBody: Uint8Array | undefined; - for (let attempt = 1; ; attempt++) { + let transportAttempts = 0; + let delayRetries = 0; + for (;;) { + const retryTimes = transportAttempts + delayRetries; + const attempt = retryTimes + 1; + const head = makeHighwayHead( + bridge.identity.uin, commandId, totalSize, offset, chunkSize, + chunkMd5, fileMd5, session.sigSession, extend, retryTimes, + ); + 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); try { if (!socket) { socket = await tcpConnect(session.host, session.port); @@ -566,7 +597,6 @@ async function uploadHighwayHttpOperation( connectCount, ); responseBody = await httpPostFrame(socket, session.host, pathStr, frame); - break; } catch (err) { if (err instanceof HighwayResponseReadError && err.responseBody) { log.trace(() => [ @@ -578,10 +608,11 @@ async function uploadHighwayHttpOperation( ]); } dropSocket(); - if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { + transportAttempts += 1; + if (transportAttempts >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { trace.failureReason = 'transport_exhausted'; const exhausted = new Error( - `highway upload transport failed after ${attempt} attempts ` + + `highway upload transport failed after ${transportAttempts} attempts ` + `(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`, ); trace.error = exhausted; @@ -591,59 +622,72 @@ async function uploadHighwayHttpOperation( 'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d error=%j', offset, chunkSize, - attempt, + transportAttempts, highwayErrorText(err), ); - await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); + await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts); + continue; } - } - // Unreachable: the retry loop only exits via break (responseBody set) or - // throw — the guard just narrows the type for the compiler. - 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(respHead); - log.trace( - 'highway_put_branch branch=chunk_control_decoded offset=%d errorCode=%d segRetCode=%d', + // Unreachable: httpPostFrame either returns a body or throws. + if (!responseBody) { + trace.failureReason = 'transport_exhausted'; + trace.error = new Error('highway upload: missing response'); + throw trace.error; + } + const body = responseBody; + log.trace(() => [ + 'highway_put_branch branch=chunk_control_response offset=%d bytes=%d responseBytes=%d responseHex=%s', 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 - // 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'); - 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; + chunkSize, + body.byteLength, + renderTraceBytes(body), + ]); + let resp: RespDataHighwayHead; + try { + const { head: respHead } = unpackHighwayFrame(body); + resp = protobuf_decode(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; + } + + const errorCode = resp?.errorCode ?? 0; + const segRetCode = resp?.msgSegHead?.retCode ?? 0; + if (errorCode !== 0 && HIGHWAY_DELAY_RETRY_CODES.has(errorCode)) { + dropSocket(); + delayRetries += 1; + if (delayRetries >= HIGHWAY_MAX_DELAY_RETRIES) { + rejectServer(errorCode, segRetCode); + } + log.trace( + 'highway_put_branch branch=chunk_delay_retry offset=%d bytes=%d attempt=%d errorCode=%d delayMs=%d', + offset, + chunkSize, + delayRetries, + errorCode, + HIGHWAY_DELAY_RETRY_MS, + ); + await sleepMs(HIGHWAY_DELAY_RETRY_MS); + continue; + } + if (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. + rejectServer(errorCode, segRetCode); + } + break; } // If the peer half-closed after sending its response, the socket can no