feat(core): stream flash-transfer uploads from disk

create_flash_task loaded every fileset file through loadBinarySource
and kept the bytes through hash, commit, and sliceupload, so a single
file over 1 GiB could not be sent. Stage to disk like group files,
stream MD5/SHA1/Sha1StateV, then POST 1 MiB chunks from FileChunkSource.

Do not reuse video sha1Blocks as Sha1StateV: an exact N-MiB file would
ship an extra un-finalized last-slice state. Local/HTTP sources use the
4 GiB group-file ceiling; inline base64 stays at 1 GiB because stage
still decodes it in RAM. Protocol order, seconds-pass, and multi-file
commit are unchanged.

Fixes #359
This commit is contained in:
DrSmoothl committed 2026-08-13 18:34:27 +08:00
1 parent e7322e2e72
commit b8b9be83c3
5 files changed
+542 -79

No files matched your search

+138 -78
View File
@@ -17,13 +17,49 @@ import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfe
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
import { SendFlashMsg } from '@snowluma/protocol/oidb-services/flash-transfer/send-flash';
import { loadBinarySource, computeHashes } from '@snowluma/protocol/highway/utils';
import { FileChunkSource } from '@snowluma/protocol/highway';
import {
computeHashes,
inlineBase64Payload,
FLASH_TRANSFER_MAX_BYTES,
FLASH_TRANSFER_INLINE_MAX_BYTES,
} from '@snowluma/protocol/highway/utils';
import { stageSourceToDisk } from '@snowluma/protocol/highway/stage';
import { hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
import type { FlashSliceUploadBody, FlashSliceUploadResp, FlashFileId } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { randomUUID, randomBytes, createHash } from 'node:crypto';
import { promises as fsp } from 'node:fs';
import { deflateSync } from 'node:zlib';
const FLASH_SLICE_SIZE = 1024 * 1024;
/** Fail cleanly if the staged file changed since the streaming hash pass. */
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 flashStageMaxBytes(source: string): number {
return inlineBase64Payload(source) !== null
? FLASH_TRANSFER_INLINE_MAX_BYTES
: FLASH_TRANSFER_MAX_BYTES;
}
interface StagedFlashItem {
filePath: string;
fileSize: number;
fileName: string;
fileUuid: string;
fileIndex: number;
formatCode: number;
guardStat: { size: number; mtimeMs: number };
cleanup(): Promise<void>;
}
/** 闪传文件信息(业务层,从 FlashFileEntry 转换)。 */
export interface FlashFileInfo {
filesetUuid: string;
@@ -379,6 +415,10 @@ export class FlashTransferApi {
* 逐个 prepare/apply/sliceupload。prepare/apply 的 filesetWrap.f4 必须与 commit
* 的 f6 一致,否则文件不计入 fileset。多文件时 ApplyFileset 的 fileName 用
* 「<首文件名>等N个文件」、fileSize 用总和——服务端据此判定 fileset 为多文件。
*
* 源文件经 stageSourceToDisk 落到本地路径后流式哈希 / 分片读取,不再经
* loadBinarySource 整文件进内存。本地与 HTTP 上限与群文件相同(4 GiB);
* 内联 base64 仍按 1 GiB 封顶,因为 stage 解码时会占用等量 RAM。
*/
async createFlashTask(files: string | string[], _name?: string, _thumbPath?: string): Promise<{ filesetId: string }> {
const fileList = Array.isArray(files) ? files : [files];
@@ -390,104 +430,124 @@ export class FlashTransferApi {
// uid drops the fileset if this runs before warmup populated selfUid.
uid: await resolveSelfUid(this.ctx),
};
// 读取所有文件,每个分配 fileUuid + 序号 + formatCode
const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = [];
for (let i = 0; i < fileList.length; i++) {
const { bytes, fileName } = await loadBinarySource(fileList[i], 'flash-transfer');
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
items.push({ bytes: new Uint8Array(bytes), fileName, fileUuid: randomUUID(), fileIndex: i + 1, formatCode });
const items: StagedFlashItem[] = [];
try {
for (let i = 0; i < fileList.length; i++) {
const source = fileList[i];
const staged = await stageSourceToDisk(source, flashStageMaxBytes(source));
const fileName = staged.fileName;
const { formatCode } = FlashTransferApi.fileTypeCode(fileName);
items.push({
filePath: staged.filePath,
fileSize: staged.fileSize,
fileName,
fileUuid: randomUUID(),
fileIndex: i + 1,
formatCode,
guardStat: await fsp.stat(staged.filePath),
cleanup: () => staged.cleanup(),
});
if (staged.fileSize === 0) throw new Error('create_flash_task: file is empty');
}
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
const first = items[0];
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
const isMulti = items.length > 1;
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
const totalSize = items.reduce((s, it) => s + it.fileSize, 0);
const apply = await ApplyFileset.invoke(this.ctx, {
fileName: filesetName, origName: filesetName,
fileSize: totalSize, typeCode, uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
const commitEntries = items.map((it) => ({
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
fileSize: it.fileSize, formatCode: it.formatCode, fileIndex: it.fileIndex,
}));
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
await CompleteFileset.invoke(this.ctx, { filesetUuid });
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
const prepared: { it: StagedFlashItem; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
for (const it of items) {
const p = await this.prepareAndApply(filesetUuid, it);
if (p) prepared.push({ it, ...p });
}
for (const p of prepared) {
await assertUnchanged(p.it.filePath, p.it.guardStat);
await this.sliceuploadFile(
p.it.filePath, p.it.fileSize, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName,
);
}
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
return { filesetId: filesetUuid };
} finally {
await Promise.all(items.map((it) => it.cleanup()));
}
// 申请 fileset。多文件时 fileName 用「<首文件名>等N个文件」、fileSize 用总和,
// 服务端据此判定 fileset 为多文件,commit 的后续 entry 才会被计入。
const first = items[0];
const { typeCode } = FlashTransferApi.fileTypeCode(first.fileName);
const isMulti = items.length > 1;
const filesetName = isMulti ? `${first.fileName}等${items.length}个文件` : first.fileName;
const totalSize = items.reduce((s, it) => s + it.bytes.length, 0);
const apply = await ApplyFileset.invoke(this.ctx, {
fileName: filesetName, origName: filesetName,
fileSize: totalSize, typeCode, uploader,
});
const filesetUuid = apply.filesetUuid;
if (!filesetUuid) throw new Error('apply fileset failed: missing uuid');
// 一次性 commit 所有文件元数据(f4 repeated,每条 f6=序号)
const commitEntries = items.map((it) => ({
fileUuid: it.fileUuid, fileName: it.fileName, origName: it.fileName,
fileSize: it.bytes.length, formatCode: it.formatCode, fileIndex: it.fileIndex,
}));
await CommitFile.invoke(this.ctx, { filesetUuid, entries: commitEntries });
await CompleteFileset.invoke(this.ctx, { filesetUuid });
// 两阶段上传:先全部 prepare+apply 注册 fileId,再全部 sliceupload 落盘。
const prepared: { it: typeof items[0]; rkey: string; sha1StateV: Uint8Array[]; sliceCount: number }[] = [];
for (const it of items) {
const p = await this.prepareAndApply(filesetUuid, it.bytes, it.fileName, it.fileUuid, it.fileIndex, it.formatCode);
if (p) prepared.push({ it, ...p });
}
for (const p of prepared) {
await this.sliceuploadFile(p.it.bytes, p.rkey, p.sha1StateV, p.sliceCount, p.it.fileName);
}
// fileset 级缩略图(序号在主文件之后递增),主文件下载入口需要缩略图关联
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'png', items.length + 1);
await this.uploadThumbnail(filesetUuid, items[0].fileUuid, 'jpg', items.length + 2);
await SetFilesetStatus.invoke(this.ctx, { filesetUuid });
return { filesetId: filesetUuid };
}
/**
* 阶段1:prepare(拿 rkey)+ apply(注册 fileId)。返回 sliceupload 所需的 rkey/sha1state。
* 阶段1:流式哈希 + prepare(拿 rkey)+ apply(注册 fileId)。
* 秒传(rkey=null)返回 null,调用方跳过 sliceupload。
*/
private async prepareAndApply(
filesetUuid: string, bytes: Uint8Array, fileName: string, fileUuid: string, fileIndex: number, formatCode: number,
filesetUuid: string, it: StagedFlashItem,
): Promise<{ rkey: string; sha1StateV: Uint8Array[]; sliceCount: number } | null> {
const fileSize = bytes.length;
const hashes = computeHashes(bytes);
const SLICE_SIZE = 1024 * 1024;
const sliceCount = Math.ceil(fileSize / SLICE_SIZE);
const sha1StateV = computeSha1StateV(bytes, sliceCount, SLICE_SIZE);
const hashes = await hashFlashFileStreaming(it.filePath);
await assertUnchanged(it.filePath, it.guardStat);
const rkey = await PrepareUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileName, fileSize, sha1: hashes.sha1Hex, fileIndex, formatCode,
filesetUuid, fileUuid: it.fileUuid, fileName: it.fileName, fileSize: it.fileSize,
sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
if (rkey === null) return null; // 秒传
const fileId = FlashTransferApi.buildFileId(hashes.sha1, fileSize);
const fileId = FlashTransferApi.buildFileId(hashes.sha1, it.fileSize);
await ApplyUpload.invoke(this.ctx, {
filesetUuid, fileUuid, fileId, fileName, fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex, formatCode,
filesetUuid, fileUuid: it.fileUuid, fileId, fileName: it.fileName, fileSize: it.fileSize,
md5: hashes.md5Hex, sha1: hashes.sha1Hex, fileIndex: it.fileIndex, formatCode: it.formatCode,
});
return { rkey, sha1StateV, sliceCount };
return { rkey, sha1StateV: hashes.sha1StateV, sliceCount: hashes.sliceCount };
}
/**
* 阶段2:sliceupload 分片上传(所有文件 prepare+apply 完成后调用)。
* 阶段2:从磁盘按 1 MiB 切片 POST sliceupload(所有文件 prepare+apply 完成后调用)。
*/
private async sliceuploadFile(
bytes: Uint8Array, rkey: string, sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
filePath: string, fileSize: number, rkey: string,
sha1StateV: Uint8Array[], sliceCount: number, fileName: string,
): Promise<void> {
const fileSize = bytes.length;
const SLICE_SIZE = 1024 * 1024;
for (let i = 0; i < sliceCount; i++) {
const start = i * SLICE_SIZE;
const chunk = bytes.subarray(start, Math.min(start + SLICE_SIZE, fileSize));
const chunkLen = chunk.length;
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
const body: FlashSliceUploadBody = {
field1: 0,
appid: 14901,
field3: 2,
payload: {
field1: {},
rkey,
start,
end: start + chunkLen - 1,
sha1: chunkSha1,
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(chunk),
},
};
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
const src = await FileChunkSource.open(filePath, fileSize);
try {
for (let i = 0; i < sliceCount; i++) {
const start = i * FLASH_SLICE_SIZE;
const chunkLen = Math.min(FLASH_SLICE_SIZE, fileSize - start);
const chunk = await src.read(start, chunkLen);
const chunkSha1 = new Uint8Array(createHash('sha1').update(Buffer.from(chunk)).digest());
const body: FlashSliceUploadBody = {
field1: 0,
appid: 14901,
field3: 2,
payload: {
field1: {},
rkey,
start,
end: start + chunkLen - 1,
sha1: chunkSha1,
sha1StateV: { state: sha1StateV.map((s) => new Uint8Array(s)) },
chunk: new Uint8Array(chunk),
},
};
const bodyBytes = protobuf_encode<FlashSliceUploadBody>(body);
await this.postSliceupload(bodyBytes, `${fileName} slice ${i}`);
}
} finally {
await src.close();
}
}
@@ -0,0 +1,267 @@
// createFlashTask stages each source to disk and streams hash + sliceupload
// (#359). OIDB / sliceupload HTTP are mocked; the file bytes and Sha1StateV
// on the wire must still match the buffered flash helpers.
import { afterEach, beforeAll, afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { promises as fsp } from 'fs';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { createHash } from 'node:crypto';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FlashSliceUploadBody, FlashSliceUploadResp } from '@snowluma/proto-defs/oidb-actions/flash-transfer';
import { ApplyFileset } from '@snowluma/protocol/oidb-services/flash-transfer/apply-fileset';
import { CommitFile } from '@snowluma/protocol/oidb-services/flash-transfer/commit-file';
import { CompleteFileset } from '@snowluma/protocol/oidb-services/flash-transfer/complete-fileset';
import { PrepareUpload } from '@snowluma/protocol/oidb-services/flash-transfer/prepare-upload';
import { ApplyUpload } from '@snowluma/protocol/oidb-services/flash-transfer/apply-upload';
import { SetFilesetStatus } from '@snowluma/protocol/oidb-services/flash-transfer/set-status';
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
import {
computeHashes,
FLASH_TRANSFER_INLINE_MAX_BYTES,
FLASH_TRANSFER_MAX_BYTES,
} from '@snowluma/protocol/highway/utils';
import * as stageMod from '@snowluma/protocol/highway/stage';
import * as hashMod from '@snowluma/protocol/highway/hash-file';
import { FlashTransferApi } from '../src/bridge/apis/flash-transfer';
import { mockBridge } from './actions/_helpers';
const FILESET = '8e40afa1-829d-498b-852f-092394ddb31f';
const SLICE_URL = 'https://multimedia.qfile.qq.com/sliceupload';
const SLICE = 1024 * 1024;
const originalFetch = globalThis.fetch;
let dir: string;
beforeAll(async () => {
dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-flash-create-'));
});
afterAll(async () => {
await fsp.rm(dir, { recursive: true, force: true });
});
afterEach(() => {
globalThis.fetch = originalFetch;
vi.restoreAllMocks();
});
function writeSrc(name: string, bytes: Uint8Array): string {
const file = path.join(dir, name);
fs.writeFileSync(file, bytes);
return file;
}
function synth(size: number, seed = 7): Uint8Array {
const b = new Uint8Array(size);
for (let i = 0; i < size; i++) b[i] = (i * 131 + seed) & 0xff;
return b;
}
function toU8(body: unknown): Uint8Array {
if (body instanceof Uint8Array) return body;
if (Buffer.isBuffer(body)) return new Uint8Array(body);
throw new Error(`unexpected fetch body: ${typeof body}`);
}
function installSliceuploadOk(): FlashSliceUploadBody[] {
const calls: FlashSliceUploadBody[] = [];
globalThis.fetch = vi.fn(async (input, init) => {
const url = String(input);
if (url !== SLICE_URL) throw new Error(`unexpected fetch ${url}`);
calls.push(protobuf_decode<FlashSliceUploadBody>(toU8(init?.body)));
return new Response(
Buffer.from(protobuf_encode<FlashSliceUploadResp>({ status: 'success' })),
{ status: 200 },
);
}) as typeof fetch;
return calls;
}
function mainSlices(calls: FlashSliceUploadBody[]): FlashSliceUploadBody[] {
return calls.filter((c) => c.appid === 14901);
}
function stubOidb(): void {
vi.spyOn(ApplyFileset, 'invoke').mockResolvedValue({ filesetUuid: FILESET });
vi.spyOn(CommitFile, 'invoke').mockResolvedValue({});
vi.spyOn(CompleteFileset, 'invoke').mockResolvedValue(undefined);
vi.spyOn(PrepareUpload, 'invoke').mockResolvedValue('rkey-main');
vi.spyOn(ApplyUpload, 'invoke').mockResolvedValue(undefined);
vi.spyOn(SetFilesetStatus, 'invoke').mockResolvedValue(undefined);
}
function api(): FlashTransferApi {
return new FlashTransferApi(mockBridge() as never);
}
describe('FlashTransferApi.createFlashTask — disk streaming (#359)', () => {
beforeEach(() => {
stubOidb();
});
it('stages a local file, commits metadata, and sliceuploads the disk bytes with flash Sha1StateV', async () => {
const bytes = synth(200);
const file = writeSrc('clip.mp4', bytes);
const hashes = computeHashes(bytes);
const sha1StateV = computeSha1StateV(bytes, 1, SLICE);
const stageSpy = vi.spyOn(stageMod, 'stageSourceToDisk');
const slices = installSliceuploadOk();
await expect(api().createFlashTask(file)).resolves.toEqual({ filesetId: FILESET });
expect(stageSpy).toHaveBeenCalledWith(file, FLASH_TRANSFER_MAX_BYTES);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'clip.mp4',
origName: 'clip.mp4',
fileSize: 200,
typeCode: 7,
uploader: { uin: '10001', nickname: 'self-nick', uid: 'self-uid' },
}));
expect(CommitFile.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
filesetUuid: FILESET,
entries: [expect.objectContaining({
fileName: 'clip.mp4',
fileSize: 200,
fileIndex: 1,
formatCode: 2,
})],
}));
expect(CompleteFileset.invoke).toHaveBeenCalledWith(expect.anything(), { filesetUuid: FILESET });
const uploaded = mainSlices(slices);
expect(uploaded).toHaveLength(1);
expect(uploaded[0]!.payload?.rkey).toBe('rkey-main');
expect(uploaded[0]!.payload?.start).toBe(0);
expect(uploaded[0]!.payload?.end).toBe(199);
expect(Buffer.from(uploaded[0]!.payload!.chunk!).equals(Buffer.from(bytes))).toBe(true);
expect(Buffer.from(uploaded[0]!.payload!.sha1!).equals(
createHash('sha1').update(Buffer.from(bytes)).digest(),
)).toBe(true);
expect(uploaded[0]!.payload!.sha1StateV!.state).toHaveLength(1);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![0]!).equals(Buffer.from(sha1StateV[0]!))).toBe(true);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![0]!).equals(Buffer.from(hashes.sha1))).toBe(true);
expect(SetFilesetStatus.invoke).toHaveBeenCalledWith(expect.anything(), { filesetUuid: FILESET });
});
it('caps inline base64 at the RAM-decode ceiling, not the 4 GiB disk ceiling', async () => {
const bytes = synth(32, 9);
const source = `base64://${Buffer.from(bytes).toString('base64')}`;
const stageSpy = vi.spyOn(stageMod, 'stageSourceToDisk');
installSliceuploadOk();
await api().createFlashTask(source);
expect(stageSpy).toHaveBeenCalledWith(source, FLASH_TRANSFER_INLINE_MAX_BYTES);
});
it('rejects an empty file before applying a fileset and still releases the stage', async () => {
const file = writeSrc('empty.bin', new Uint8Array(0));
const cleanups: Array<ReturnType<typeof vi.fn>> = [];
const actualStage = stageMod.stageSourceToDisk;
vi.spyOn(stageMod, 'stageSourceToDisk').mockImplementation(async (source, maxBytes) => {
const staged = await actualStage(source, maxBytes);
const cleanup = vi.fn(async () => staged.cleanup());
cleanups.push(cleanup);
return { ...staged, cleanup };
});
await expect(api().createFlashTask(file)).rejects.toThrow(/empty/i);
expect(ApplyFileset.invoke).not.toHaveBeenCalled();
expect(cleanups[0]).toHaveBeenCalled();
});
it('releases staged temps when apply-fileset fails', async () => {
const file = writeSrc('fail.mp4', synth(40, 3));
const cleanups: Array<ReturnType<typeof vi.fn>> = [];
const actualStage = stageMod.stageSourceToDisk;
vi.spyOn(stageMod, 'stageSourceToDisk').mockImplementation(async (source, maxBytes) => {
const staged = await actualStage(source, maxBytes);
const cleanup = vi.fn(async () => staged.cleanup());
cleanups.push(cleanup);
return { ...staged, cleanup };
});
vi.mocked(ApplyFileset.invoke).mockRejectedValueOnce(new Error('oidb down'));
await expect(api().createFlashTask(file)).rejects.toThrow('oidb down');
expect(cleanups[0]).toHaveBeenCalled();
});
it('skips sliceupload when prepare-upload reports a seconds-pass', async () => {
const file = writeSrc('hit.mp4', synth(80, 11));
vi.mocked(PrepareUpload.invoke).mockImplementation(async (_ctx, p) => (
p.thumbType ? 'thumb-rkey' : null
));
const slices = installSliceuploadOk();
await api().createFlashTask(file);
expect(mainSlices(slices)).toHaveLength(0);
expect(ApplyUpload.invoke).toHaveBeenCalled(); // thumbs still apply
expect(SetFilesetStatus.invoke).toHaveBeenCalled();
});
it('sliceuploads a multi-megabyte file as 1 MiB disk chunks with flash Sha1StateV', async () => {
const bytes = synth(SLICE + 80, 13);
const file = writeSrc('big.mp4', bytes);
const sha1StateV = computeSha1StateV(bytes, 2, SLICE);
const slices = installSliceuploadOk();
await api().createFlashTask(file);
const uploaded = mainSlices(slices);
expect(uploaded).toHaveLength(2);
expect(uploaded[0]!.payload?.start).toBe(0);
expect(uploaded[0]!.payload?.end).toBe(SLICE - 1);
expect(uploaded[1]!.payload?.start).toBe(SLICE);
expect(uploaded[1]!.payload?.end).toBe(SLICE + 79);
expect(Buffer.from(uploaded[0]!.payload!.chunk!).equals(Buffer.from(bytes.subarray(0, SLICE)))).toBe(true);
expect(Buffer.from(uploaded[1]!.payload!.chunk!).equals(Buffer.from(bytes.subarray(SLICE)))).toBe(true);
expect(uploaded[0]!.payload!.sha1StateV!.state).toHaveLength(2);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![0]!).equals(Buffer.from(sha1StateV[0]!))).toBe(true);
expect(Buffer.from(uploaded[0]!.payload!.sha1StateV!.state![1]!).equals(Buffer.from(sha1StateV[1]!))).toBe(true);
expect(Buffer.from(uploaded[1]!.payload!.sha1StateV!.state![1]!).equals(
createHash('sha1').update(Buffer.from(bytes)).digest(),
)).toBe(true);
});
it('commits every fileset entry once, then sliceuploads each file from disk', async () => {
const a = synth(50, 1);
const b = synth(70, 2);
const fileA = writeSrc('a.mp4', a);
const fileB = writeSrc('b.zip', b);
const slices = installSliceuploadOk();
await api().createFlashTask([fileA, fileB]);
expect(ApplyFileset.invoke).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
fileName: 'a.mp4等2个文件',
fileSize: 120,
}));
const commit = vi.mocked(CommitFile.invoke).mock.calls[0]![1];
expect(commit.entries).toHaveLength(2);
expect(commit.entries[0]).toEqual(expect.objectContaining({
fileName: 'a.mp4', fileSize: 50, fileIndex: 1, formatCode: 2,
}));
expect(commit.entries[1]).toEqual(expect.objectContaining({
fileName: 'b.zip', fileSize: 70, fileIndex: 2, formatCode: 4,
}));
const uploaded = mainSlices(slices);
expect(uploaded).toHaveLength(2);
expect(Buffer.from(uploaded[0]!.payload!.chunk!).equals(Buffer.from(a))).toBe(true);
expect(Buffer.from(uploaded[1]!.payload!.chunk!).equals(Buffer.from(b))).toBe(true);
});
it('rejects a source that mutates between hashing and upload', async () => {
const file = writeSrc('mut.mp4', synth(90, 5));
const actualHash = hashMod.hashFlashFileStreaming;
vi.spyOn(hashMod, 'hashFlashFileStreaming').mockImplementation(async (filePath) => {
const hashes = await actualHash(filePath);
await fsp.appendFile(filePath, Buffer.from([0xff]));
return hashes;
});
installSliceuploadOk();
await expect(api().createFlashTask(file)).rejects.toThrow(/changed during send/i);
});
});
+65 -1
View File
@@ -11,8 +11,9 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { randomUUID } from 'crypto';
import { hashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { hashFileStreaming, hashFlashFileStreaming } from '@snowluma/protocol/highway/hash-file';
import { computeHashes, computeMd5 } from '@snowluma/protocol/highway/utils';
import { computeSha1StateV } from '@snowluma/protocol/highway/sha1-stream';
import { computeVideoSha1Blocks } from '@snowluma/protocol/highway/video-upload';
const MB = 1024 * 1024;
@@ -90,3 +91,66 @@ describe('hashFileStreaming ≡ buffered computeHashes + computeVideoSha1Blocks
expect(eq(streamed.headMd5!, computeMd5(new Uint8Array(0)))).toBe(true);
});
});
// Flash sliceupload Sha1StateV is NOT video sha1Blocks. Both snapshot
// un-finalized SHA1 at 1 MiB boundaries, but flash omits the un-finalized
// snapshot of the last full slice — that slot is the finalized whole-file
// SHA1. Reusing sha1Blocks when size % 1 MiB === 0 ships an extra state
// and the server rejects the upload.
describe('hashFlashFileStreaming ≡ buffered computeHashes + computeSha1StateV', () => {
let dir: string;
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-flash-hash-')); });
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
const SIZES = [0, 1, 63, 64, 65, MB - 1, MB, MB + 1, 2 * MB, 2 * MB + 123];
for (const size of SIZES) {
it(`size=${size}: md5 / sha1 / Sha1StateV match the buffered flash helpers`, async () => {
const data = synth(size);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const streamed = await hashFlashFileStreaming(file);
const buffered = computeHashes(data);
const sliceCount = Math.ceil(size / MB);
const refState = computeSha1StateV(data, sliceCount, MB);
expect(eq(streamed.md5, buffered.md5)).toBe(true);
expect(eq(streamed.sha1, buffered.sha1)).toBe(true);
expect(streamed.md5Hex).toBe(buffered.md5Hex);
expect(streamed.sha1Hex).toBe(buffered.sha1Hex);
expect(streamed.sliceCount).toBe(sliceCount);
expect(streamed.sha1StateV.length).toBe(refState.length);
for (let i = 0; i < refState.length; i++) {
expect(eq(streamed.sha1StateV[i]!, refState[i]!)).toBe(true);
}
});
}
it('exact 1 MiB is not video sha1Blocks (no extra un-finalized last-slice state)', async () => {
const data = synth(MB);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const flash = await hashFlashFileStreaming(file);
const video = await hashFileStreaming(file);
expect(flash.sha1StateV.length).toBe(1);
expect(video.sha1Blocks.length).toBe(2);
expect(eq(flash.sha1StateV[0]!, video.sha1Blocks[1]!)).toBe(true);
expect(eq(flash.sha1StateV[0]!, video.sha1Blocks[0]!)).toBe(false);
});
it('exact 2 MiB: flash has 2 states, video sha1Blocks has 3', async () => {
const data = synth(2 * MB);
const file = path.join(dir, `${randomUUID()}.bin`);
fs.writeFileSync(file, data);
const flash = await hashFlashFileStreaming(file);
const video = await hashFileStreaming(file);
expect(flash.sliceCount).toBe(2);
expect(flash.sha1StateV.length).toBe(2);
expect(video.sha1Blocks.length).toBe(3);
expect(eq(flash.sha1StateV[0]!, video.sha1Blocks[0]!)).toBe(true);
expect(eq(flash.sha1StateV[1]!, video.sha1Blocks[2]!)).toBe(true);
});
});
@@ -95,3 +95,68 @@ export async function hashFileStreaming(
await src.close();
}
}
export interface StreamedFlashHashes {
md5: Uint8Array;
sha1: Uint8Array;
md5Hex: string;
sha1Hex: string;
/** Flash sliceupload Sha1StateV — un-finalized little-endian state after
* every full 1 MiB slice except the last; the last entry is the finalized
* whole-file SHA1. Same shape as `computeSha1StateV`, not `sha1Blocks`. */
sha1StateV: Uint8Array[];
sliceCount: number;
}
/**
* Streaming hash for flash-transfer sliceupload. Equivalent to
* `computeHashes` + `computeSha1StateV(bytes, ceil(size/1MiB), 1MiB)`
* without buffering the file.
*
* Do not substitute `hashFileStreaming().sha1Blocks`: when
* `size % 1 MiB === 0` that list has an extra un-finalized last-slice
* state that flash's Sha1StateV must not carry.
*/
export async function hashFlashFileStreaming(filePath: string): Promise<StreamedFlashHashes> {
const { size } = await fsp.stat(filePath);
const sliceCount = Math.ceil(size / SHA1_STREAM_BLOCK_SIZE);
const src = await FileChunkSource.open(filePath, size);
try {
const md5 = createHash('md5');
const sha1 = createHash('sha1');
const blockSha1 = new Sha1Stream();
const sha1StateV: Uint8Array[] = [];
let offset = 0;
let sliceIndex = 0;
while (offset < size) {
const len = Math.min(SHA1_STREAM_BLOCK_SIZE, size - offset);
const chunk = await src.read(offset, len);
md5.update(chunk);
sha1.update(chunk);
blockSha1.update(chunk);
if (sliceIndex !== sliceCount - 1) {
sha1StateV.push(blockSha1.hash(true));
}
offset += len;
sliceIndex += 1;
}
const sha1Digest = sha1.digest();
if (sliceCount > 0) {
sha1StateV.push(new Uint8Array(sha1Digest));
}
const md5Digest = md5.digest();
return {
md5: new Uint8Array(md5Digest),
sha1: new Uint8Array(sha1Digest),
md5Hex: md5Digest.toString('hex'),
sha1Hex: sha1Digest.toString('hex'),
sha1StateV,
sliceCount,
};
} finally {
await src.close();
}
}
+7
View File
@@ -20,6 +20,13 @@ export interface LoadedBinary {
const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB
/** Hard ceiling QQ's file protocol supports — used by group/private files. */
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB
/** Local / HTTP flash sources. Official fileset max is unknown; reuse the
* group/private file ceiling so create_flash_task is not stuck on
* `loadBinarySource`'s 1 GiB default. */
export const FLASH_TRANSFER_MAX_BYTES = FILE_UPLOAD_MAX_BYTES;
/** Inline `base64://` / `data:` flash sources still decode into RAM inside
* `stageSourceToDisk`, so they keep the 1 GiB buffered-load ceiling. */
export const FLASH_TRANSFER_INLINE_MAX_BYTES = DEFAULT_MAX_BINARY_SIZE;
const FETCH_TIMEOUT_MS = 60_000;
/**