feat(file): stream group + offline file uploads from disk (phase 5)

Wire the streaming primitives into the group-file and private/offline-file
upload paths. Both now stage the source onto a local disk path
(stageSourceToDisk — hardlink/download), hash it in one streaming pass
(hashFileStreaming; the offline-file md510MCheckSum comes from the same pass via
headLimit=MD5_HEAD_LIMIT), and PUT the file through a FileChunkSource — so a file
up to the 4 GiB protocol ceiling never holds more than one 1 MiB chunk in RAM.
The old readFileSync/loadBinarySource + computeHashes + md5First10MB buffered
path is removed.

The highway session is resolved before the file handle is opened (the handle's
owner, uploadHighwayHttp, must be the next call so its finally-close always
runs); a size+mtime guard re-checks the staged file before the PUT so a source
mutated mid-send fails cleanly; and the staged temp is released in a finally on
every exit. The OIDB preflight fields, the remembered-upload cache, the ext
blobs, and the publish steps (group 0x6D9_4 / private sendC2cFile) are byte-for-
byte unchanged. Tests re-mock at the stage/hash seams and assert the streamed
FileChunkSource + cleanup for both group and c2c uploads.
This commit is contained in:
DrSmoothl committed 2026-07-05 03:42:16 +08:00
1 parent e83eb80f2c
commit 1b968b9126
2 files changed
+216 -105

No files matched your search

