From 7b91903f804eea0957504902463f17482934012a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 5 Jul 2026 02:37:56 +0800 Subject: [PATCH] feat(highway): add streaming file hasher hashFileStreaming (phase 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Single-pass, disk-streaming replacement for the buffered `computeHashes` + `computeVideoSha1Blocks` (+ offline-file head md5): reads the file 1 MiB at a time so hashing a multi-GiB upload never buffers the whole file. Reproduces the buffered helpers exactly — whole-file md5/sha1, the per-1 MiB intermediate SHA1 state snapshots plus the finalized whole-file SHA1, and an optional md5 over the first N bytes (`headLimit`, for `md510MCheckSum`). Additive only — not wired into any caller yet; the old helpers stay in place. Lands in a new leaf module to avoid a utils↔highway-client import cycle. A byte-oracle test asserts identity vs the buffered functions across sizes around the 1 MiB block boundary (empty, sub-block, exact multiples, ±1, multi-block + tail) and head limits across chunk boundaries. --- packages/core/tests/highway/hash-file.test.ts | 92 ++++++++++++++++++ packages/protocol/src/highway/hash-file.ts | 97 +++++++++++++++++++ 2 files changed, 189 insertions(+) create mode 100644 packages/core/tests/highway/hash-file.test.ts create mode 100644 packages/protocol/src/highway/hash-file.ts diff --git a/packages/core/tests/highway/hash-file.test.ts b/packages/core/tests/highway/hash-file.test.ts new file mode 100644 index 00000000..406096bc --- /dev/null +++ b/packages/core/tests/highway/hash-file.test.ts @@ -0,0 +1,92 @@ +// hashFileStreaming is the streaming replacement for the buffered +// `computeHashes` + `computeVideoSha1Blocks` (+ head-md5) used before an +// upload. The refactor's whole promise is byte-for-byte identity, so this +// test IS the oracle: for a spread of sizes around the 1 MiB block boundary +// (and a spread of head limits around chunk boundaries) it asserts the +// streaming result equals the buffered functions over the same bytes. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { promises as fsp } from 'fs'; +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 { computeHashes, computeMd5 } from '@snowluma/protocol/highway/utils'; +import { computeVideoSha1Blocks } from '@snowluma/protocol/highway/video-upload'; + +const MB = 1024 * 1024; + +function synth(size: number): Uint8Array { + const b = new Uint8Array(size); + for (let i = 0; i < size; i++) b[i] = (i * 131 + 7) & 0xff; + return b; +} + +function eq(a: Uint8Array, b: Uint8Array): boolean { + return Buffer.from(a).equals(Buffer.from(b)); +} + +describe('hashFileStreaming ≡ buffered computeHashes + computeVideoSha1Blocks + head-md5', () => { + let dir: string; + beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-hash-')); }); + afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); }); + + // Sizes chosen around the 1 MiB block boundary + sub-block + multi-block. + 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 / sha1Blocks match the buffered helpers`, async () => { + const data = synth(size); + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, data); + + const streamed = await hashFileStreaming(file); + const buffered = computeHashes(data); + const refBlocks = computeVideoSha1Blocks(data); + + 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.headMd5).toBeUndefined(); + + // sha1Blocks must match exactly — same count, same bytes, same order. + expect(streamed.sha1Blocks.length).toBe(refBlocks.length); + for (let i = 0; i < refBlocks.length; i++) { + expect(eq(streamed.sha1Blocks[i]!, refBlocks[i]!)).toBe(true); + } + }); + } + + it('headMd5 matches computeMd5(first N bytes) across boundaries (±1, block edge, ≥size)', async () => { + const size = 2 * MB + 500; + const data = synth(size); + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, data); + + // head limits: empty, tiny, mid-first-block, exact block boundary ±1, + // and past the end (must clamp to size). + const limits = [0, 1, 1000, MB - 1, MB, MB + 1, size - 1, size, size + 1]; + for (const L of limits) { + const streamed = await hashFileStreaming(file, { headLimit: L }); + const ref = computeMd5(data.subarray(0, Math.min(data.length, L))); + expect(streamed.headMd5).toBeDefined(); + expect(eq(streamed.headMd5!, ref)).toBe(true); + // The rest of the digests are unaffected by headLimit. + expect(streamed.md5Hex).toBe(computeHashes(data).md5Hex); + } + }); + + it('empty file: md5/sha1 of nothing, single finalized sha1 block, headMd5 of empty', async () => { + const file = path.join(dir, `${randomUUID()}.bin`); + fs.writeFileSync(file, new Uint8Array(0)); + const streamed = await hashFileStreaming(file, { headLimit: 10 }); + const buffered = computeHashes(new Uint8Array(0)); + expect(streamed.md5Hex).toBe(buffered.md5Hex); + expect(streamed.sha1Hex).toBe(buffered.sha1Hex); + expect(streamed.sha1Blocks.length).toBe(1); // just the finalized whole-file sha1 + expect(eq(streamed.sha1Blocks[0]!, buffered.sha1)).toBe(true); + expect(eq(streamed.headMd5!, computeMd5(new Uint8Array(0)))).toBe(true); + }); +}); diff --git a/packages/protocol/src/highway/hash-file.ts b/packages/protocol/src/highway/hash-file.ts new file mode 100644 index 00000000..a9a795b6 --- /dev/null +++ b/packages/protocol/src/highway/hash-file.ts @@ -0,0 +1,97 @@ +// Streaming file hasher for the disk-backed upload path (#stream-upload). +// +// The buffered path reads the whole file into RAM and calls +// `computeHashes(bytes)` + `computeVideoSha1Blocks(bytes)` (+ a head-md5 for +// offline files). This does the same in ONE sequential pass over the file, +// 1 MiB at a time, so a multi-GiB upload never buffers more than a chunk. +// +// It MUST be byte-for-byte identical to the buffered helpers — verified by +// `tests/highway/hash-file.test.ts` against `computeHashes` / +// `computeVideoSha1Blocks` / `computeMd5(head)` over the same bytes. + +import { createHash } from 'crypto'; +import { promises as fsp } from 'fs'; +import { FileChunkSource } from './highway-client'; +import { Sha1Stream } from './sha1-stream'; + +// Must match video-upload.ts's SHA1_STREAM_BLOCK_SIZE: the Highway video +// "block sha1" snapshots the running SHA1 state at every 1 MiB boundary. +const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024; + +export interface StreamedFileHashes { + md5: Uint8Array; + sha1: Uint8Array; + md5Hex: string; + sha1Hex: string; + /** Per-1 MiB intermediate SHA1 states (little-endian, un-finalized) plus a + * final entry that is the finalized whole-file SHA1 — the exact shape + * `computeVideoSha1Blocks` returns. Only meaningful for video; file uploads + * ignore it. */ + sha1Blocks: Uint8Array[]; + /** md5 of the first `headLimit` bytes — the offline-file `md510MCheckSum`. + * Present only when `headLimit` was passed. */ + headMd5?: Uint8Array; +} + +/** + * Hash a file on disk in a single streaming pass. Equivalent to + * `computeHashes` + `computeVideoSha1Blocks` (+ `computeMd5(bytes[0:headLimit])` + * when `headLimit` is given) over the file's bytes, without buffering the file. + */ +export async function hashFileStreaming( + filePath: string, + opts?: { headLimit?: number }, +): Promise { + const { size } = await fsp.stat(filePath); + const src = await FileChunkSource.open(filePath, size); + try { + const md5 = createHash('md5'); + const sha1 = createHash('sha1'); + const headLimit = opts?.headLimit; + const headMd5 = headLimit !== undefined ? createHash('md5') : null; + let headRemaining = headLimit ?? 0; + + // Running SHA1 state fed only full 1 MiB chunks, snapshotted at each 1 MiB + // boundary — mirrors computeVideoSha1Blocks (which feeds 64-byte blocks and + // snapshots at 1 MiB; identical result since 1 MiB is a multiple of 64 and + // Sha1Stream buffers internally). The sub-1 MiB tail is never snapshotted, + // so it need not be fed to the block-sha1 at all. + const blockSha1 = new Sha1Stream(); + const sha1Blocks: Uint8Array[] = []; + + let offset = 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); + if (headMd5 && headRemaining > 0) { + const take = Math.min(headRemaining, chunk.length); + headMd5.update(chunk.subarray(0, take)); + headRemaining -= take; + } + if (len === SHA1_STREAM_BLOCK_SIZE) { + blockSha1.update(chunk); + sha1Blocks.push(blockSha1.hash(true)); // little-endian intermediate state + } + offset += len; + } + + const sha1Digest = sha1.digest(); + // Final entry: the finalized whole-file SHA1 — the last element + // computeVideoSha1Blocks pushes. + sha1Blocks.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'), + sha1Blocks, + headMd5: headMd5 ? new Uint8Array(headMd5.digest()) : undefined, + }; + } finally { + await src.close(); + } +}