refactor(highway): introduce ChunkSource for uploadHighwayHttp (phase 1)
Prep for streaming large media uploads from disk instead of buffering the whole file in RAM. Add a `ChunkSource` abstraction — `BufferChunkSource` (in-memory, byte-for-byte the old path) and `FileChunkSource` (disk-backed, reads exact-length chunks via a FileHandle, loops on short reads, throws on unexpected EOF) — and change `uploadHighwayHttp` to consume a `ChunkSource` instead of a `Uint8Array`. The uploader now owns the source and closes it once in `finally` (best-effort; never masks a primary upload error). Pure structural refactor: no streaming is wired yet. All five call sites (pipeline runPuts, group + private file upload, personal + group avatar) wrap their bytes in `BufferChunkSource`, so behavior is unchanged. Adds a byte-oracle test proving FileChunkSource ≡ BufferChunkSource across block boundaries, plus short-read/EOF/empty-input coverage.
This commit is contained in:
11 files changed
+276
-83
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { toHexUpper } from '@snowluma/common/hex';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { FileUploadExt } from '@snowluma/proto-defs/highway';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import type { Bridge } from '../bridge';
|
||||
@@ -330,7 +330,7 @@ export class GroupFileApi {
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 71, loaded.bytes, hashes.md5, ext);
|
||||
await uploadHighwayHttp(bridge, session, 71, new BufferChunkSource(loaded.bytes), hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: file is on the server, now publish it as a chat message.
|
||||
@@ -490,7 +490,7 @@ export class GroupFileApi {
|
||||
);
|
||||
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 95, loaded.bytes, hashes.md5, ext);
|
||||
await uploadHighwayHttp(bridge, session, 95, new BufferChunkSource(loaded.bytes), hashes.md5, ext);
|
||||
}
|
||||
|
||||
// Stage 3: publish the file as a c2c chat message. C2C files use
|
||||
|
||||
@@ -10,7 +10,7 @@ import { DeleteCustomFace } from '@snowluma/protocol/oidb-services/custom-face/d
|
||||
import { ModifyCustomFace } from '@snowluma/protocol/oidb-services/custom-face/modify-custom-face';
|
||||
import { MoveCustomFace } from '@snowluma/protocol/oidb-services/custom-face/move-custom-face';
|
||||
import { OrderCustomFace } from '@snowluma/protocol/oidb-services/custom-face/order-custom-face';
|
||||
import { fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { BufferChunkSource, fetchHighwaySession, uploadHighwayHttp } from '@snowluma/protocol/highway';
|
||||
import { computeHashes, loadBinarySource } from '@snowluma/protocol/highway/utils';
|
||||
import { GetLike, type LikeInfo } from '@snowluma/protocol/oidb-services/profile/get-like';
|
||||
import { GetUnidirectionalFriendList, type UnidirectionalFriendEntry } from '@snowluma/protocol/oidb-services/profile/get-unidirectional-friend-list';
|
||||
@@ -93,7 +93,7 @@ export class ProfileApi {
|
||||
|
||||
const hashes = computeHashes(loaded.bytes);
|
||||
const session = await fetchHighwaySession(bridge);
|
||||
await uploadHighwayHttp(bridge, session, 90, loaded.bytes, hashes.md5, new Uint8Array(0));
|
||||
await uploadHighwayHttp(bridge, session, 90, new BufferChunkSource(loaded.bytes), hashes.md5, new Uint8Array(0));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -120,7 +120,7 @@ export class ProfileApi {
|
||||
field5: 3,
|
||||
field6: 1,
|
||||
});
|
||||
await uploadHighwayHttp(bridge, session, 3000, loaded.bytes, hashes.md5, extra);
|
||||
await uploadHighwayHttp(bridge, session, 3000, new BufferChunkSource(loaded.bytes), hashes.md5, extra);
|
||||
}
|
||||
|
||||
// ─────────────── queries on me / my contacts ───────────────
|
||||
|
||||
@@ -26,6 +26,7 @@ import type {
|
||||
vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({})),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
}));
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/utils', () => ({
|
||||
|
||||
@@ -28,6 +28,7 @@ vi.mock('@snowluma/protocol/bridge-oidb', async () => {
|
||||
vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({})),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
}));
|
||||
|
||||
vi.mock('@snowluma/protocol/highway/utils', () => ({
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// ChunkSource is the buffer-or-disk abstraction the highway PUT loop reads
|
||||
// through (#stream-upload). The whole streaming refactor rests on one
|
||||
// invariant: a FileChunkSource must yield BYTE-FOR-BYTE the same chunks as a
|
||||
// BufferChunkSource over the same file, at every (offset, length) the uploader
|
||||
// asks for. These tests are that byte-oracle.
|
||||
|
||||
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 { BufferChunkSource, FileChunkSource } from '@snowluma/protocol/highway';
|
||||
|
||||
// Mirrors highway-client's HIGHWAY_BLOCK_SIZE chunk walk without the network:
|
||||
// step through [0,size) in `block` strides, last chunk short by construction.
|
||||
async function collectChunks(src: { size: number; read(o: number, l: number): Promise<Uint8Array> }, block: number) {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let offset = 0;
|
||||
while (offset < src.size) {
|
||||
const len = Math.min(block, src.size - offset);
|
||||
chunks.push(new Uint8Array(await src.read(offset, len)));
|
||||
offset += len;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
describe('ChunkSource — FileChunkSource ≡ BufferChunkSource', () => {
|
||||
let dir: string;
|
||||
beforeAll(async () => { dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-chunk-')); });
|
||||
afterAll(async () => { await fsp.rm(dir, { recursive: true, force: true }); });
|
||||
|
||||
// Sizes chosen around block boundaries: exact multiple, +1, -1, tiny, empty.
|
||||
for (const [label, size, block] of [
|
||||
['empty', 0, 7],
|
||||
['tiny (< block)', 5, 7],
|
||||
['exact multiple', 21, 7],
|
||||
['one past a boundary', 22, 7],
|
||||
['one before a boundary', 20, 7],
|
||||
['single full block', 7, 7],
|
||||
] as const) {
|
||||
it(`${label}: chunks + size are byte-identical (size=${size}, block=${block})`, async () => {
|
||||
const data = new Uint8Array(size);
|
||||
for (let i = 0; i < size; i++) data[i] = (i * 31 + 7) & 0xff;
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
|
||||
const buf = new BufferChunkSource(data);
|
||||
const fch = await FileChunkSource.open(file, size);
|
||||
try {
|
||||
expect(fch.size).toBe(buf.size);
|
||||
expect(fch.size).toBe(size);
|
||||
const a = await collectChunks(buf, block);
|
||||
const b = await collectChunks(fch, block);
|
||||
expect(b.length).toBe(a.length);
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
expect(Buffer.from(b[i]!).equals(Buffer.from(a[i]!))).toBe(true);
|
||||
}
|
||||
// Reassembled stream equals the original bytes exactly.
|
||||
expect(Buffer.concat(b.map((c) => Buffer.from(c))).equals(Buffer.from(data))).toBe(true);
|
||||
} finally {
|
||||
await fch.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it('FileChunkSource.read returns EXACTLY the requested length (no short read leaks)', async () => {
|
||||
const data = new Uint8Array(1000).map((_, i) => (i * 13) & 0xff);
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
const fch = await FileChunkSource.open(file, data.length);
|
||||
try {
|
||||
for (const [off, len] of [[0, 1], [0, 1000], [37, 200], [999, 1], [500, 500]] as const) {
|
||||
const got = await fch.read(off, len);
|
||||
expect(got.length).toBe(len);
|
||||
expect(Buffer.from(got).equals(Buffer.from(data.subarray(off, off + len)))).toBe(true);
|
||||
}
|
||||
} finally {
|
||||
await fch.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('FileChunkSource.read throws on unexpected EOF (request past end)', async () => {
|
||||
const data = new Uint8Array(10);
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, data);
|
||||
const fch = await FileChunkSource.open(file, 10);
|
||||
try {
|
||||
await expect(fch.read(5, 20)).rejects.toThrow(/unexpected EOF/);
|
||||
} finally {
|
||||
await fch.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('BufferChunkSource.close and FileChunkSource.close both resolve (idempotent contract)', async () => {
|
||||
const buf = new BufferChunkSource(new Uint8Array(3));
|
||||
await expect(buf.close()).resolves.toBeUndefined();
|
||||
const file = path.join(dir, `${randomUUID()}.bin`);
|
||||
fs.writeFileSync(file, new Uint8Array(3));
|
||||
const fch = await FileChunkSource.open(file, 3);
|
||||
await expect(fch.close()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -88,7 +88,7 @@ vi.mock('net', () => ({
|
||||
createConnection: createConnectionMock,
|
||||
}));
|
||||
|
||||
import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway';
|
||||
import { uploadHighwayHttp, BufferChunkSource, type HighwaySession } from '@snowluma/protocol/highway';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
@@ -130,7 +130,7 @@ describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
// 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。
|
||||
const bytes = new Uint8Array(512 * 1024);
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createdSockets[0]!.destroyed).toBe(true);
|
||||
@@ -142,7 +142,7 @@ describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
// 关闭,新实现必须为每个 chunk 各开一个 socket。
|
||||
const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
expect(createdSockets).toHaveLength(2);
|
||||
@@ -154,8 +154,15 @@ describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
it('opens N connections for N chunks (3 chunks here)', async () => {
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('a zero-length source opens ZERO connections (empty-input invariant)', async () => {
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, new BufferChunkSource(new Uint8Array(0)), new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -153,9 +153,12 @@ describe('runNtv2Upload — two images in one message (sequential)', () => {
|
||||
|
||||
// The PUT receives image-2's bytes, image-2's md5, and the
|
||||
// image-2-derived extend (NOT image-1's data).
|
||||
const [, , cmdId, putBytes, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
|
||||
const [, , cmdId, putSource, putMd5, putExtend] = vi.mocked(highway.uploadHighwayHttp).mock.calls[0]!;
|
||||
expect(cmdId).toBe(1004);
|
||||
expect(putBytes).toBe(image2Bytes);
|
||||
// The PUT source is a ChunkSource wrapping image-2's bytes — verify it
|
||||
// yields image-2 exactly (not image-1) through its public read().
|
||||
expect(putSource.size).toBe(image2Bytes.length);
|
||||
expect(Buffer.from(await putSource.read(0, putSource.size)).equals(Buffer.from(image2Bytes))).toBe(true);
|
||||
expect(putMd5).toBe(image2Md5);
|
||||
|
||||
// Decode the extend bytes; uKey + fileUuid must come from image-2's
|
||||
|
||||
@@ -12,6 +12,7 @@ vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
PRIVATE_IMAGE_CMD_ID: 1003,
|
||||
GROUP_IMAGE_CMD_ID: 1004,
|
||||
}));
|
||||
|
||||
@@ -17,6 +17,7 @@ vi.mock('@snowluma/protocol/highway', () => ({
|
||||
fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })),
|
||||
uploadHighwayHttp: vi.fn(async () => undefined),
|
||||
buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])),
|
||||
BufferChunkSource: class BufferChunkSource { constructor(readonly bytes: Uint8Array) {} },
|
||||
PRIVATE_IMAGE_CMD_ID: 1003,
|
||||
GROUP_IMAGE_CMD_ID: 1004,
|
||||
}));
|
||||
|
||||
Reference in new issue
Block a user