perf(highway): single-connection pipelined upload — supersede #211 concurrency

The #211 concurrency attempt (c17fff6) was disproven on a live endpoint.
QQ's highway server requires blocks to arrive in offset order and rejects
an out-of-order PUT with error_code=102902 — ~20% failure under a real
account even after deferring the finalize block. Parallel connections
can't guarantee arrival order, so that approach is unshippable.

Replace it with a single persistent connection that PUTs blocks in strict
offset order, reusing the socket across the whole file via HTTP keep-alive:
- In order: the server never sees an out-of-order block, so no 102902.
- One warm connection: the TCP congestion window stays open across the
  file instead of paying slow-start on a fresh connection per 1 MiB block.
  That per-block cold start was the real throughput cap behind #211.

Adaptive to QQ's edge nodes FIN'ing between chunks (the reason #118 went
one-connection-per-chunk): on a transport failure, or a peer half-close
after a response, drop the socket, reconnect, and re-send the SAME block
(re-PUTting an offset is idempotent). Worst case degrades to one
connection per block — no worse than #118, and still strictly in order.

Also fixes a latent bug on the reconnect path, surfaced by review: a
response truncated mid-stream (header arrived, Content-Length unmet, then
FIN) was resolved as a partial frame and then fatally rejected by
unpackHighwayFrame OUTSIDE the retry loop, turning a recoverable mid-body
FIN into a failed upload. A truncated response now rejects as a retryable
transport failure so the block is re-sent. Added an idle read timeout so
a silent peer can't hang the upload forever (the persistent socket widens
that exposure).

