feat: add configurable parallel video uploads
Allow up to four video upload connections while keeping one connection as the default. Preserve existing messaging interfaces and add configuration controls, reliable failure handling, and upload diagnostics. Closes #569
This commit is contained in:
18 files changed
+1182
-217
No files matched your search
@@ -80,6 +80,7 @@ Use focused tests while iterating. Before handing off a code change, run the ful
|
||||
- **MCP agents:** preserve existing text results, business-error envelopes, default search matching and mode gates when extending the tools. Use the server SDK's `serveStdio` entry to support modern discovery and legacy initialization from the same command; test both with freshly compiled output. Cache hints belong only on bundled catalog discovery, never execution or account data. Keep trace metadata out of action parameters and sensitive data out of diagnostics. Protocol compatibility, tracing and the additive agent features are documented in [AGENT_FEATURES.md](packages/mcp/AGENT_FEATURES.md). Use isolated HTTP and MCP transports in tests; local runtime inspection must not query a live account.
|
||||
- **MCP execution services:** keep background tasks and event connections opt-in. Persist task state before effects, never replay interrupted writes, and finish durable cleanup before draining the protocol on shutdown. Input continuations must retain their original arguments and execute at most once. Event buffers require explicit account binding, bounded storage and visible gaps. Build the bundled message preview through `packages/mcp/scripts/build-message-app.mjs`; loading a preview must not send a message. Test restart, cancellation and legacy compatibility using isolated transports, including the compiled CLI.
|
||||
- **Protocol codecs:** keep the existing Proton integration in tests so they exercise the same transformations as production. Import real implementations; do not duplicate the algorithm in the test.
|
||||
- **Video uploads:** preserve the single-connection default and the additive global setting in [HIGHWAY_UPLOADS.md](packages/protocol/HIGHWAY_UPLOADS.md). Only video bodies opt into parallel chunks. Confirm every chunk before completion, bound both concurrency and lookahead, and drain outstanding reads and requests before closing the source. Keep retries bounded and backpressure changes visible. Test the actual uploader with isolated transports; passing tests do not prove live throughput.
|
||||
- **Native coverage:** `pnpm test:native` is separate from default protocol tests and requires compatible native artifacts. A missing artifact or unavailable target is a reported limitation, not permission to bypass the check.
|
||||
- **Live QQ behavior:** fixture tests and a successful API response do not prove delivery or client rendering. State what was tested locally and what still needs a real client.
|
||||
|
||||
|
||||
@@ -527,6 +527,10 @@ function prepareGlobalSettingsJson(
|
||||
const normalized = normalizeGlobalSettings(raw);
|
||||
const canonical: Record<string, unknown> = { rkey: normalized.rkey };
|
||||
|
||||
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'videoUploadConcurrency')) {
|
||||
canonical.videoUploadConcurrency = normalized.videoUploadConcurrency;
|
||||
}
|
||||
|
||||
// Missing is the existing one-shot migration sentinel: startup scans legacy
|
||||
// onebot*.json only until snowluma.json first carries this key.
|
||||
if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) {
|
||||
|
||||
@@ -2173,6 +2173,11 @@ export async function initWebUI(
|
||||
'save global config failed: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
);
|
||||
|
||||
if (err instanceof RangeError) {
|
||||
return c.json({ success: false, message: err.message }, 400);
|
||||
}
|
||||
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
|
||||
import type { ReqDataHighwayHead, RespDataHighwayHead } from '@snowluma/proto-defs/highway';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
import { packHighwayFrame, unpackHighwayFrame, computeMd5 } from '@snowluma/protocol/highway/utils';
|
||||
import {
|
||||
uploadHighwayHttp,
|
||||
type ChunkSource,
|
||||
type HighwaySession,
|
||||
} from '@snowluma/protocol/highway';
|
||||
|
||||
const { connect } = vi.hoisted(() => ({ connect: vi.fn() }));
|
||||
vi.mock('net', () => ({ default: { createConnection: connect } }));
|
||||
const BLOCK = 1024 * 1024;
|
||||
const bridge = { identity: { uin: '10001' } } as unknown as BridgeContext;
|
||||
const session: HighwaySession = {
|
||||
sigSession: new Uint8Array([1]),
|
||||
sessionKey: new Uint8Array(),
|
||||
servers: [
|
||||
{ host: '192.0.2.1', port: 80 },
|
||||
{ host: '192.0.2.2', port: 80 },
|
||||
],
|
||||
};
|
||||
const turn = () => new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
interface Request {
|
||||
socket: TestSocket;
|
||||
head: ReqDataHighwayHead;
|
||||
bytes: Uint8Array;
|
||||
offset: number;
|
||||
respond(override?: RespDataHighwayHead): void;
|
||||
frame(bytes: Uint8Array): void;
|
||||
disconnect(): void;
|
||||
}
|
||||
let requests: Request[];
|
||||
let sockets: TestSocket[];
|
||||
let active: Set<Request>;
|
||||
let peak: number;
|
||||
let onRequest: (request: Request) => void;
|
||||
|
||||
class TestSocket extends EventEmitter {
|
||||
destroyed = false;
|
||||
readableEnded = false;
|
||||
writable = true;
|
||||
private buffer = Buffer.alloc(0);
|
||||
setTimeout() {
|
||||
return this;
|
||||
}
|
||||
write(data: Uint8Array, callback: (error?: Error) => void): boolean {
|
||||
if (this.destroyed) {
|
||||
callback(new Error('socket closed'));
|
||||
return false;
|
||||
}
|
||||
|
||||
this.buffer = Buffer.concat([this.buffer, data]);
|
||||
const end = this.buffer.indexOf('\r\n\r\n');
|
||||
|
||||
if (end >= 0) {
|
||||
const length = Number(
|
||||
this.buffer
|
||||
.subarray(0, end)
|
||||
.toString()
|
||||
.match(/Content-Length: (\d+)/i)![1],
|
||||
);
|
||||
|
||||
if (this.buffer.length >= end + 4 + length) {
|
||||
const { head, body } = unpackHighwayFrame(
|
||||
this.buffer.subarray(end + 4, end + 4 + length),
|
||||
);
|
||||
const decoded = protobuf_decode<ReqDataHighwayHead>(head);
|
||||
this.buffer = this.buffer.subarray(end + 4 + length);
|
||||
const request: Request = {
|
||||
socket: this,
|
||||
head: decoded,
|
||||
bytes: body,
|
||||
offset: Number(decoded.msgSegHead?.dataOffset ?? 0n),
|
||||
frame: (frame) => {
|
||||
if (this.destroyed) {
|
||||
throw new Error('reply on destroyed socket');
|
||||
}
|
||||
|
||||
active.delete(request);
|
||||
this.emit(
|
||||
'data',
|
||||
Buffer.concat([
|
||||
Buffer.from(
|
||||
`HTTP/1.1 200 OK\r\nContent-Length: ${frame.length}\r\n\r\n`,
|
||||
),
|
||||
frame,
|
||||
]),
|
||||
);
|
||||
},
|
||||
respond: (override = {}) =>
|
||||
request.frame(
|
||||
packHighwayFrame(
|
||||
protobuf_encode<RespDataHighwayHead>({
|
||||
msgBaseHead: { seq: decoded.msgBaseHead?.seq },
|
||||
msgSegHead: {
|
||||
filesize: decoded.msgSegHead?.filesize,
|
||||
dataOffset: decoded.msgSegHead?.dataOffset,
|
||||
dataLength: decoded.msgSegHead?.dataLength,
|
||||
},
|
||||
...override,
|
||||
}),
|
||||
new Uint8Array(),
|
||||
),
|
||||
),
|
||||
disconnect: () => this.emit('error', new Error('ECONNRESET')),
|
||||
};
|
||||
expect([...active].some((item) => item.socket === this)).toBe(false);
|
||||
requests.push(request);
|
||||
active.add(request);
|
||||
peak = Math.max(peak, active.size);
|
||||
// Deliberately respond before the write callback. Real fast peers
|
||||
// can reply while socket.write is still completing.
|
||||
onRequest(request);
|
||||
}
|
||||
}
|
||||
|
||||
callback();
|
||||
return true;
|
||||
}
|
||||
destroy() {
|
||||
if (!this.destroyed) {
|
||||
this.destroyed = true;
|
||||
this.writable = false;
|
||||
|
||||
for (const request of active) {
|
||||
if (request.socket === this) {
|
||||
active.delete(request);
|
||||
}
|
||||
}
|
||||
|
||||
queueMicrotask(() => this.emit('close'));
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
class Source implements ChunkSource {
|
||||
reads: number[] = [];
|
||||
closes = 0;
|
||||
constructor(readonly size: number) {}
|
||||
async read(offset: number, length: number) {
|
||||
this.reads.push(offset);
|
||||
return new Uint8Array(length).fill(offset / BLOCK + 1);
|
||||
}
|
||||
async close() {
|
||||
this.closes += 1;
|
||||
}
|
||||
}
|
||||
|
||||
function upload(source: ChunkSource, concurrency: number) {
|
||||
return uploadHighwayHttp(bridge, session, 1005, source, new Uint8Array(16), new Uint8Array(), {
|
||||
concurrency,
|
||||
});
|
||||
}
|
||||
|
||||
const level = getLogLevel();
|
||||
beforeEach(() => {
|
||||
requests = [];
|
||||
sockets = [];
|
||||
active = new Set();
|
||||
peak = 0;
|
||||
|
||||
onRequest = () => {};
|
||||
|
||||
connect.mockReset().mockImplementation((_options, listener) => {
|
||||
const socket = new TestSocket();
|
||||
sockets.push(socket);
|
||||
setImmediate(listener);
|
||||
return socket;
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
setLogLevel(level);
|
||||
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
describe('bounded parallel highway uploads', () => {
|
||||
it.each([2, 3, 4])(
|
||||
'uses %i connections, accepts out-of-order acknowledgements and sends the tail last',
|
||||
async (concurrency) => {
|
||||
const source = new Source(6 * BLOCK + 17);
|
||||
const confirmed = new Set<number>();
|
||||
|
||||
const checkAndAck = (request: Request) => {
|
||||
if (request.offset === 6 * BLOCK) {
|
||||
expect(confirmed.size).toBe(6);
|
||||
}
|
||||
|
||||
expect(request.bytes.every((byte) => byte === request.offset / BLOCK + 1)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(Buffer.from(request.head.msgSegHead!.md5!)).toEqual(
|
||||
Buffer.from(computeMd5(request.bytes)),
|
||||
);
|
||||
confirmed.add(request.offset);
|
||||
request.respond();
|
||||
};
|
||||
|
||||
const result = upload(source, concurrency);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(concurrency));
|
||||
expect(source.closes).toBe(0);
|
||||
onRequest = checkAndAck;
|
||||
|
||||
for (const request of [...active].reverse()) {
|
||||
checkAndAck(request);
|
||||
}
|
||||
|
||||
await result;
|
||||
expect(peak).toBe(concurrency);
|
||||
expect(sockets).toHaveLength(concurrency);
|
||||
expect(requests).toHaveLength(7);
|
||||
expect(new Set(requests.map((request) => request.head.msgBaseHead?.seq)).size).toBe(7);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('logs confirmed bytes separately from the contiguous prefix after out-of-order replies', async () => {
|
||||
const entries: LogEntry[] = [];
|
||||
setLogLevel('trace');
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
const source = new Source(3 * BLOCK + 1);
|
||||
|
||||
try {
|
||||
const result = upload(source, 3);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(3));
|
||||
requests[2].respond();
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
entries.some((entry) =>
|
||||
entry.message.includes('acknowledgedBytes=1048576 contiguousBytes=0'),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
expect(requests).toHaveLength(3);
|
||||
onRequest = (request) => request.respond();
|
||||
requests[1].respond();
|
||||
requests[0].respond();
|
||||
await result;
|
||||
const terminal = entries.filter((entry) =>
|
||||
entry.message.startsWith('highway_put_terminal '),
|
||||
);
|
||||
expect(terminal).toHaveLength(1);
|
||||
expect(terminal[0]?.message).toContain(`uploadedBytes=${source.size}`);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
it('surfaces repeated backpressure after the retry budget is exhausted', async () => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset === 0) {
|
||||
request.respond({ errorCode: 102902 });
|
||||
} else {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
await expect(upload(source, 3)).rejects.toThrow(/error_code=102902/);
|
||||
expect(requests.filter((request) => request.offset === 0)).toHaveLength(8);
|
||||
expect(requests.some((request) => request.offset === 3 * BLOCK)).toBe(false);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('limits lookahead behind a slow chunk and recovers an idle connection failure', async () => {
|
||||
const source = new Source(14 * BLOCK + 1);
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset !== 0) {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
const result = upload(source, 4);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(10));
|
||||
await turn();
|
||||
expect(Math.max(...requests.map((request) => request.offset))).toBe(9 * BLOCK);
|
||||
const idle = sockets.find(
|
||||
(socket) => ![...active].some((request) => request.socket === socket),
|
||||
)!;
|
||||
idle.emit('error', new Error('idle connection reset'));
|
||||
onRequest = (request) => request.respond();
|
||||
requests[0].respond();
|
||||
await result;
|
||||
expect(requests).toHaveLength(15);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('retries only the unconfirmed range after a transport failure', async () => {
|
||||
const source = new Source(6 * BLOCK);
|
||||
let failed = false;
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset === BLOCK && !failed) {
|
||||
failed = true;
|
||||
request.disconnect();
|
||||
} else {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
await upload(source, 3);
|
||||
const retried = requests.filter((request) => request.offset === BLOCK);
|
||||
expect(retried).toHaveLength(2);
|
||||
expect(retried[1].bytes).toEqual(retried[0].bytes);
|
||||
expect(retried[1].head.msgBaseHead?.retryTimes).toBe(1);
|
||||
expect(retried[1].head.msgBaseHead?.seq).not.toBe(retried[0].head.msgBaseHead?.seq);
|
||||
expect(source.reads).toHaveLength(6);
|
||||
expect(requests.filter((request) => request.offset !== BLOCK)).toHaveLength(5);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it.each([102902, 302902])(
|
||||
'drains in-flight requests and reduces concurrency on %i',
|
||||
async (code) => {
|
||||
const source = new Source(7 * BLOCK);
|
||||
const entries: LogEntry[] = [];
|
||||
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
|
||||
|
||||
try {
|
||||
const result = upload(source, 4);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(4));
|
||||
requests[0].respond({ errorCode: code });
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
entries.some((entry) =>
|
||||
entry.message.includes('reducing concurrency from 4 to 1'),
|
||||
),
|
||||
).toBe(true),
|
||||
);
|
||||
await turn();
|
||||
expect(requests).toHaveLength(4);
|
||||
let afterDrainPeak = 0;
|
||||
|
||||
onRequest = (request) => {
|
||||
afterDrainPeak = Math.max(afterDrainPeak, active.size);
|
||||
request.respond();
|
||||
};
|
||||
|
||||
for (const request of [...active]) {
|
||||
request.respond();
|
||||
}
|
||||
|
||||
await result;
|
||||
expect(afterDrainPeak).toBe(1);
|
||||
expect(requests.filter((request) => request.offset === 0)).toHaveLength(2);
|
||||
expect(requests).toHaveLength(8);
|
||||
expect(source.closes).toBe(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ msgBaseHead: { seq: 999 } },
|
||||
{ msgSegHead: { dataOffset: 99n } },
|
||||
{ msgSegHead: { dataLength: 99 } },
|
||||
{ msgSegHead: { filesize: 99n } },
|
||||
])('rejects mismatched acknowledgements without retrying (case %#)', async (response) => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
onRequest = (request) => request.respond(response);
|
||||
await expect(upload(source, 3)).rejects.toThrow(/acknowledgement mismatch/);
|
||||
expect(requests.every((request) => (request.head.msgBaseHead?.retryTimes ?? 0) === 0)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(requests.some((request) => request.offset === 3 * BLOCK)).toBe(false);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects segment-level errors even when the top-level code is zero', async () => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
onRequest = (request) => request.respond({ msgSegHead: { retCode: 921 } });
|
||||
await expect(upload(source, 3)).rejects.toThrow(/segRetCode=921/);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it('stops peers on rejection and waits for pending source reads before closing', async () => {
|
||||
let release!: () => void;
|
||||
let reading = false;
|
||||
const source = new Source(5 * BLOCK);
|
||||
const read = source.read.bind(source);
|
||||
|
||||
source.read = async (offset, length) => {
|
||||
if (offset === BLOCK) {
|
||||
reading = true;
|
||||
await new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
reading = false;
|
||||
}
|
||||
|
||||
return read(offset, length);
|
||||
};
|
||||
|
||||
const close = vi.spyOn(source, 'close').mockImplementation(async () => {
|
||||
expect(reading).toBe(false);
|
||||
});
|
||||
const result = upload(source, 3);
|
||||
const rejected = expect(result).rejects.toThrow(/error_code=921/);
|
||||
await vi.waitFor(() => expect(requests).toHaveLength(2));
|
||||
requests.find((request) => request.offset === 0)!.respond({ errorCode: 921 });
|
||||
await turn();
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
release();
|
||||
await rejected;
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(sockets.every((socket) => socket.destroyed)).toBe(true);
|
||||
});
|
||||
|
||||
it('stops after bounded transport retries without sending the final chunk', async () => {
|
||||
const source = new Source(5 * BLOCK);
|
||||
|
||||
onRequest = (request) => {
|
||||
if (request.offset === 0) {
|
||||
request.disconnect();
|
||||
} else {
|
||||
request.respond();
|
||||
}
|
||||
};
|
||||
|
||||
await expect(upload(source, 3)).rejects.toThrow(/transport failed after 3 attempts/);
|
||||
expect(requests.filter((request) => request.offset === 0)).toHaveLength(3);
|
||||
expect(requests.some((request) => request.offset === 4 * BLOCK)).toBe(false);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
|
||||
it.each([1, BLOCK + 1, 2 * BLOCK])('keeps a %i-byte upload on one connection', async (size) => {
|
||||
onRequest = (request) => request.respond();
|
||||
await upload(new Source(size), 4);
|
||||
expect(peak).toBe(1);
|
||||
expect(sockets).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps legacy success responses without echo fields compatible', async () => {
|
||||
onRequest = (request) => request.respond({ msgBaseHead: undefined, msgSegHead: undefined });
|
||||
await upload(new Source(4 * BLOCK), 3);
|
||||
expect(requests).toHaveLength(4);
|
||||
});
|
||||
|
||||
it.each([0, 5, -1, 1.5, NaN])(
|
||||
'rejects invalid concurrency %s and closes the source',
|
||||
async (concurrency) => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
await expect(upload(source, concurrency)).rejects.toThrow(/integer from 1 to 4/);
|
||||
expect(source.closes).toBe(1);
|
||||
expect(requests).toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects short reads instead of acknowledging bytes that were not uploaded', async () => {
|
||||
const source = new Source(4 * BLOCK);
|
||||
source.read = async () => new Uint8Array(1);
|
||||
await expect(upload(source, 3)).rejects.toThrow(/expected 1048576/);
|
||||
expect(requests).toHaveLength(0);
|
||||
expect(source.closes).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -132,6 +132,36 @@ describe('pipeline — runNtv2Upload', () => {
|
||||
setLogLevel(previousLogLevel);
|
||||
});
|
||||
|
||||
it('passes concurrency only for the sub-file that explicitly opts in', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
upload: {
|
||||
uKey: 'main-key',
|
||||
subFileInfos: [{ uKey: 'cover-key' }],
|
||||
msgInfo: { msgInfoBody: [{}, {}], extBizInfo: {} },
|
||||
},
|
||||
}),
|
||||
});
|
||||
const media = {
|
||||
bytes: new Uint8Array([1]),
|
||||
md5: new Uint8Array(16),
|
||||
sha1: new Uint8Array(20),
|
||||
};
|
||||
await runNtv2Upload(
|
||||
baseParams({
|
||||
bridge,
|
||||
uploads: [
|
||||
{ ...media, source: 'top', cmdId: 1005, concurrency: 4 },
|
||||
{ ...media, source: 0, cmdId: 1006 },
|
||||
],
|
||||
}),
|
||||
);
|
||||
const calls = vi.mocked(highway.uploadHighwayHttp).mock.calls;
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]?.[6]).toEqual({ concurrency: 4 });
|
||||
expect(calls[1]?.[6]).toBeUndefined();
|
||||
});
|
||||
|
||||
it('records fast-upload selection and one completed media terminal', async () => {
|
||||
const bridge = makeBridge({
|
||||
responseData: encodeOidbResponse({
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
getVideoUploadConcurrency,
|
||||
setVideoUploadConcurrency,
|
||||
} from '@snowluma/protocol/highway/upload-settings';
|
||||
// video-upload tests cover the fingerprint (fast-upload) path. The
|
||||
// regular load path exercises ffmpeg + the OS temp dir + a streaming
|
||||
// SHA1 implementation; that machinery has its own seams worth testing
|
||||
@@ -9,7 +13,7 @@
|
||||
// fastOnlyError difference (main has it; thumb doesn't — FALLBACK_THUMB
|
||||
// always provides bytes), and the video-specific OIDB fields.
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { promises as fsp } from 'fs';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
@@ -44,11 +48,27 @@ const FINGERPRINT = {
|
||||
} as any;
|
||||
|
||||
describe('video-upload', () => {
|
||||
afterEach(() => setVideoUploadConcurrency(1));
|
||||
beforeEach(() => {
|
||||
vi.mocked(pipeline.runNtv2Upload).mockClear();
|
||||
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
|
||||
});
|
||||
|
||||
it('snapshots the global concurrency for video bodies without parallelizing covers', async () => {
|
||||
expect(getVideoUploadConcurrency()).toBe(1);
|
||||
setVideoUploadConcurrency(4);
|
||||
const first = uploadVideoMsgInfo({} as any, true, 12345, FINGERPRINT);
|
||||
setVideoUploadConcurrency(2);
|
||||
await first;
|
||||
const firstUpload = vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0];
|
||||
expect(firstUpload.uploads[0]!.concurrency).toBe(4);
|
||||
expect(firstUpload.uploads[1]!.concurrency).toBeUndefined();
|
||||
await uploadVideoMsgInfo({} as any, false, 'recipient-uid', FINGERPRINT);
|
||||
const secondUpload = vi.mocked(pipeline.runNtv2Upload).mock.calls[1]![0];
|
||||
expect(secondUpload.uploads[0]!.concurrency).toBe(2);
|
||||
expect(secondUpload.uploads[1]!.concurrency).toBeUndefined();
|
||||
});
|
||||
|
||||
it('retains successful upload metadata for self-sent history', async () => {
|
||||
const node = { fileUuid: 'uploaded-resource', storeId: 1, info: { fileSize: 1234 } };
|
||||
vi.mocked(pipeline.runNtv2Upload).mockResolvedValueOnce({
|
||||
|
||||
@@ -679,6 +679,23 @@ describe('prepareRestorePlan — strict semantic preflight', () => {
|
||||
expect(canonical.webuiTls.enabled).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves video concurrency in backups and rejects invalid restored values', () => {
|
||||
const prepare = (videoUploadConcurrency: number) =>
|
||||
prepareRestorePlan(
|
||||
backupWith({
|
||||
'snowluma.json': {
|
||||
encoding: 'utf8',
|
||||
data: JSON.stringify({ videoUploadConcurrency }),
|
||||
},
|
||||
}),
|
||||
{ restoreCredentials: false, readCurrent: () => null },
|
||||
);
|
||||
expect(JSON.parse(prepare(4).restore[0].data.toString('utf8')).videoUploadConcurrency).toBe(
|
||||
4,
|
||||
);
|
||||
expect(() => prepare(5)).toThrow(/videoUploadConcurrency/);
|
||||
});
|
||||
|
||||
it('accepts owner-supported whitespace trimming without accepting changed values', () => {
|
||||
const prepared = prepareRestorePlan(
|
||||
backupWith({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { validateUploadConcurrency } from '@snowluma/protocol/highway/upload-settings';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
@@ -20,10 +21,12 @@ export interface GlobalSettings {
|
||||
/** Music-card signing service URL. Deployment-wide (same service for every
|
||||
* account), so global rather than per-UIN. Empty = use the built-in default. */
|
||||
musicSignUrl: string;
|
||||
/** Video upload connections, 1–4. Omitted by older callers means one. */
|
||||
videoUploadConcurrency?: number;
|
||||
}
|
||||
|
||||
export function defaultGlobalSettings(): GlobalSettings {
|
||||
return { rkey: { fallbackServers: [] }, musicSignUrl: '' };
|
||||
return { rkey: { fallbackServers: [] }, musicSignUrl: '', videoUploadConcurrency: 1 };
|
||||
}
|
||||
|
||||
/** Keep only well-formed, deduped http(s) URLs (must parse + have a host). */
|
||||
@@ -86,6 +89,10 @@ export function normalizeGlobalSettings(value: unknown): GlobalSettings {
|
||||
out.musicSignUrl = v && isHttpUrl(v) ? v : '';
|
||||
}
|
||||
|
||||
if ('videoUploadConcurrency' in value) {
|
||||
out.videoUploadConcurrency = validateUploadConcurrency(value.videoUploadConcurrency);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -98,6 +105,11 @@ export function loadGlobalSettings(): GlobalSettings {
|
||||
const raw = fs.readFileSync(GLOBAL_CONFIG_PATH, 'utf8');
|
||||
return normalizeGlobalSettings(JSON.parse(raw) as unknown);
|
||||
} catch (err) {
|
||||
if (err instanceof RangeError) {
|
||||
log.error('invalid global upload settings: %s', err.message);
|
||||
throw err;
|
||||
}
|
||||
|
||||
log.warn(
|
||||
'config/snowluma.json is corrupt and will be ignored: %s',
|
||||
err instanceof Error ? err.message : String(err),
|
||||
@@ -120,6 +132,12 @@ export function saveGlobalSettings(incoming: unknown): GlobalSettings {
|
||||
merged.rkey.fallbackServers = normalizeRkeyServers(incoming.rkey.fallbackServers);
|
||||
}
|
||||
|
||||
if ('videoUploadConcurrency' in incoming) {
|
||||
merged.videoUploadConcurrency = validateUploadConcurrency(
|
||||
incoming.videoUploadConcurrency,
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof incoming.musicSignUrl === 'string') {
|
||||
const v = incoming.musicSignUrl.trim();
|
||||
merged.musicSignUrl = v && isHttpUrl(v) ? v : '';
|
||||
@@ -137,6 +155,7 @@ function toJson(settings: GlobalSettings): JsonObject {
|
||||
return {
|
||||
rkey: { fallbackServers: settings.rkey.fallbackServers },
|
||||
musicSignUrl: settings.musicSignUrl,
|
||||
videoUploadConcurrency: settings.videoUploadConcurrency ?? 1,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { setVideoUploadConcurrency } from '@snowluma/protocol/highway/upload-settings';
|
||||
import { createLogger, runWithoutRequestContext } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface, BridgeSessionSource } from '@snowluma/core/bridge-interface';
|
||||
import { loadOneBotConfig, OneBotConfigValidationError } from './config';
|
||||
@@ -155,6 +156,7 @@ export class OneBotManager {
|
||||
private readonly sessionReleaseDeadlineMs: number;
|
||||
|
||||
constructor(options: OneBotManagerOptions = {}) {
|
||||
setVideoUploadConcurrency(loadGlobalSettings().videoUploadConcurrency ?? 1);
|
||||
const envRaw = process.env[SESSION_RELEASE_DEADLINE_ENV];
|
||||
|
||||
if (
|
||||
@@ -267,6 +269,7 @@ export class OneBotManager {
|
||||
* them to every live instance. Called after the WebUI saves global config. */
|
||||
reloadGlobalSettings(): void {
|
||||
const globalSettings = loadGlobalSettings();
|
||||
setVideoUploadConcurrency(globalSettings.videoUploadConcurrency ?? 1);
|
||||
|
||||
for (const instance of this.instances.values()) {
|
||||
instance.applyGlobalSettings(globalSettings);
|
||||
|
||||
@@ -29,8 +29,13 @@ describe('global-config (config/snowluma.json)', () => {
|
||||
expect(defaultGlobalSettings()).toEqual({
|
||||
rkey: { fallbackServers: [] },
|
||||
musicSignUrl: '',
|
||||
videoUploadConcurrency: 1,
|
||||
});
|
||||
expect(loadGlobalSettings()).toEqual({
|
||||
rkey: { fallbackServers: [] },
|
||||
musicSignUrl: '',
|
||||
videoUploadConcurrency: 1,
|
||||
});
|
||||
expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
|
||||
});
|
||||
|
||||
it('keeps only well-formed http(s) URLs, trims, and dedupes', () => {
|
||||
@@ -55,10 +60,12 @@ describe('global-config (config/snowluma.json)', () => {
|
||||
expect(normalizeGlobalSettings({ rkey: 'nope' })).toEqual({
|
||||
rkey: { fallbackServers: [] },
|
||||
musicSignUrl: '',
|
||||
videoUploadConcurrency: 1,
|
||||
});
|
||||
expect(normalizeGlobalSettings(null)).toEqual({
|
||||
rkey: { fallbackServers: [] },
|
||||
musicSignUrl: '',
|
||||
videoUploadConcurrency: 1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -74,6 +81,7 @@ describe('global-config (config/snowluma.json)', () => {
|
||||
expect(onDisk).toEqual({
|
||||
rkey: { fallbackServers: ['https://r.example/rkey'] },
|
||||
musicSignUrl: '',
|
||||
videoUploadConcurrency: 1,
|
||||
});
|
||||
|
||||
expect(loadGlobalSettings().rkey.fallbackServers).toEqual(['https://r.example/rkey']);
|
||||
@@ -100,6 +108,37 @@ describe('global-config (config/snowluma.json)', () => {
|
||||
expect(loadGlobalSettings().musicSignUrl).toBe('https://s.example/c');
|
||||
});
|
||||
|
||||
it.each([1, 2, 3, 4])('persists %i video connections and preserves partial saves', (value) => {
|
||||
expect(saveGlobalSettings({ videoUploadConcurrency: value }).videoUploadConcurrency).toBe(
|
||||
value,
|
||||
);
|
||||
saveGlobalSettings({ musicSignUrl: 'https://sign.example/card' });
|
||||
expect(loadGlobalSettings().videoUploadConcurrency).toBe(value);
|
||||
});
|
||||
|
||||
it.each([0, 5, -1, 1.5, '2', null, false])(
|
||||
'rejects invalid video concurrency %j without writing',
|
||||
(value) => {
|
||||
saveGlobalSettings({ videoUploadConcurrency: 3 });
|
||||
const file = path.join(tempDir, 'config', 'snowluma.json');
|
||||
const before = fs.readFileSync(file, 'utf8');
|
||||
expect(() => saveGlobalSettings({ videoUploadConcurrency: value })).toThrow(
|
||||
/integer from 1 to 4/,
|
||||
);
|
||||
expect(fs.readFileSync(file, 'utf8')).toBe(before);
|
||||
expect(() => normalizeGlobalSettings({ videoUploadConcurrency: value })).toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it('reports an invalid persisted concurrency instead of silently ignoring it', () => {
|
||||
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(tempDir, 'config', 'snowluma.json'),
|
||||
JSON.stringify({ videoUploadConcurrency: 99 }),
|
||||
);
|
||||
expect(() => loadGlobalSettings()).toThrow(/videoUploadConcurrency/);
|
||||
});
|
||||
|
||||
describe('migrateGlobalSettings (musicSignUrl copy-up)', () => {
|
||||
function writeOnebot(file: string, body: unknown) {
|
||||
const dir = path.join(tempDir, 'config');
|
||||
@@ -167,6 +206,10 @@ describe('global-config (config/snowluma.json)', () => {
|
||||
it('falls back to defaults when the file is corrupt', () => {
|
||||
fs.mkdirSync(path.join(tempDir, 'config'), { recursive: true });
|
||||
fs.writeFileSync(path.join(tempDir, 'config', 'snowluma.json'), '{ not json', 'utf8');
|
||||
expect(loadGlobalSettings()).toEqual({ rkey: { fallbackServers: [] }, musicSignUrl: '' });
|
||||
expect(loadGlobalSettings()).toEqual({
|
||||
rkey: { fallbackServers: [] },
|
||||
musicSignUrl: '',
|
||||
videoUploadConcurrency: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,8 @@
|
||||
import * as globalConfig from '../src/global-config';
|
||||
import {
|
||||
getVideoUploadConcurrency,
|
||||
setVideoUploadConcurrency,
|
||||
} from '@snowluma/protocol/highway/upload-settings';
|
||||
import { currentRequestId, runWithRequestId } from '@snowluma/common/logger';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { OneBotManager } from '../src/manager';
|
||||
@@ -13,6 +18,27 @@ function config(trigger: string): OneBotConfig {
|
||||
}
|
||||
|
||||
describe('OneBotManager config apply value ownership', () => {
|
||||
it('applies video concurrency at startup and reloads it even with no active accounts', () => {
|
||||
const load = vi.spyOn(globalConfig, 'loadGlobalSettings').mockReturnValue({
|
||||
...globalConfig.defaultGlobalSettings(),
|
||||
videoUploadConcurrency: 3,
|
||||
});
|
||||
|
||||
try {
|
||||
const manager = new OneBotManager();
|
||||
expect(getVideoUploadConcurrency()).toBe(3);
|
||||
load.mockReturnValue({
|
||||
...globalConfig.defaultGlobalSettings(),
|
||||
videoUploadConcurrency: 2,
|
||||
});
|
||||
manager.reloadGlobalSettings();
|
||||
expect(getVideoUploadConcurrency()).toBe(2);
|
||||
} finally {
|
||||
load.mockRestore();
|
||||
setVideoUploadConcurrency(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('passes each concurrent caller exact config value to the instance', async () => {
|
||||
const manager = new OneBotManager();
|
||||
const seen: OneBotConfig[] = [];
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Video upload connections
|
||||
|
||||
Video uploads use one connection by default. In **Settings → Global configuration →
|
||||
Video upload connections**, choose 1, 2, 3 or 4 connections. The equivalent setting
|
||||
in `config/snowluma.json` is:
|
||||
|
||||
```json
|
||||
{
|
||||
"videoUploadConcurrency": 1
|
||||
}
|
||||
```
|
||||
|
||||
The setting applies to all accounts. Saving through the WebUI affects the next
|
||||
video upload; uploads already preparing or sending retain their original value.
|
||||
Restart SnowLuma after editing the file manually. Missing values in older
|
||||
configurations mean one connection. Invalid values are reported, not clamped.
|
||||
Partial configuration saves and configuration backups preserve this setting.
|
||||
|
||||
Parallelism applies only to video bodies. Covers, images, voice messages and file
|
||||
uploads retain their existing behavior. Videos no larger than 2 MiB still use one
|
||||
connection. The final video chunk waits until all preceding chunks are confirmed.
|
||||
The setting does not change OneBot actions, message segments or response shapes.
|
||||
|
||||
An interrupted connection retries only its unconfirmed chunk, within a bounded
|
||||
retry budget. Known server backpressure reduces that upload to one active request
|
||||
and retries after a delay. A server rejection, invalid acknowledgement or exhausted
|
||||
retry budget fails the upload. A failed upload is never silently reported as sent.
|
||||
|
||||
Debug logs separate video preparation from transfer duration and report requested
|
||||
and effective concurrency, connections and retries. Trace logs include per-chunk
|
||||
attempts, acknowledgement progress and failure context. Higher concurrency does
|
||||
not guarantee a particular speed; compare the same file and network conditions,
|
||||
excluding cached uploads, before drawing performance conclusions.
|
||||
|
||||
Regression tests use isolated transports and cover concurrency bounds,
|
||||
out-of-order acknowledgements, a stalled early chunk, retry exhaustion, backpressure
|
||||
and cleanup. They do not establish real QQ delivery or upload throughput.
|
||||
@@ -18,6 +18,7 @@ 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 { validateUploadConcurrency } from './upload-settings';
|
||||
import { computeMd5, packHighwayFrame, unpackHighwayFrame } from './utils';
|
||||
|
||||
const log = createLogger('Highway');
|
||||
@@ -26,11 +27,9 @@ const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
const HIGHWAY_CONNECT_TIMEOUT_MS = 3000;
|
||||
const HIGHWAY_CONNECT_BUDGET_MS = 10000;
|
||||
|
||||
// Per-chunk transport retry. A large file uploads as many sequential
|
||||
// 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). Transport failures retry. Most decoded highway
|
||||
// Per-chunk transport retry: a transient connection failure retries only
|
||||
// the unconfirmed offset, preserving acknowledged data (issue #118).
|
||||
// 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).
|
||||
@@ -53,7 +52,22 @@ const HIGHWAY_MAX_DELAY_RETRIES = 8;
|
||||
// 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));
|
||||
function sleepMs(ms: number, signal: AbortSignal): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(signal.reason);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
export const PRIVATE_IMAGE_CMD_ID = 1003;
|
||||
export const GROUP_IMAGE_CMD_ID = 1004;
|
||||
@@ -74,6 +88,8 @@ function ipv4ToString(value: number): string {
|
||||
}
|
||||
|
||||
type HighwayPutFailureReason =
|
||||
| 'invalid_options'
|
||||
| 'ack_mismatch'
|
||||
| 'connect_exhausted'
|
||||
| 'control_decode_failed'
|
||||
| 'server_rejected'
|
||||
@@ -218,13 +234,14 @@ function makeHighwayHead(
|
||||
sigSession: Uint8Array,
|
||||
extend: Uint8Array,
|
||||
retryTimes = 0,
|
||||
sequence = 0,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<ReqDataHighwayHead>({
|
||||
msgBaseHead: {
|
||||
version: 1,
|
||||
uin,
|
||||
command: 'PicUp.DataUp',
|
||||
seq: 0,
|
||||
seq: sequence,
|
||||
retryTimes,
|
||||
appId: HIGHWAY_APP_ID,
|
||||
dataFlag: 16,
|
||||
@@ -291,52 +308,57 @@ export function buildHighwayExtend(
|
||||
|
||||
// --- TCP-based HTTP highway upload ---
|
||||
|
||||
function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise<net.Socket> {
|
||||
function tcpConnect(
|
||||
host: string,
|
||||
port: number,
|
||||
timeoutMs: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<net.Socket> {
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const onTimeout = () => {
|
||||
const cleanup = () => {
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
};
|
||||
|
||||
const fail = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
cleanup();
|
||||
socket.destroy();
|
||||
reject(new Error('TCP connect timeout'));
|
||||
};
|
||||
|
||||
const onError = (err: Error) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
socket.destroy();
|
||||
reject(err);
|
||||
reject(error);
|
||||
};
|
||||
|
||||
const onTimeout = () => fail(new Error('TCP connect timeout'));
|
||||
const onError = (error: Error) => fail(error);
|
||||
const onAbort = () => fail(signal.reason);
|
||||
const socket = net.createConnection({ host, port }, () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
// Drop the connect-only listeners so subsequent IO errors / idle
|
||||
// timeouts don't try to reject this already-resolved promise.
|
||||
socket.setTimeout(0);
|
||||
socket.removeListener('timeout', onTimeout);
|
||||
socket.removeListener('error', onError);
|
||||
cleanup();
|
||||
resolve(socket);
|
||||
});
|
||||
socket.setTimeout(timeoutMs);
|
||||
socket.once('timeout', onTimeout);
|
||||
socket.once('error', onError);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function connectHighway(
|
||||
servers: HighwayServer[],
|
||||
startIndex = 0,
|
||||
startIndex: number,
|
||||
signal: AbortSignal,
|
||||
): Promise<{ socket: net.Socket; server: HighwayServer; serverIndex: number }> {
|
||||
const deadline = Date.now() + HIGHWAY_CONNECT_BUDGET_MS;
|
||||
const errors: Error[] = [];
|
||||
@@ -355,9 +377,11 @@ async function connectHighway(
|
||||
server.host,
|
||||
server.port,
|
||||
Math.min(HIGHWAY_CONNECT_TIMEOUT_MS, remaining),
|
||||
signal,
|
||||
);
|
||||
return { socket, server, serverIndex };
|
||||
} catch (cause) {
|
||||
signal.throwIfAborted();
|
||||
const error = new Error(`${server.host}:${server.port}: ${highwayErrorText(cause)}`, {
|
||||
cause,
|
||||
});
|
||||
@@ -378,7 +402,8 @@ function socketWrite(socket: net.Socket, data: Uint8Array): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
function readHttpResponseBody(socket: net.Socket, signal: AbortSignal): Promise<Uint8Array> {
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let headerEnd = -1;
|
||||
@@ -426,6 +451,7 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
socket.off('data', onData);
|
||||
socket.off('error', onError);
|
||||
socket.off('close', onClose);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
};
|
||||
|
||||
const finish = (fn: () => void) => {
|
||||
@@ -460,6 +486,7 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = () => finish(() => reject(signal.reason));
|
||||
const onError = (err: Error) =>
|
||||
finish(() => {
|
||||
const responseBody = partialResponseBody();
|
||||
@@ -505,6 +532,7 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
socket.on('data', onData);
|
||||
socket.on('error', onError);
|
||||
socket.on('close', onClose);
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -513,15 +541,40 @@ async function httpPostFrame(
|
||||
host: string,
|
||||
path: string,
|
||||
body: Uint8Array,
|
||||
signal: AbortSignal,
|
||||
): Promise<Uint8Array> {
|
||||
const header = `POST ${path} HTTP/1.1\r\nHost: ${host}\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\nUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2)\r\nContent-Length: ${body.length}\r\n\r\n`;
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
const responseAbort = new AbortController();
|
||||
|
||||
if (body.length > 0) {
|
||||
await socketWrite(socket, body);
|
||||
const onAbort = () => {
|
||||
responseAbort.abort(signal.reason);
|
||||
socket.destroy();
|
||||
};
|
||||
|
||||
signal.throwIfAborted();
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
// Arm the reader before writing: a fast peer may reply before write callbacks.
|
||||
const response = readHttpResponseBody(socket, responseAbort.signal);
|
||||
const write = (async () => {
|
||||
await socketWrite(socket, Buffer.from(header, 'ascii'));
|
||||
signal.throwIfAborted();
|
||||
|
||||
if (body.length > 0) {
|
||||
await socketWrite(socket, body);
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
const [, result] = await Promise.all([write, response]);
|
||||
return result;
|
||||
} catch (error) {
|
||||
responseAbort.abort(error);
|
||||
socket.destroy();
|
||||
await Promise.allSettled([write, response]);
|
||||
throw error;
|
||||
} finally {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
|
||||
return readHttpResponseBody(socket);
|
||||
}
|
||||
|
||||
// ─────────────── ChunkSource: buffer-or-disk input for highway PUTs ───────────────
|
||||
@@ -595,6 +648,11 @@ export class FileChunkSource implements ChunkSource {
|
||||
}
|
||||
}
|
||||
|
||||
export interface HighwayUploadOptions {
|
||||
/** One connection by default; two to four opt into bounded parallel chunks. */
|
||||
concurrency?: number;
|
||||
}
|
||||
|
||||
export function uploadHighwayHttp(
|
||||
bridge: BridgeContext,
|
||||
session: HighwaySession,
|
||||
@@ -602,6 +660,7 @@ export function uploadHighwayHttp(
|
||||
source: ChunkSource,
|
||||
fileMd5: Uint8Array,
|
||||
extend: Uint8Array,
|
||||
options: HighwayUploadOptions = {},
|
||||
): Promise<void> {
|
||||
const state: HighwayPutTraceState = {
|
||||
startedAt: Date.now(),
|
||||
@@ -628,6 +687,7 @@ export function uploadHighwayHttp(
|
||||
fileMd5,
|
||||
extend,
|
||||
state,
|
||||
options,
|
||||
);
|
||||
log.trace(
|
||||
'highway_put_terminal cmdId=%d outcome=completed reason=upload_complete totalBytes=%d uploadedBytes=%d connections=%d elapsedMs=%d',
|
||||
@@ -661,97 +721,105 @@ async function uploadHighwayHttpOperation(
|
||||
fileMd5: Uint8Array,
|
||||
extend: Uint8Array,
|
||||
trace: HighwayPutTraceState,
|
||||
options: HighwayUploadOptions,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const totalSize = source.size;
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const abort = new AbortController();
|
||||
const { signal } = abort;
|
||||
const wakeups = new Set<() => void>();
|
||||
|
||||
// Single-connection, in-order, pipelined upload (issue #211).
|
||||
//
|
||||
// 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 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
|
||||
// the real throughput cap behind #211.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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
|
||||
// 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;
|
||||
let server = session.servers[0]!;
|
||||
let serverIndex = 0;
|
||||
|
||||
const dropSocket = (): void => {
|
||||
if (socket) {
|
||||
socket.destroy();
|
||||
socket = null;
|
||||
const wake = () => {
|
||||
for (const resolve of wakeups) {
|
||||
resolve();
|
||||
}
|
||||
|
||||
wakeups.clear();
|
||||
};
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
signal.addEventListener('abort', wake, { once: true });
|
||||
|
||||
while (offset < totalSize) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, totalSize - offset);
|
||||
let chunk: Uint8Array;
|
||||
const fail = (reason: HighwayPutFailureReason, error: unknown): never => {
|
||||
if (!signal.aborted) {
|
||||
trace.failureReason = reason;
|
||||
trace.error = error;
|
||||
abort.abort(error);
|
||||
}
|
||||
|
||||
throw signal.reason;
|
||||
};
|
||||
|
||||
interface Worker {
|
||||
id: number;
|
||||
socket: net.Socket | null;
|
||||
serverIndex: number;
|
||||
connections: number;
|
||||
}
|
||||
const workers: Worker[] = [];
|
||||
const running = new Map<number, Promise<Worker>>();
|
||||
let succeeded = false;
|
||||
let sourceCloseFailure: { error: unknown } | undefined;
|
||||
let concurrency = 1;
|
||||
let effectiveConcurrency = 1;
|
||||
let activeRequests = 0;
|
||||
let sequence = 0;
|
||||
let retries = 0;
|
||||
let contiguous = 0;
|
||||
const confirmed = new Set<number>();
|
||||
|
||||
const dropSocket = (worker: Worker) => {
|
||||
worker.socket?.destroy();
|
||||
worker.socket = null;
|
||||
};
|
||||
|
||||
const acquire = async () => {
|
||||
while (activeRequests >= effectiveConcurrency) {
|
||||
signal.throwIfAborted();
|
||||
await new Promise<void>((resolve) => wakeups.add(resolve));
|
||||
}
|
||||
|
||||
signal.throwIfAborted();
|
||||
activeRequests += 1;
|
||||
};
|
||||
|
||||
const sendChunk = async (worker: Worker, piece: number): Promise<Worker> => {
|
||||
const offset = piece * HIGHWAY_BLOCK_SIZE;
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, totalSize - offset);
|
||||
let chunk: Uint8Array;
|
||||
|
||||
try {
|
||||
chunk = await source.read(offset, chunkSize);
|
||||
|
||||
if (chunk.byteLength !== chunkSize) {
|
||||
throw new Error(
|
||||
`highway source returned ${chunk.byteLength} bytes, expected ${chunkSize} at offset ${offset}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
return fail('source_read_failed', error);
|
||||
}
|
||||
|
||||
signal.throwIfAborted();
|
||||
log.trace('highway_put_branch branch=chunk_read offset=%d bytes=%d', offset, chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const rejectServer = (errorCode: number, segRetCode: number): never =>
|
||||
fail(
|
||||
'server_rejected',
|
||||
new Error(
|
||||
`highway upload error_code=${errorCode} (cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset} segRetCode=${segRetCode})`,
|
||||
),
|
||||
);
|
||||
let transportAttempts = 0;
|
||||
let delayRetries = 0;
|
||||
|
||||
for (;;) {
|
||||
await acquire();
|
||||
const retryTimes = transportAttempts + delayRetries;
|
||||
const attempt = retryTimes + 1;
|
||||
const requestSequence = concurrency === 1 ? 0 : ++sequence;
|
||||
const requestStarted = Date.now();
|
||||
|
||||
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 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;
|
||||
let transportAttempts = 0;
|
||||
let delayRetries = 0;
|
||||
|
||||
for (;;) {
|
||||
const retryTimes = transportAttempts + delayRetries;
|
||||
const attempt = retryTimes + 1;
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin,
|
||||
commandId,
|
||||
@@ -763,6 +831,7 @@ async function uploadHighwayHttpOperation(
|
||||
session.sigSession,
|
||||
extend,
|
||||
retryTimes,
|
||||
requestSequence,
|
||||
);
|
||||
log.trace(() => [
|
||||
'highway_put_branch branch=chunk_control_request offset=%d bytes=%d headBytes=%d headHex=%s',
|
||||
@@ -771,91 +840,112 @@ async function uploadHighwayHttpOperation(
|
||||
head.byteLength,
|
||||
renderTraceBytes(head),
|
||||
]);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
let body: Uint8Array;
|
||||
|
||||
try {
|
||||
if (!socket) {
|
||||
({ socket, server, serverIndex } = await connectHighway(
|
||||
session.servers,
|
||||
serverIndex,
|
||||
));
|
||||
if (
|
||||
worker.socket &&
|
||||
(worker.socket.destroyed ||
|
||||
worker.socket.readableEnded ||
|
||||
!worker.socket.writable)
|
||||
) {
|
||||
dropSocket(worker);
|
||||
}
|
||||
|
||||
connectCount += 1;
|
||||
trace.connectCount = connectCount;
|
||||
if (!worker.socket) {
|
||||
const connected = await connectHighway(
|
||||
session.servers,
|
||||
worker.serverIndex,
|
||||
signal,
|
||||
);
|
||||
worker.socket = connected.socket;
|
||||
worker.serverIndex = connected.serverIndex;
|
||||
worker.connections += 1;
|
||||
trace.connectCount += 1;
|
||||
// Idle pooled connections can fail while another worker is active.
|
||||
// Retain an error observer between requests; the next attempt reconnects.
|
||||
const socket = worker.socket;
|
||||
socket.on('error', (error) => {
|
||||
log.trace(
|
||||
'highway_put_branch branch=socket_error worker=%d error=%j',
|
||||
worker.id,
|
||||
highwayErrorText(error),
|
||||
);
|
||||
socket.destroy();
|
||||
});
|
||||
log.trace(
|
||||
'highway_put_branch branch=%s offset=%d attempt=%d connection=%d host=%j port=%d',
|
||||
connectCount === 1 ? 'connect' : 'reconnect',
|
||||
'highway_put_branch branch=%s offset=%d attempt=%d connection=%d worker=%d host=%j port=%d',
|
||||
worker.connections === 1 ? 'connect' : 'reconnect',
|
||||
offset,
|
||||
attempt,
|
||||
connectCount,
|
||||
server.host,
|
||||
server.port,
|
||||
trace.connectCount,
|
||||
worker.id,
|
||||
connected.server.host,
|
||||
connected.server.port,
|
||||
);
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_attempt offset=%d bytes=%d attempt=%d connection=%d',
|
||||
'highway_put_branch branch=chunk_attempt offset=%d bytes=%d attempt=%d connection=%d worker=%d seq=%d',
|
||||
offset,
|
||||
chunkSize,
|
||||
attempt,
|
||||
connectCount,
|
||||
trace.connectCount,
|
||||
worker.id,
|
||||
requestSequence,
|
||||
);
|
||||
responseBody = await httpPostFrame(socket, server.host, pathStr, frame);
|
||||
} catch (err) {
|
||||
if (connectCount === 0) {
|
||||
trace.failureReason = 'connect_exhausted';
|
||||
trace.error = err;
|
||||
throw err;
|
||||
body = await httpPostFrame(
|
||||
worker.socket,
|
||||
session.servers[worker.serverIndex]!.host,
|
||||
pathStr,
|
||||
packHighwayFrame(head, chunk),
|
||||
signal,
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
|
||||
if (worker.connections === 0) {
|
||||
return fail('connect_exhausted', error);
|
||||
}
|
||||
|
||||
if (err instanceof HighwayResponseReadError && err.responseBody) {
|
||||
if (error instanceof HighwayResponseReadError && error.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!),
|
||||
error.responseBody!.byteLength,
|
||||
renderTraceBytes(error.responseBody!),
|
||||
]);
|
||||
}
|
||||
|
||||
dropSocket();
|
||||
dropSocket(worker);
|
||||
transportAttempts += 1;
|
||||
|
||||
if (transportAttempts >= HIGHWAY_MAX_CHUNK_ATTEMPTS) {
|
||||
trace.failureReason = 'transport_exhausted';
|
||||
const exhausted = new Error(
|
||||
`highway upload transport failed after ${transportAttempts} attempts ` +
|
||||
`(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}` +
|
||||
` acknowledgedBytes=${offset}; current chunk unconfirmed): ${String(err)}`,
|
||||
{ cause: err },
|
||||
return fail(
|
||||
'transport_exhausted',
|
||||
new Error(
|
||||
`highway upload transport failed after ${transportAttempts} attempts (cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset} acknowledgedBytes=${trace.uploadedBytes}; current chunk unconfirmed): ${String(error)}`,
|
||||
{ cause: error },
|
||||
),
|
||||
);
|
||||
trace.error = exhausted;
|
||||
throw exhausted;
|
||||
}
|
||||
|
||||
// Keep the current session and chunk intact when changing nodes.
|
||||
// Missing acknowledgement does not prove the previous node received nothing.
|
||||
serverIndex = (serverIndex + 1) % session.servers.length;
|
||||
retries += 1;
|
||||
worker.serverIndex = (worker.serverIndex + 1) % session.servers.length;
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_retry offset=%d bytes=%d attempt=%d nextServer=%j error=%j',
|
||||
offset,
|
||||
chunkSize,
|
||||
transportAttempts,
|
||||
session.servers[serverIndex],
|
||||
highwayErrorText(err),
|
||||
session.servers[worker.serverIndex],
|
||||
highwayErrorText(error),
|
||||
);
|
||||
await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts);
|
||||
await sleepMs(HIGHWAY_RETRY_BASE_MS * transportAttempts, signal);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 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;
|
||||
signal.throwIfAborted();
|
||||
log.trace(() => [
|
||||
'highway_put_branch branch=chunk_control_response offset=%d bytes=%d responseBytes=%d responseHex=%s',
|
||||
offset,
|
||||
@@ -863,95 +953,221 @@ async function uploadHighwayHttpOperation(
|
||||
body.byteLength,
|
||||
renderTraceBytes(body),
|
||||
]);
|
||||
let resp: RespDataHighwayHead;
|
||||
let response: RespDataHighwayHead;
|
||||
|
||||
try {
|
||||
const { head: respHead } = unpackHighwayFrame(body);
|
||||
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,
|
||||
);
|
||||
response = protobuf_decode<RespDataHighwayHead>(unpackHighwayFrame(body).head);
|
||||
} catch (error) {
|
||||
trace.failureReason = 'control_decode_failed';
|
||||
trace.error = error;
|
||||
throw error;
|
||||
return fail('control_decode_failed', error);
|
||||
}
|
||||
|
||||
const errorCode = resp?.errorCode ?? 0;
|
||||
const segRetCode = resp?.msgSegHead?.retCode ?? 0;
|
||||
const errorCode = response.errorCode ?? 0;
|
||||
const segRetCode = response.msgSegHead?.retCode ?? 0;
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_control_decoded offset=%d errorCode=%d segRetCode=%d',
|
||||
offset,
|
||||
errorCode,
|
||||
segRetCode,
|
||||
);
|
||||
|
||||
if (errorCode !== 0 && HIGHWAY_DELAY_RETRY_CODES.has(errorCode)) {
|
||||
dropSocket();
|
||||
if (HIGHWAY_DELAY_RETRY_CODES.has(errorCode)) {
|
||||
dropSocket(worker);
|
||||
delayRetries += 1;
|
||||
|
||||
if (delayRetries >= HIGHWAY_MAX_DELAY_RETRIES) {
|
||||
rejectServer(errorCode, segRetCode);
|
||||
}
|
||||
|
||||
retries += 1;
|
||||
|
||||
if (effectiveConcurrency > 1) {
|
||||
log.warn(
|
||||
'highway upload reducing concurrency from %d to 1 after server backpressure (cmdId=%d offset=%d code=%d)',
|
||||
effectiveConcurrency,
|
||||
commandId,
|
||||
offset,
|
||||
errorCode,
|
||||
);
|
||||
effectiveConcurrency = 1;
|
||||
}
|
||||
|
||||
worker.serverIndex = (worker.serverIndex + 1) % session.servers.length;
|
||||
const delayMs = HIGHWAY_DELAY_RETRY_MS;
|
||||
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,
|
||||
delayMs,
|
||||
);
|
||||
await sleepMs(HIGHWAY_DELAY_RETRY_MS);
|
||||
await sleepMs(delayMs, signal);
|
||||
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.
|
||||
if (errorCode !== 0 || segRetCode !== 0) {
|
||||
rejectServer(errorCode, segRetCode);
|
||||
}
|
||||
|
||||
const seg = response.msgSegHead;
|
||||
// Each socket has exactly one outstanding request. Older responses
|
||||
// may omit echo fields (Proton decodes missing optionals as null);
|
||||
// when supplied, they must match that request.
|
||||
const mismatch =
|
||||
(response.msgBaseHead?.seq != null &&
|
||||
response.msgBaseHead.seq !== requestSequence) ||
|
||||
(seg?.filesize != null && seg.filesize !== BigInt(totalSize)) ||
|
||||
(seg?.dataOffset != null && seg.dataOffset !== BigInt(offset)) ||
|
||||
(seg?.dataLength != null && seg.dataLength !== chunkSize);
|
||||
|
||||
if (mismatch) {
|
||||
return fail(
|
||||
'ack_mismatch',
|
||||
new Error(
|
||||
`highway acknowledgement mismatch (cmdId=${commandId} offset=${offset} bytes=${chunkSize} seq=${requestSequence}; ackOffset=${String(seg?.dataOffset)} ackBytes=${String(seg?.dataLength)} ackSeq=${String(response.msgBaseHead?.seq)})`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
break;
|
||||
} finally {
|
||||
activeRequests -= 1;
|
||||
wake();
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_attempt_finished offset=%d worker=%d attempt=%d elapsedMs=%d',
|
||||
offset,
|
||||
worker.id,
|
||||
attempt,
|
||||
Date.now() - requestStarted,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
}
|
||||
trace.uploadedBytes += chunkSize;
|
||||
confirmed.add(piece);
|
||||
|
||||
offset += chunkSize;
|
||||
trace.uploadedBytes = offset;
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_completed offset=%d totalBytes=%d',
|
||||
offset,
|
||||
totalSize,
|
||||
while (confirmed.delete(contiguous)) {
|
||||
contiguous += 1;
|
||||
}
|
||||
|
||||
log.trace(
|
||||
'highway_put_branch branch=chunk_completed offset=%d totalBytes=%d acknowledgedBytes=%d contiguousBytes=%d worker=%d',
|
||||
offset + chunkSize,
|
||||
totalSize,
|
||||
trace.uploadedBytes,
|
||||
Math.min(totalSize, contiguous * HIGHWAY_BLOCK_SIZE),
|
||||
worker.id,
|
||||
);
|
||||
return worker;
|
||||
};
|
||||
|
||||
try {
|
||||
try {
|
||||
concurrency = validateUploadConcurrency(
|
||||
options.concurrency === undefined ? 1 : options.concurrency,
|
||||
);
|
||||
} catch (error) {
|
||||
fail('invalid_options', error);
|
||||
}
|
||||
|
||||
const pieces = Math.ceil(totalSize / HIGHWAY_BLOCK_SIZE);
|
||||
// The final piece commits the file only after every preceding piece is
|
||||
// acknowledged. One/two-piece files therefore need just one connection.
|
||||
effectiveConcurrency = Math.max(1, Math.min(concurrency, pieces - 1));
|
||||
const slots = effectiveConcurrency;
|
||||
|
||||
for (let id = 0; id < slots; id++) {
|
||||
workers.push({ id, socket: null, serverIndex: 0, connections: 0 });
|
||||
}
|
||||
|
||||
const free = [...workers];
|
||||
let next = 0;
|
||||
log.debug(
|
||||
'highway upload start: bytes=%d concurrency=%d effectiveConcurrency=%d cmdId=%d',
|
||||
totalSize,
|
||||
concurrency,
|
||||
slots,
|
||||
commandId,
|
||||
);
|
||||
|
||||
while (next < pieces || running.size > 0) {
|
||||
signal.throwIfAborted();
|
||||
|
||||
// Bound the distance from the first unconfirmed piece as well as
|
||||
// the number in flight. A slow early piece must not create an
|
||||
// unbounded hole even if later requests finish immediately.
|
||||
while (
|
||||
free.length &&
|
||||
running.size < effectiveConcurrency &&
|
||||
next < pieces &&
|
||||
next < contiguous + 10 &&
|
||||
(next !== pieces - 1 || contiguous === next)
|
||||
) {
|
||||
const worker = free.pop()!;
|
||||
const piece = next++;
|
||||
const job = sendChunk(worker, piece).catch((error: unknown) => {
|
||||
if (!signal.aborted) {
|
||||
abort.abort(error);
|
||||
}
|
||||
|
||||
throw error;
|
||||
});
|
||||
running.set(piece, job);
|
||||
}
|
||||
|
||||
if (running.size === 0) {
|
||||
throw new Error('highway upload stalled before all chunks were acknowledged');
|
||||
}
|
||||
|
||||
const finished = await Promise.race(
|
||||
[...running].map(async ([piece, job]) => ({ piece, worker: await job })),
|
||||
);
|
||||
running.delete(finished.piece);
|
||||
free.push(finished.worker);
|
||||
}
|
||||
|
||||
if (trace.uploadedBytes !== totalSize || contiguous !== pieces) {
|
||||
throw new Error('highway upload completed without confirming the whole file');
|
||||
}
|
||||
|
||||
succeeded = true;
|
||||
|
||||
if (totalSize > 0) {
|
||||
log.debug(
|
||||
'highway upload done: %d bytes over %d connection(s) (cmdId=%d)',
|
||||
totalSize,
|
||||
connectCount,
|
||||
commandId,
|
||||
);
|
||||
}
|
||||
log.debug(
|
||||
'highway upload done: %d bytes over %d connection(s) (cmdId=%d concurrency=%d effectiveConcurrency=%d retries=%d elapsedMs=%d)',
|
||||
totalSize,
|
||||
trace.connectCount,
|
||||
commandId,
|
||||
concurrency,
|
||||
effectiveConcurrency,
|
||||
retries,
|
||||
Date.now() - trace.startedAt,
|
||||
);
|
||||
} finally {
|
||||
// Best-effort close — never mask a primary upload error. A close failure
|
||||
// is only surfaced when the upload itself succeeded.
|
||||
dropSocket();
|
||||
abort.abort(new Error('highway upload stopped'));
|
||||
|
||||
for (const worker of workers) {
|
||||
dropSocket(worker);
|
||||
}
|
||||
|
||||
// Wait for positional reads, writes and retry waits before closing the
|
||||
// shared file handle. Never leave a worker sending after this call fails.
|
||||
await Promise.allSettled(running.values());
|
||||
|
||||
for (const worker of workers) {
|
||||
dropSocket(worker);
|
||||
}
|
||||
|
||||
signal.removeEventListener('abort', wake);
|
||||
|
||||
try {
|
||||
await source.close();
|
||||
} catch (closeErr) {
|
||||
} catch (error) {
|
||||
if (succeeded) {
|
||||
sourceCloseFailure = { error: closeErr };
|
||||
sourceCloseFailure = { error };
|
||||
} else {
|
||||
log.warn(
|
||||
'highway source close failed after upload failure: %s',
|
||||
highwayErrorText(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,8 @@ export interface MediaSubFileUpload {
|
||||
source: 'top' | number;
|
||||
/** Highway command id for this sub-file. */
|
||||
cmdId: number;
|
||||
/** Optional bounded parallel upload; only video bodies opt in. */
|
||||
concurrency?: number;
|
||||
/** Bytes to upload. Empty when the caller is forwarding from cached
|
||||
* fingerprints; in that case set fastOnlyError so we throw with a
|
||||
* typed message when the server actually demands the bytes. Also empty
|
||||
@@ -352,7 +354,28 @@ async function runNtv2UploadOperation(
|
||||
);
|
||||
const t0 = Date.now();
|
||||
setState('put_failed');
|
||||
await uploadHighwayHttp(bridge, putSession, sub.cmdId, chunkSource, sub.md5, extend);
|
||||
|
||||
if (sub.concurrency === undefined) {
|
||||
await uploadHighwayHttp(
|
||||
bridge,
|
||||
putSession,
|
||||
sub.cmdId,
|
||||
chunkSource,
|
||||
sub.md5,
|
||||
extend,
|
||||
);
|
||||
} else {
|
||||
await uploadHighwayHttp(
|
||||
bridge,
|
||||
putSession,
|
||||
sub.cmdId,
|
||||
chunkSource,
|
||||
sub.md5,
|
||||
extend,
|
||||
{ concurrency: sub.concurrency },
|
||||
);
|
||||
}
|
||||
|
||||
log.debug('%s PUT done in %dms', label, Date.now() - t0);
|
||||
didPut = true;
|
||||
setState('unexpected_failure', true);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Deployment-wide policy. Each video snapshots it before preparing its bytes. */
|
||||
let videoUploadConcurrency = 1;
|
||||
|
||||
export function validateUploadConcurrency(value: unknown): number {
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 4) {
|
||||
throw new RangeError('videoUploadConcurrency must be an integer from 1 to 4');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function setVideoUploadConcurrency(value: number): void {
|
||||
videoUploadConcurrency = validateUploadConcurrency(value);
|
||||
}
|
||||
|
||||
export function getVideoUploadConcurrency(): number {
|
||||
return videoUploadConcurrency;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getVideoUploadConcurrency } from './upload-settings';
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import { promises as fsp } from 'fs';
|
||||
@@ -341,7 +342,15 @@ export async function uploadVideoMsgInfo(
|
||||
element: MessageElement,
|
||||
): Promise<Uint8Array> {
|
||||
const log = loggerFor(bridge);
|
||||
const concurrency = getVideoUploadConcurrency();
|
||||
const preparedAt = Date.now();
|
||||
const video = await loadVideo(element);
|
||||
log.debug(
|
||||
'video preparation done: bytes=%d elapsedMs=%d concurrency=%d',
|
||||
video.fileSize,
|
||||
Date.now() - preparedAt,
|
||||
concurrency,
|
||||
);
|
||||
log.debug(
|
||||
'uploading %d bytes md5=%s... → %s %s',
|
||||
video.fileSize,
|
||||
@@ -354,6 +363,7 @@ export async function uploadVideoMsgInfo(
|
||||
const uploads: MediaSubFileUpload[] = [
|
||||
{
|
||||
source: 'top',
|
||||
concurrency,
|
||||
cmdId: isGroup ? GROUP_VIDEO_CMD_ID : PRIVATE_VIDEO_CMD_ID,
|
||||
bytes: video.bytes,
|
||||
fileSource: video.fileSource, // streamed from disk (undefined on the fingerprint fast path)
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AlertTriangle, KeyRound, Music, Plus, RefreshCw, Trash2 } from 'lucide-
|
||||
import { SkeletonSwap } from '@/components/interior/skeleton-swap';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { DropdownSelect } from '@/components/ui/dropdown-select';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useActionFeedback } from '@/contexts/ActionFeedbackContext';
|
||||
import { useApi } from '@/lib/api';
|
||||
@@ -223,6 +224,26 @@ export function GlobalConfigPanel() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-3 rounded-xl border bg-card/40 p-4">
|
||||
<Label>视频上传连接数</Label>
|
||||
<DropdownSelect
|
||||
ariaLabel="视频上传连接数"
|
||||
value={String(config.videoUploadConcurrency ?? 1)}
|
||||
options={[
|
||||
{ value: '1', label: '1 路(默认)' },
|
||||
{ value: '2', label: '2 路' },
|
||||
{ value: '3', label: '3 路' },
|
||||
{ value: '4', label: '4 路' },
|
||||
]}
|
||||
onChange={(value) =>
|
||||
commit({ ...config, videoUploadConcurrency: Number(value) })
|
||||
}
|
||||
/>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
对所有账号的下一次视频上传生效。小视频仍使用单连接;多路上传的提速效果取决于网络和服务器,遇到拥塞时会降低并发。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* music sign URL */}
|
||||
<div className="flex flex-col gap-4 rounded-xl border bg-card/40 p-4">
|
||||
<div className="flex items-start gap-2 text-xs leading-relaxed text-muted-foreground">
|
||||
|
||||
@@ -172,6 +172,7 @@ export interface GlobalSettings {
|
||||
rkey: RKeyConfig;
|
||||
/** Music-card signing service URL. Empty = built-in default. */
|
||||
musicSignUrl: string;
|
||||
videoUploadConcurrency?: number;
|
||||
}
|
||||
|
||||
// ─── Notifications (account up/down webhooks) ───────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user