+131 -97
View File
@@ -1,9 +1,12 @@
import { toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
import { FileChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
import { FILE_UPLOAD_MAX_BYTES } from '@snowluma/protocol/highway/utils';
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { protobuf_encode } from '@snowluma/proton';
import { promises as fsp } from 'fs';
import type { Bridge } from '../bridge';
import type { BridgeContext } from '../bridge-context';
import { resolveSelfUid, toInt, type MediaIndexNode } from './shared';
@@ -108,9 +111,14 @@ function normalizeUploadFileName(name: string, fallback: string): string {
// offline file uploads but never finalises as downloadable (#157).
const MD5_HEAD_LIMIT = 10002432;
function md5First10MB(bytes: Uint8Array): Uint8Array {
const limit = Math.min(bytes.length, MD5_HEAD_LIMIT);
return computeMd5(bytes.subarray(0, limit));
/** Fail cleanly if the staged file changed since the streaming hash pass (a
* local source mutated mid-send). The server's per-chunk md5 during the PUT is
* the backstop; this is the cheap early check. */
async function assertUnchanged(filePath: string, baseline: { size: number; mtimeMs: number }): Promise<void> {
const now = await fsp.stat(filePath);
if (now.size !== baseline.size || now.mtimeMs !== baseline.mtimeMs) {
throw new Error('file source changed during send (mutated between hashing and upload)');
}
}
function buildGroupFileUploadExt(
@@ -266,97 +274,110 @@ export class GroupFileApi {
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
// Group/private files may legitimately be up to 4 GiB on QQ's wire,
// so override the default 1 GiB cap with the protocol ceiling.
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('group file is empty');
// Group/private files may legitimately be up to 4 GiB on QQ's wire, so
// override the default 1 GiB cap with the protocol ceiling. Stage onto a
// local disk path and stream-hash it — the (up to 4 GiB) file is never
// buffered in RAM.
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
try {
if (staged.fileSize === 0) throw new Error('group file is empty');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath);
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
groupId,
fileName,
folderId: normalizeDirectory(folderId),
fileSize: loaded.bytes.length,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
scope: 'group',
groupId,
fileName,
fileSize: loaded.bytes.length,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
const ext = buildGroupFileUploadExt(
senderUin,
const upload = await UploadGroupFileRequest.invoke(this.ctx, {
groupId,
fileName,
loaded.bytes.length,
hashes.md5,
folderId: normalizeDirectory(folderId),
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
});
ensureRetCodeZero('group file upload', upload.retCode, upload.retMsg, upload.clientWording);
const fileId = typeof upload.fileId === 'string' && upload.fileId ? upload.fileId : null;
if (!fileId) throw new Error('group file upload response missing file_id');
// Remember the upload so a later `send_group_msg` carrying just the
// file_id can route via `publish` without forcing the OneBot caller
// to thread fileName/size/md5 separately. For groups the wire
// publish (OIDB 0x6d9_4) only needs the file_id itself, so this is
// mainly for log-line correctness; the c2c counterpart in
// `uploadPrivate` is where the cache is actually load-bearing.
this.ctx.rememberUploadedFile({
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
scope: 'group',
groupId,
fileName,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
rememberedAt: Date.now(),
});
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 71, new BufferChunkSource(loaded.bytes), hashes.md5, ext);
}
if (!upload.boolFileExist && uploadFile) {
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for group file upload');
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
// the chat shows nothing. The publish step goes via a dedicated OIDB
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a
// caller only needs a valid file_id embedded elsewhere, e.g. a
// forward-message long-msg payload. Routes through `this.publish` so
// tests can mock at the same Api boundary.
if (publishFile) {
try {
await this.publish(groupId, fileId);
} catch (err) {
// The bytes are already on the server and the fileId is valid —
// fail loud but don't lose the upload result the action handler
// committed to returning. Callers can still resolve the file by
// id; they'll just have to re-publish it themselves.
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
const uploadHost = (typeof upload.uploadIp === 'string' && upload.uploadIp)
|| (typeof upload.serverDns === 'string' && upload.serverDns)
|| '';
const uploadPort = toInt(upload.uploadPort);
if (!uploadHost || uploadPort <= 0) {
throw new Error('group file upload host is invalid');
}
const ext = buildGroupFileUploadExt(
senderUin,
groupId,
fileName,
staged.fileSize,
hashes.md5,
fileId,
upload.fileKey instanceof Uint8Array ? upload.fileKey : new Uint8Array(0),
upload.checkKey instanceof Uint8Array ? upload.checkKey : new Uint8Array(0),
uploadHost,
uploadPort,
);
// Fail cleanly if the source changed since hashing, then stream the PUT
// from disk. Fetch the session BEFORE opening the handle so
// uploadHighwayHttp (the handle's owner) is the next call and always
// closes it.
await assertUnchanged(staged.filePath, guardStat);
const session = await fetchHighwaySession(bridge);
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
await uploadHighwayHttp(bridge, session, 71, chunkSource, hashes.md5, ext);
}
}
return { fileId };
// Stage 3: file is on the server, now publish it as a chat message.
//
// Without this, OIDB 0x6D6_0 + highway PUT only stages the bytes —
// the chat shows nothing. The publish step goes via a dedicated OIDB
// call (0x6D9_4), NOT via `MessageSvc.PbSendMsg` with a transElem(24)
// payload — the QQ-NT server rejects that with `result=79`. Mirrors
// Lagrange.Core V2's `GroupSendFileService.cs`. Suppressed when a
// caller only needs a valid file_id embedded elsewhere, e.g. a
// forward-message long-msg payload. Routes through `this.publish` so
// tests can mock at the same Api boundary.
if (publishFile) {
try {
await this.publish(groupId, fileId);
} catch (err) {
// The bytes are already on the server and the fileId is valid —
// fail loud but don't lose the upload result the action handler
// committed to returning. Callers can still resolve the file by
// id; they'll just have to re-publish it themselves.
log.warn('group file uploaded (fileId=%s) but chat post failed: %s',
fileId, err instanceof Error ? err.message : String(err));
}
}
return { fileId };
} finally {
await staged.cleanup();
}
}
async uploadPrivate(
@@ -367,8 +388,12 @@ export class GroupFileApi {
publishFile = uploadFile,
): Promise<UploadFileResult> {
const bridge = asBridge(this.ctx);
const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES);
if (!loaded.bytes.length) throw new Error('private file is empty');
// Stage onto a local disk path + stream-hash — the (up to 4 GiB) file is
// never buffered in RAM. headLimit = MD5_HEAD_LIMIT yields the offline-file
// md510MCheckSum in the same single pass.
const staged = await stageSourceToDisk(source, FILE_UPLOAD_MAX_BYTES);
try {
if (staged.fileSize === 0) throw new Error('private file is empty');
const targetUid = await this.ctx.resolveUserUid(userId);
const selfUid = await resolveSelfUid(this.ctx);
@@ -376,17 +401,18 @@ export class GroupFileApi {
const senderUin = toInt(this.ctx.identity.uin);
if (senderUin <= 0) throw new Error('invalid self uin for private file upload');
const fileName = normalizeUploadFileName(name, loaded.fileName);
const hashes = computeHashes(loaded.bytes);
const fileName = normalizeUploadFileName(name, staged.fileName);
const guardStat = await fsp.stat(staged.filePath); // mutation-guard baseline
const hashes = await hashFileStreaming(staged.filePath, { headLimit: MD5_HEAD_LIMIT });
const upload = await UploadPrivateFileRequest.invoke(this.ctx, {
senderUid: selfUid,
receiverUid: targetUid,
fileName,
fileSize: loaded.bytes.length,
fileSize: staged.fileSize,
fileSha1: hashes.sha1,
fileMd5: hashes.md5,
md510MCheckSum: md5First10MB(loaded.bytes),
md510MCheckSum: hashes.headMd5!,
});
ensureRetCodeZero('private file upload', upload.retCode, upload.retMsg, undefined);
@@ -404,7 +430,7 @@ export class GroupFileApi {
scope: 'private',
userId,
fileName,
fileSize: loaded.bytes.length,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileSha1: hashes.sha1,
fileHash: fileHash ?? '',
@@ -478,7 +504,7 @@ export class GroupFileApi {
const ext = buildPrivateFileUploadExt(
senderUin,
fileName,
loaded.bytes.length,
staged.fileSize,
hashes.md5,
hashes.sha1,
fileId,
@@ -489,8 +515,13 @@ export class GroupFileApi {
uploadPort,
);
// Fail cleanly if the source changed since hashing, then stream the PUT
// from disk. Session BEFORE opening the handle so uploadHighwayHttp (the
// handle's owner) is the next call and always closes it.
await assertUnchanged(staged.filePath, guardStat);
const session = await fetchHighwaySession(bridge);
await uploadHighwayHttp(bridge, session, 95, new BufferChunkSource(loaded.bytes), hashes.md5, ext);
const chunkSource = await FileChunkSource.open(staged.filePath, staged.fileSize);
await uploadHighwayHttp(bridge, session, 95, chunkSource, hashes.md5, ext);
}
// Stage 3: publish the file as a c2c chat message. C2C files use
@@ -504,7 +535,7 @@ export class GroupFileApi {
await this.ctx.apis.message.sendC2cFile(userId, targetUid, {
fileId,
fileName,
fileSize: loaded.bytes.length,
fileSize: staged.fileSize,
fileMd5: hashes.md5,
fileHash: fileHash ?? '',
});
@@ -515,6 +546,9 @@ export class GroupFileApi {
}
return { fileId, fileHash };
} finally {
await staged.cleanup();
}
}
// ─────────────── list (paginated loop) ───────────────
+85 -8
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, beforeAll, afterAll } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
@@ -26,20 +26,32 @@ import type {
vi.mock('@snowluma/protocol/highway', () => ({
fetchHighwaySession: vi.fn(async () => ({})),
uploadHighwayHttp: vi.fn(async () => undefined),
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
FileChunkSource: { open: vi.fn(async () => ({ size: 3, read: vi.fn(), close: vi.fn(async () => undefined) })) },
}));
vi.mock('@snowluma/protocol/highway/utils', () => ({
loadBinarySource: vi.fn(async (_src: string, fallback: string) => ({
bytes: new Uint8Array([1, 2, 3]),
fileName: `${fallback}.bin`,
})),
computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })),
computeMd5: vi.fn(() => new Uint8Array(16)),
FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024,
}));
// The upload path now stages the source to disk + stream-hashes it; mock those
// two seams. stageSourceToDisk's filePath must be a REAL file so the mutation
// guard's fsp.stat succeeds (configured per-test in beforeEach → STAGED_FILE).
vi.mock('@snowluma/protocol/highway/stage', () => ({
stageSourceToDisk: vi.fn(),
}));
vi.mock('@snowluma/protocol/highway/hash-file', () => ({
hashFileStreaming: vi.fn(async () => ({
md5: new Uint8Array(16), sha1: new Uint8Array(20),
md5Hex: '00'.repeat(16), sha1Hex: '00'.repeat(20),
sha1Blocks: [], headMd5: new Uint8Array(16),
})),
}));
import fs from 'fs';
import os from 'os';
import path from 'path';
import * as highwayClient from '@snowluma/protocol/highway';
import * as stageMod from '@snowluma/protocol/highway/stage';
import { GroupFileApi } from '../../src/bridge/apis/group-file';
import { mockBridge } from './_helpers';
@@ -50,10 +62,23 @@ function packResponse(body: Uint8Array) {
};
}
let STAGED_FILE: string;
describe('apis/group-file', () => {
beforeAll(() => {
STAGED_FILE = path.join(os.tmpdir(), `sl-gf-staged-${process.pid}.bin`);
fs.writeFileSync(STAGED_FILE, Buffer.from([1, 2, 3])); // real 3-byte file for the guard stat
});
afterAll(() => { try { fs.unlinkSync(STAGED_FILE); } catch { /* ignore */ } });
beforeEach(() => {
vi.mocked(highwayClient.fetchHighwaySession).mockClear();
vi.mocked(highwayClient.uploadHighwayHttp).mockClear();
vi.mocked(highwayClient.FileChunkSource.open).mockClear();
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValue({
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin',
cleanup: vi.fn(async () => undefined),
} as any);
});
it('getCount returns { fileCount, maxCount } from the OIDB response', async () => {
@@ -119,6 +144,32 @@ describe('apis/group-file', () => {
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
});
it('[stream] PUTs from the staged disk file via FileChunkSource and releases the temp', async () => {
const cleanup = vi.fn(async () => undefined);
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValueOnce({
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin', cleanup,
} as any);
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbGroupFileResp>>({
body: {
upload: {
fileId: 'fid-xyz', uploadIp: '1.2.3.4', uploadPort: 8080,
fileKey: new Uint8Array([9]), checkKey: new Uint8Array([8]),
},
} as any,
}),
));
const api = new GroupFileApi(bridge as any);
vi.spyOn(api, 'publish').mockResolvedValue();
await api.upload(12345, '/path/file.bin');
// Main file streamed from the staged path (not buffered), and the temp is
// released afterward.
expect(highwayClient.FileChunkSource.open).toHaveBeenCalledWith(STAGED_FILE, 3);
expect(vi.mocked(highwayClient.uploadHighwayHttp).mock.calls[0]![3]).toBeDefined();
expect(cleanup).toHaveBeenCalled();
});
it('upload throws on missing upload response', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
@@ -364,6 +415,32 @@ describe('apis/group-file', () => {
expect(bridge.apis.message.sendC2cFile).not.toHaveBeenCalled();
});
it('[stream] uploadPrivate PUTs from the staged disk file via FileChunkSource and releases the temp', async () => {
const cleanup = vi.fn(async () => undefined);
vi.mocked(stageMod.stageSourceToDisk).mockResolvedValueOnce({
filePath: STAGED_FILE, fileSize: 3, fileName: 'file.bin', cleanup,
} as any);
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbPrivateFileUploadResp>>({
body: {
upload: {
uuid: 'pfid-stream', fileAddon: 'phash',
rtpMediaPlatformUploadAddress: [
{ outIP: 0, outPort: 0, inIP: 16885952, inPort: 8080, iPType: 1 },
],
mediaPlatformUploadKey: new Uint8Array([1, 2, 3]),
} as any,
},
}),
));
await new GroupFileApi(bridge as any).uploadPrivate(67890, '/path/file', 'doc.pdf', true, false);
expect(highwayClient.FileChunkSource.open).toHaveBeenCalledWith(STAGED_FILE, 3);
expect(highwayClient.uploadHighwayHttp).toHaveBeenCalledOnce();
expect(cleanup).toHaveBeenCalled();
});
it('uploadPrivate reads host from rtpMediaPlatformUploadAddress[0].inIP when populated', async () => {
const bridge = mockBridge();
vi.mocked(bridge.resolveUserUid).mockResolvedValueOnce('target-uid');