Verified live (tempserver, repeated 48 MiB group-file uploads): 1
connection per file, 0 failures across dense repeats, ~1.4x throughput
over the old per-chunk-connection serial path in a low-RTT datacenter —
the win is larger on high-RTT home links where per-block slow-start hurt
most (the original #211 report). Unit tests cover keep-alive reuse,
FIN-after-each-response degradation, mid-stream reconnect+resume, body-
truncation retry, in-order exactly-once coverage, and close-once.
This commit is contained in:
DrSmoothl committed 2026-07-09 13:55:25 +08:00
1 parent c17fff6e2f
commit 7ab91c81e9
2 files changed
+358 -360

No files matched your search

+143 -146
View File
@@ -28,17 +28,13 @@ const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
const HIGHWAY_MAX_CHUNK_ATTEMPTS = 3;
const HIGHWAY_RETRY_BASE_MS = 300;
// Concurrent chunk upload fan-out. A large file's chunks are independent —
// each highway frame is self-contained (its own dataOffset, chunkMd5, fileMd5
// and serviceTicket) and the server reassembles by offset, so chunks can be
// PUT in any order over parallel connections. Uploading them one-at-a-time
// (the old behavior) capped throughput at ~1 chunk / RTT AND paid TCP
// slow-start on every fresh per-chunk connection, so a 1 MiB chunk finished
// before its cold congestion window opened — the upload never reached line
// rate (issue #211). A small pool overlaps the RTT stalls and lets several
// connections ramp their windows at once. Kept modest so we stay a good
// citizen on QQ's highway edge nodes (which rate-limit — see error_code=921).
const HIGHWAY_UPLOAD_CONCURRENCY = 4;
// 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
// neither responds nor FINs would hang the whole upload forever. The single
// persistent connection (issue #211) keeps a socket alive across the whole
// file, widening that exposure, so the response reader arms its own idle timer
// and treats a stall as a retryable transport failure.
const HIGHWAY_READ_IDLE_MS = 30000;
const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
@@ -196,7 +192,18 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
let totalNeeded = 0;
let settled = false;
// 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)'))),
HIGHWAY_READ_IDLE_MS,
);
};
const detach = () => {
if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }
socket.off('data', onData);
socket.off('error', onError);
socket.off('close', onClose);
@@ -208,6 +215,7 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
fn();
};
const onData = (chunk: Buffer) => {
armIdle();
chunks.push(chunk);
const buf = Buffer.concat(chunks);
if (headerEnd < 0) {
@@ -227,17 +235,30 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
const onError = (err: Error) => finish(() => reject(err));
const onClose = () => finish(() => {
const buf = Buffer.concat(chunks);
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
// QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定:
// 第一次 POST 拿到响应后服务器经常立刻 FIN 关闭,下一次写入的请求体
// 走到一个已被对端 close 的 socket 上,触发这里。诊断信息把已收到的
// 字节数和是否解析到 header 一起带出来,便于区分 “连接刚握手就被关”
// 和 “响应读到一半被截断” 两种情况。
else reject(new Error(
`connection closed before response (received=${buf.length}B, headerSeen=${headerEnd >= 0})`
));
// A fully-received body would already have resolved in onData; reaching
// here means the peer FIN'd before the response completed. Only a
// close-delimited body (no Content-Length) is legitimately ended by the
// FIN — resolve that. A declared-but-unmet Content-Length, or a
// half-received header, is a TRUNCATED response: reject it as a
// retryable transport failure so the caller's attempt loop reconnects
// and re-sends this block, instead of resolving a partial frame that
// unpackHighwayFrame would fatally reject OUTSIDE that loop (turning a
// recoverable mid-body FIN into a failed upload).
//
// QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定,常在
// 响应后立刻 FIN;诊断信息带上已收字节数、是否见到 header、需要多少,
// 便于区分 “连接刚握手就被关” 和 “响应读到一半被截断”。
if (headerEnd >= 0 && contentLength === 0) {
resolve(new Uint8Array(buf.subarray(headerEnd)));
} else {
reject(new Error(
`connection closed before full response (received=${buf.length}B, ` +
`headerSeen=${headerEnd >= 0}${headerEnd >= 0 ? `, need=${totalNeeded}` : ''})`,
));
}
});
armIdle();
socket.on('data', onData);
socket.on('error', onError);
socket.on('close', onClose);
@@ -318,142 +339,118 @@ export async function uploadHighwayHttp(
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
const totalSize = source.size;
// Upload exactly one chunk. Extracted verbatim from the old sequential loop
// body — the per-chunk wire behavior is unchanged, only the *scheduling*
// across chunks becomes concurrent (see HIGHWAY_UPLOAD_CONCURRENCY).
// Single-connection, in-order, pipelined upload (issue #211).
//
// 每个 chunk 仍然一个独立的 TCP 连接。
// 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.
// - 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
// the real throughput cap behind #211.
//
// 旧实现整个文件复用同一个 socket,依赖 `Connection: keep-alive` 跑多次
// POST。但 QQ highway 边缘节点(以及链路上的代理/NAT)经常在第一次响应
// 之后立刻 FIN 关闭连接,导致第二个 chunk 写入一个已被对端关闭的 socket,
// `readHttpResponseBody` 立刻收到 `close` 事件并抛 `connection closed
// before response`(#118)。所以每个 chunk 独立建连的不变量必须保留 ——
// 并发只是让多个这样的一次性连接同时在飞,连接之间没有任何共享状态。
// QQ's edge nodes (and proxies/NAT on the path) sometimes FIN between
// chunks — that is what forced the one-connection-per-chunk workaround in
// #118. We handle it adaptively: if reusing the socket fails, or the peer
// 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).
//
// Data safety: `source.read` returns a fresh buffer per call (FileChunkSource
// allocates; BufferChunkSource returns a read-only subarray), and reads are
// positional (offset-addressed), so concurrent reads at distinct offsets are
// race-free. Each chunk computes its own md5 over its own bytes.
const uploadChunk = async (offset: number, chunkSize: number): Promise<void> => {
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<RespDataHighwayHead>(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)}…)`,
);
}
};
// Concurrent worker pool over the chunk range.
//
// Atomicity / consistency: an offset is claimed synchronously — there is NO
// await between reading `nextOffset` and advancing it — so two workers can
// never claim the same chunk, and every byte range is PUT exactly once. On
// the first permanent chunk failure a worker sets `aborted`; peers stop
// pulling new chunks but drain the one already in flight. `worker()` NEVER
// rejects (it captures its error), so `Promise.all` always resolves only
// after every in-flight read/socket has settled — that is what makes it safe
// to `source.close()` in the finally without racing a live read.
//
// Rollback: a thrown upload leaves the server holding an incomplete set of
// chunks that it never finalizes — identical to the pre-concurrency failure
// mode. The caller's publish/finalize step (which makes the file visible)
// only runs when this resolves, so a partial upload is never published.
let nextOffset = 0;
let uploaded = 0;
let aborted = false;
let firstError: Error | null = null;
const worker = async (): Promise<void> => {
while (!aborted) {
const offset = nextOffset;
if (offset >= totalSize) return;
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, totalSize - offset);
nextOffset = offset + chunkSize; // claim — synchronous, race-free
try {
await uploadChunk(offset, chunkSize);
} catch (err) {
aborted = true;
firstError ??= err instanceof Error ? err : new Error(String(err));
return;
}
uploaded += chunkSize;
log.trace('uploaded %d/%d bytes', uploaded, totalSize);
}
};
// `source` may buffer the whole file (BufferChunkSource) or stream it from
// disk (FileChunkSource). We own the source and close it exactly once below,
// only after all workers have settled.
// 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 socket: net.Socket | null = null;
let connectCount = 0;
const dropSocket = (): void => {
if (socket) { socket.destroy(); socket = null; }
};
try {
const chunkCount = Math.max(1, Math.ceil(totalSize / HIGHWAY_BLOCK_SIZE));
const workerCount = Math.min(HIGHWAY_UPLOAD_CONCURRENCY, chunkCount);
await Promise.all(Array.from({ length: workerCount }, () => worker()));
if (firstError) throw firstError;
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);
// 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.
let responseBody: Uint8Array | undefined;
for (let attempt = 1; ; attempt++) {
try {
if (!socket) {
socket = await tcpConnect(session.host, session.port);
connectCount += 1;
}
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
break;
} catch (err) {
dropSocket();
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), reconnecting', offset, attempt, String(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 (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)}…)`,
);
}
// If the peer half-closed after sending its response, the socket can no
// longer carry the next block — drop it now so the next iteration
// reconnects cleanly instead of writing into a dead socket.
if (socket && (socket.destroyed || socket.readableEnded || !socket.writable)) {
dropSocket();
}
offset += chunkSize;
log.trace('uploaded %d/%d bytes', offset, totalSize);
}
succeeded = true;
if (totalSize > 0) {
log.debug('highway upload done: %d bytes over %d connection(s) (cmdId=%d)',
totalSize, connectCount, commandId);
}
} finally {
// Best-effort close — never mask a primary upload error. A close failure
// is only surfaced when the upload itself succeeded.
dropSocket();
try {
await source.close();
} catch (closeErr) {