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

+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');