feat(highway): add stageSourceToDisk + shared HTTP downloader (phase 3)
Stage any upload source onto a local disk path so the uploader can stream it without buffering the whole file. `stageSourceToDisk(source, maxBytes)` unifies: local file:// / raw path → hardlink into an owned stage dir (O(1); the inode link pins the bytes against a caller-side unlink/retention), streamed-copy fallback on any link() failure; http(s):// → stream to a .part file; base64:// → maxBytes-checked decode to a .part file. Temps are finalized atomically (fsync file → rename → fsync dir); a TTL reaper reaps crash-orphaned temps while an in-use `active` set protects live uploads (a hardlink keeps the source's old mtime, so the staged path is reserved in `active` before it appears on disk). To avoid divergence, the existing `loadBinarySource` HTTP transport is extracted into a shared `downloadHttp(source, name, maxBytes, makeSink)` engine (browser UA, redirect, timeout, Referer retry, declared + streamed size caps, noRetry); `loadBinarySource` now drives it with an in-memory sink — behavior unchanged. Additive only — not yet wired into video/file uploads. Tests cover the retention race (hardlink survives the original's deletion), the reaper's active-set protection, size caps, symlink resolution, the copy fallback, the Referer retry reusing the .part, and streamed-overflow .part cleanup.
This commit is contained in:
3 files changed
+574
-71
No files matched your search
@@ -0,0 +1,214 @@
|
||||
// stageSourceToDisk unifies every upload source onto a local disk path so the
|
||||
// streaming uploader never buffers a whole file. These tests cover the three
|
||||
// source kinds, the crash-safety contract (hardlink survives caller-side
|
||||
// deletion — the retention race Codex flagged), size caps, symlink resolution,
|
||||
// cleanup, and the orphan reaper's active-set safety.
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } 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 { stageSourceToDisk, sweepStagedUploads, STAGE_DIR } from '@snowluma/protocol/highway/stage';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
let scratch: string;
|
||||
|
||||
async function readStaged(p: string): Promise<Buffer> {
|
||||
return fsp.readFile(p);
|
||||
}
|
||||
|
||||
beforeEach(async () => { scratch = await fsp.mkdtemp(path.join(os.tmpdir(), 'sl-stage-src-')); });
|
||||
afterEach(async () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
await fsp.rm(scratch, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — base64', () => {
|
||||
it('stages base64 bytes to disk', async () => {
|
||||
const data = Buffer.from('hello base64 world');
|
||||
const staged = await stageSourceToDisk(`base64://${data.toString('base64')}`, 1024);
|
||||
try {
|
||||
expect(staged.fileSize).toBe(data.length);
|
||||
expect(staged.fileName).toBe('');
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
expect(staged.filePath.startsWith(STAGE_DIR)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('rejects oversized base64 on decoded length (before allocation) and leaves no temp', async () => {
|
||||
const big = Buffer.alloc(4096).toString('base64');
|
||||
await expect(stageSourceToDisk(`base64://${big}`, 64)).rejects.toThrow(/too large/);
|
||||
const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
|
||||
expect(parts).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — http', () => {
|
||||
it('streams an http download to disk with the URL basename', async () => {
|
||||
const body = new Uint8Array([9, 8, 7, 6, 5]);
|
||||
globalThis.fetch = (async () => new Response(body, { status: 200 })) as typeof fetch;
|
||||
const staged = await stageSourceToDisk('https://example.test/clip.mp4', 1024);
|
||||
try {
|
||||
expect(staged.fileName).toBe('clip.mp4');
|
||||
expect(staged.fileSize).toBe(body.length);
|
||||
expect((await readStaged(staged.filePath)).equals(Buffer.from(body))).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('rejects an oversized http download and cleans up the .part', async () => {
|
||||
globalThis.fetch = (async () => new Response(new Uint8Array(4096), {
|
||||
status: 200, headers: { 'content-length': '4096' },
|
||||
})) as typeof fetch;
|
||||
await expect(stageSourceToDisk('https://example.test/big.bin', 64)).rejects.toThrow(/too large/);
|
||||
const leftover = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
|
||||
expect(leftover).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a STREAMED overflow (no Content-Length) after the sink+.part exist, then cleans up', async () => {
|
||||
// No content-length → the size cap only trips mid-stream, AFTER fileSink has
|
||||
// opened the .part. This exercises fileSink.discard()'s close-before-unlink.
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(c) { for (let i = 0; i < 8; i++) c.enqueue(new Uint8Array(4096)); c.close(); },
|
||||
});
|
||||
globalThis.fetch = (async () => new Response(stream, { status: 200 })) as typeof fetch;
|
||||
await expect(stageSourceToDisk('https://example.test/stream.bin', 4 * 1024)).rejects.toThrow(/too large/);
|
||||
const parts = (await fsp.readdir(STAGE_DIR).catch(() => [] as string[])).filter((n) => n.endsWith('.part'));
|
||||
expect(parts).toEqual([]);
|
||||
});
|
||||
|
||||
it('retries with a Referer after a network failure and stages the retry body cleanly (no attempt-1 leftovers)', async () => {
|
||||
const body = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
|
||||
let n = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
n += 1;
|
||||
if (n === 1) throw new TypeError('fetch failed'); // anti-bot RST on attempt 1
|
||||
return new Response(body, { status: 200 });
|
||||
}) as typeof fetch;
|
||||
const staged = await stageSourceToDisk('https://example.test/r.mp4', 1024);
|
||||
try {
|
||||
expect(n).toBe(2);
|
||||
expect(staged.fileSize).toBe(body.length);
|
||||
expect((await readStaged(staged.filePath)).equals(Buffer.from(body))).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — local files', () => {
|
||||
it('hardlinks a local file:// source and survives caller-side deletion (retention race)', async () => {
|
||||
const src = path.join(scratch, 'video.mp4');
|
||||
const data = Buffer.from('the caller-owned temp that retention will delete');
|
||||
fs.writeFileSync(src, data);
|
||||
|
||||
const staged = await stageSourceToDisk(pathToFileURL(src).href, 1 << 20);
|
||||
try {
|
||||
expect(staged.fileName).toBe('video.mp4');
|
||||
expect(staged.fileSize).toBe(data.length);
|
||||
// Simulate upload_file_stream's retention timer unlinking the original
|
||||
// BETWEEN the hash pass and the upload pass.
|
||||
await fsp.unlink(src);
|
||||
// The hardlink kept the inode alive — the staged path is still fully readable.
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('accepts a raw local path and preserves its basename', async () => {
|
||||
const src = path.join(scratch, 'doc.bin');
|
||||
fs.writeFileSync(src, Buffer.from([1, 2, 3, 4]));
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
try {
|
||||
expect(staged.fileName).toBe('doc.bin');
|
||||
expect(staged.fileSize).toBe(4);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('resolves a symlink to its target but keeps the symlink basename', async () => {
|
||||
const target = path.join(scratch, 'real-xyz.tmp');
|
||||
const linkPath = path.join(scratch, 'friendly.mp4');
|
||||
const data = Buffer.from('symlinked content');
|
||||
fs.writeFileSync(target, data);
|
||||
fs.symlinkSync(target, linkPath);
|
||||
const staged = await stageSourceToDisk(linkPath, 1 << 20);
|
||||
try {
|
||||
expect(staged.fileName).toBe('friendly.mp4'); // original basename, not the target's
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
});
|
||||
|
||||
it('falls back to a streamed copy when hardlink fails (e.g. cross-filesystem EXDEV)', async () => {
|
||||
const src = path.join(scratch, 'xfs.mp4');
|
||||
const data = Buffer.from('content that must copy when link() is refused');
|
||||
fs.writeFileSync(src, data);
|
||||
const linkSpy = vi.spyOn(fsp, 'link').mockRejectedValueOnce(Object.assign(new Error('EXDEV'), { code: 'EXDEV' }));
|
||||
try {
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
try {
|
||||
expect(linkSpy).toHaveBeenCalledOnce();
|
||||
expect(staged.fileName).toBe('xfs.mp4');
|
||||
expect(staged.fileSize).toBe(data.length);
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
// The copy is an independent file — deleting the source leaves it intact.
|
||||
await fsp.unlink(src);
|
||||
expect((await readStaged(staged.filePath)).equals(data)).toBe(true);
|
||||
} finally { await staged.cleanup(); }
|
||||
} finally { linkSpy.mockRestore(); }
|
||||
});
|
||||
|
||||
it('rejects a non-regular file (directory)', async () => {
|
||||
await expect(stageSourceToDisk(scratch, 1 << 20)).rejects.toThrow(/not a regular file/);
|
||||
});
|
||||
|
||||
it('rejects an oversized local file before staging', async () => {
|
||||
const src = path.join(scratch, 'huge.bin');
|
||||
fs.writeFileSync(src, Buffer.alloc(200));
|
||||
await expect(stageSourceToDisk(src, 64)).rejects.toThrow(/too large: 200 > 64/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stageSourceToDisk — cleanup + reaper', () => {
|
||||
it('cleanup removes the staged temp and is idempotent', async () => {
|
||||
const src = path.join(scratch, 'c.bin');
|
||||
fs.writeFileSync(src, Buffer.from([1]));
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
expect(fs.existsSync(staged.filePath)).toBe(true);
|
||||
await staged.cleanup();
|
||||
expect(fs.existsSync(staged.filePath)).toBe(false);
|
||||
await expect(staged.cleanup()).resolves.toBeUndefined(); // idempotent, no throw
|
||||
});
|
||||
|
||||
it('reaper removes an old ORPHAN temp but NEVER an in-flight (active) staged file', async () => {
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
const old = Date.now() - 60 * 60 * 1000; // 1h ago
|
||||
|
||||
// Orphan: a temp NOT tracked in `active` (as a crash would leave), aged out.
|
||||
const orphan = path.join(STAGE_DIR, `stage-${randomUUID()}.orphan`);
|
||||
fs.writeFileSync(orphan, Buffer.from('crash leftover'));
|
||||
fs.utimesSync(orphan, new Date(old), new Date(old));
|
||||
|
||||
// In-flight: a real staged file (registered in `active`), also aged out —
|
||||
// the active-set must protect it from the age sweep.
|
||||
const src = path.join(scratch, 'inflight.bin');
|
||||
fs.writeFileSync(src, Buffer.from('being uploaded'));
|
||||
const staged = await stageSourceToDisk(src, 1 << 20);
|
||||
fs.utimesSync(staged.filePath, new Date(old), new Date(old)); // read-only upload → stale mtime
|
||||
|
||||
const removed = await sweepStagedUploads(Date.now());
|
||||
expect(fs.existsSync(orphan)).toBe(false); // orphan reaped
|
||||
expect(fs.existsSync(staged.filePath)).toBe(true); // active file preserved
|
||||
expect(removed).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await staged.cleanup();
|
||||
});
|
||||
|
||||
it('reaper leaves a recent orphan alone', async () => {
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
const recent = path.join(STAGE_DIR, `stage-${randomUUID()}.recent`);
|
||||
fs.writeFileSync(recent, Buffer.from('fresh'));
|
||||
try {
|
||||
await sweepStagedUploads(Date.now());
|
||||
expect(fs.existsSync(recent)).toBe(true);
|
||||
} finally { await fsp.rm(recent, { force: true }); }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
// Stage any upload source onto a local disk path so the uploader can stream it
|
||||
// (#stream-upload). Unifies the three source kinds into one "here is a file on
|
||||
// disk + its size + a cleanup" contract, so the streaming hash pass and the
|
||||
// FileChunkSource PUT never have to care where the bytes came from:
|
||||
//
|
||||
// file:// / raw path → hardlink into our own stage dir (O(1); the extra inode
|
||||
// link pins the bytes so a caller-side retention/unlink
|
||||
// — e.g. upload_file_stream's timer — can't delete the
|
||||
// data mid-send). Copy fallback on any link() failure.
|
||||
// http(s):// → stream the download to a .part file, fsync, atomic
|
||||
// rename (shares the exact transport of loadBinarySource
|
||||
// via downloadHttp — same UA/redirect/timeout/retry/caps).
|
||||
// base64:// → enforce maxBytes on the DECODED length, then decode to
|
||||
// a .part file and rename.
|
||||
//
|
||||
// Crash safety: staged temps are written `.part` → fsync → rename → fsync(dir),
|
||||
// so a partial file is never consumed; a background TTL reaper reaps temps left
|
||||
// by a crash, skipping any path currently in use (the `active` set), so it can
|
||||
// never delete an in-flight upload.
|
||||
|
||||
import { promises as fsp } from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { downloadHttp, resolveLocalFilePath, type DownloadSink } from './utils';
|
||||
|
||||
const log = createLogger('Highway.Stage');
|
||||
|
||||
export const STAGE_DIR = path.join(os.tmpdir(), 'snowluma-stage');
|
||||
// Must comfortably exceed the slowest plausible single upload (a 1.5 GiB PUT at
|
||||
// a few MB/s is ~5-10 min). Only unregistered (crash-orphaned) temps are reaped.
|
||||
const STAGE_TTL_MS = 30 * 60 * 1000;
|
||||
const REAPER_INTERVAL_MS = 5 * 60 * 1000;
|
||||
|
||||
/** Absolute paths currently in use (being written, or a live staged file). The
|
||||
* reaper never touches these — an in-flight upload's file is read-only so its
|
||||
* mtime won't advance, and an age-only sweep would otherwise delete it. */
|
||||
const active = new Set<string>();
|
||||
|
||||
export interface StagedSource {
|
||||
/** Local disk path the uploader reads from. */
|
||||
filePath: string;
|
||||
fileSize: number;
|
||||
/** Caller-facing name (URL basename / original local basename); '' for base64. */
|
||||
fileName: string;
|
||||
/** Remove the staged temp (our hardlink/copy/downloaded file). Idempotent,
|
||||
* best-effort; never throws. Never touches the caller's original file. */
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
|
||||
let reaperTimer: NodeJS.Timeout | null = null;
|
||||
function ensureReaper(): void {
|
||||
if (reaperTimer) return;
|
||||
reaperTimer = setInterval(() => { void sweepStagedUploads(); }, REAPER_INTERVAL_MS);
|
||||
reaperTimer.unref(); // never pin the event loop
|
||||
void sweepStagedUploads(); // startup sweep of crash orphans
|
||||
}
|
||||
|
||||
/** Reap staged temps older than the TTL, skipping any path currently in use.
|
||||
* Best-effort; never throws. Exposed for an explicit startup/interval hook. */
|
||||
export async function sweepStagedUploads(now: number = Date.now()): Promise<number> {
|
||||
let removed = 0;
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fsp.readdir(STAGE_DIR);
|
||||
} catch {
|
||||
return 0; // dir not created yet
|
||||
}
|
||||
await Promise.all(names.map(async (n) => {
|
||||
const p = path.join(STAGE_DIR, n);
|
||||
if (active.has(p)) return; // in-flight — never reap
|
||||
try {
|
||||
const s = await fsp.stat(p);
|
||||
if (now - s.mtimeMs > STAGE_TTL_MS) {
|
||||
await fsp.rm(p, { force: true });
|
||||
removed += 1;
|
||||
}
|
||||
} catch { /* vanished / racing cleanup */ }
|
||||
}));
|
||||
if (removed > 0) log.debug('reaped %d stale staged upload temp(s)', removed);
|
||||
return removed;
|
||||
}
|
||||
|
||||
function tempPaths(ext: string): { partPath: string; finalPath: string } {
|
||||
const id = randomUUID();
|
||||
const base = path.join(STAGE_DIR, `stage-${id}${ext}`);
|
||||
return { partPath: `${base}.part`, finalPath: base };
|
||||
}
|
||||
|
||||
/** fsync the file's directory entry so the rename survives a crash (POSIX). */
|
||||
async function fsyncDir(): Promise<void> {
|
||||
try {
|
||||
const dh = await fsp.open(STAGE_DIR, 'r');
|
||||
try { await dh.sync(); } finally { await dh.close(); }
|
||||
} catch { /* some platforms reject directory fsync — best effort */ }
|
||||
}
|
||||
|
||||
async function finalizeRename(partPath: string, finalPath: string): Promise<void> {
|
||||
await fsp.rename(partPath, finalPath);
|
||||
await fsyncDir();
|
||||
}
|
||||
|
||||
function registerStaged(filePath: string, fileSize: number, fileName: string): StagedSource {
|
||||
active.add(filePath);
|
||||
let done = false;
|
||||
return {
|
||||
filePath,
|
||||
fileSize,
|
||||
fileName,
|
||||
async cleanup() {
|
||||
if (done) return;
|
||||
done = true;
|
||||
active.delete(filePath);
|
||||
await fsp.unlink(filePath).catch(() => { /* best-effort */ });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Disk sink for `downloadHttp`: streams chunks to a FileHandle, fsyncs on
|
||||
* success, and closes-before-unlink on failure. Backpressure comes from
|
||||
* awaiting each `fh.write`. */
|
||||
function fileSink(partPath: string): DownloadSink<void> {
|
||||
let opened: Promise<import('fs').promises.FileHandle> | null = null;
|
||||
const open = () => (opened ??= fsp.open(partPath, 'w'));
|
||||
return {
|
||||
async write(chunk) { const fh = await open(); await fh.write(chunk); },
|
||||
async done() {
|
||||
const fh = await open(); // create even for an empty body
|
||||
await fh.sync();
|
||||
await fh.close();
|
||||
},
|
||||
async discard() {
|
||||
if (opened) { try { const fh = await opened; await fh.close(); } catch { /* already closed */ } }
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** base64 decoded byte length without allocating the buffer. */
|
||||
function base64DecodedLength(b64: string): number {
|
||||
const clean = b64.replace(/[^A-Za-z0-9+/=]/g, '');
|
||||
const pad = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
|
||||
return Math.floor((clean.length * 3) / 4) - pad;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage `source` onto a local disk path. `maxBytes` bounds the size (rejected
|
||||
* before any large allocation for base64, before reading for local files, and
|
||||
* incrementally for http). The returned `cleanup()` MUST be called when the
|
||||
* upload is done (or fails) to remove the staged temp.
|
||||
*/
|
||||
export async function stageSourceToDisk(source: string, maxBytes: number): Promise<StagedSource> {
|
||||
if (!source) throw new Error('stage source is empty');
|
||||
ensureReaper();
|
||||
await fsp.mkdir(STAGE_DIR, { recursive: true });
|
||||
|
||||
// ── base64:// ──────────────────────────────────────────────────────────
|
||||
if (/^base64:\/\//i.test(source)) {
|
||||
const b64 = source.slice(9);
|
||||
const decodedLen = base64DecodedLength(b64);
|
||||
if (decodedLen > maxBytes) {
|
||||
throw new Error(`stage source too large: ${decodedLen} > ${maxBytes}`);
|
||||
}
|
||||
const bytes = Buffer.from(b64, 'base64');
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new Error(`stage source too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
const { partPath, finalPath } = tempPaths('.bin');
|
||||
active.add(partPath);
|
||||
try {
|
||||
const fh = await fsp.open(partPath, 'w');
|
||||
try { await fh.write(bytes); await fh.sync(); } finally { await fh.close(); }
|
||||
await finalizeRename(partPath, finalPath);
|
||||
} catch (e) {
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
throw e;
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
log.debug('staged base64 source (%d bytes)', bytes.length);
|
||||
return registerStaged(finalPath, bytes.length, '');
|
||||
}
|
||||
|
||||
// ── http(s):// ─────────────────────────────────────────────────────────
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const { partPath, finalPath } = tempPaths('.bin');
|
||||
active.add(partPath);
|
||||
let fileName = '';
|
||||
try {
|
||||
const r = await downloadHttp<void>(source, 'stage', maxBytes, () => fileSink(partPath));
|
||||
fileName = r.fileName;
|
||||
await finalizeRename(partPath, finalPath);
|
||||
} catch (e) {
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
throw e;
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
const { size } = await fsp.stat(finalPath);
|
||||
log.debug('staged http source %s (%d bytes)', fileName || '(unnamed)', size);
|
||||
return registerStaged(finalPath, size, fileName);
|
||||
}
|
||||
|
||||
// ── local path / file:// ───────────────────────────────────────────────
|
||||
const local = resolveLocalFilePath(source);
|
||||
if (!local) throw new Error('stage source is not a local file');
|
||||
const real = await fsp.realpath(local); // resolve symlinks — hardlink the target, not the link
|
||||
const st = await fsp.stat(real);
|
||||
if (!st.isFile()) throw new Error(`stage source is not a regular file: ${local}`);
|
||||
if (st.size > maxBytes) throw new Error(`stage source too large: ${st.size} > ${maxBytes}`);
|
||||
const fileName = path.basename(local); // caller-facing name (before symlink resolution)
|
||||
const { partPath, finalPath } = tempPaths(path.extname(local) || '.bin');
|
||||
|
||||
// Reserve finalPath in `active` BEFORE it exists on disk. A hardlink inherits
|
||||
// the source's (often old) mtime, so — unlike the fresh-mtime http/base64/copy
|
||||
// temps whose TTL saves them during the pre-register gap — only the active-set
|
||||
// can keep the age reaper from deleting this live staged file in the window
|
||||
// between link and registerStaged.
|
||||
active.add(finalPath);
|
||||
let staged: 'link' | 'copy';
|
||||
try {
|
||||
try {
|
||||
await fsp.link(real, finalPath); // O(1) hardlink; pins the inode against caller-side unlink
|
||||
staged = 'link';
|
||||
} catch {
|
||||
// Any link() failure (cross-fs EXDEV, hardlink protection, permissions,
|
||||
// link-count/platform limits) — fall back to a streamed copy of the
|
||||
// readable source (disk-to-disk, never buffered in RAM).
|
||||
active.add(partPath);
|
||||
try {
|
||||
await fsp.copyFile(real, partPath);
|
||||
const fh = await fsp.open(partPath, 'r+'); // fsync copied data before rename
|
||||
try { await fh.sync(); } finally { await fh.close(); }
|
||||
await finalizeRename(partPath, finalPath);
|
||||
staged = 'copy';
|
||||
} finally {
|
||||
active.delete(partPath);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
active.delete(finalPath);
|
||||
await fsp.unlink(finalPath).catch(() => { /* best-effort */ });
|
||||
await fsp.unlink(partPath).catch(() => { /* best-effort */ });
|
||||
throw e;
|
||||
}
|
||||
log.debug('staged local source %s via %s (%d bytes)', fileName, staged, st.size);
|
||||
return registerStaged(finalPath, st.size, fileName);
|
||||
}
|
||||
@@ -82,10 +82,104 @@ export function resolveLocalFilePath(source: string): string | null {
|
||||
* Tag a size-limit error so the HTTP retry path leaves it alone — retrying
|
||||
* a too-large response just re-downloads the same oversized body.
|
||||
*/
|
||||
function tooLarge(message: string): Error {
|
||||
export function tooLarge(message: string): Error {
|
||||
return Object.assign(new Error(message), { noRetry: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a download's bytes go. `loadBinarySource` uses an in-memory sink;
|
||||
* `stageSourceToDisk` uses a disk-file sink. A fresh sink is built per fetch
|
||||
* attempt and `discard()`ed on failure so a Referer retry starts clean.
|
||||
*/
|
||||
export interface DownloadSink<T> {
|
||||
write(chunk: Uint8Array): Promise<void> | void;
|
||||
done(): Promise<T> | T;
|
||||
discard(): Promise<void> | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared HTTP download engine for both the buffered and the disk-streaming
|
||||
* paths — the single owner of the observable download behavior: browser UA +
|
||||
* Accept, redirect follow, 60s timeout, incremental `maxBytes` enforcement
|
||||
* (declared Content-Length AND streamed total, `noRetry`-tagged), and one
|
||||
* Referer retry on a non-size failure. Bytes are delivered chunk-by-chunk to a
|
||||
* caller-provided sink so the same length-checking transport feeds either RAM
|
||||
* or disk.
|
||||
*/
|
||||
export async function downloadHttp<T>(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
maxBytes: number,
|
||||
makeSink: () => DownloadSink<T>,
|
||||
): Promise<{ result: T; fileName: string }> {
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
|
||||
const attempt = async (headers: Record<string, string>): Promise<T> => {
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
|
||||
const sink = makeSink();
|
||||
try {
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const buf = new Uint8Array(await resp.arrayBuffer());
|
||||
if (buf.length > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${buf.length} > ${maxBytes}`);
|
||||
}
|
||||
await sink.write(buf);
|
||||
} else {
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw tooLarge(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
await sink.write(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
return await sink.done();
|
||||
} catch (e) {
|
||||
await sink.discard();
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
// First try with a browser UA only. On any non-size failure — a
|
||||
// network-level `fetch failed` (connection reset by an anti-bot front-end)
|
||||
// or a 403/4xx from anti-hotlink — retry once with a Referer pointing at the
|
||||
// resource itself, the common bypass for same-origin hotlink checks.
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'User-Agent': DOWNLOAD_USER_AGENT,
|
||||
Accept: '*/*',
|
||||
};
|
||||
try {
|
||||
return { result: await attempt(baseHeaders), fileName };
|
||||
} catch (err) {
|
||||
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
|
||||
try {
|
||||
return { result: await attempt({ ...baseHeaders, Referer: source }), fileName };
|
||||
} catch {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadBinarySource(
|
||||
source: string,
|
||||
resourceName: string,
|
||||
@@ -102,79 +196,25 @@ export async function loadBinarySource(
|
||||
}
|
||||
|
||||
if (/^https?:\/\//i.test(source)) {
|
||||
const fileName = guessFileNameFromUrl(source);
|
||||
|
||||
// A single fetch attempt with the given headers. Streams the body
|
||||
// incrementally so a server that omits or understates Content-Length
|
||||
// can't make us buffer a chunked response past maxBytes — `await
|
||||
// resp.arrayBuffer()` would happily allocate the entire payload before
|
||||
// we get a chance to length-check it. Size-limit rejections are tagged
|
||||
// `noRetry` so the outer retry doesn't re-download an oversized body.
|
||||
const attempt = async (headers: Record<string, string>): Promise<LoadedBinary> => {
|
||||
const resp = await fetch(source, {
|
||||
headers,
|
||||
redirect: 'follow',
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`);
|
||||
const declared = Number(resp.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declared) && declared > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`);
|
||||
}
|
||||
const reader = resp.body?.getReader();
|
||||
if (!reader) {
|
||||
const bytes = new Uint8Array(await resp.arrayBuffer());
|
||||
if (bytes.length > maxBytes) {
|
||||
throw tooLarge(`${resourceName} too large: ${bytes.length} > ${maxBytes}`);
|
||||
}
|
||||
return { bytes, fileName };
|
||||
}
|
||||
// Buffered sink: accumulate the streamed chunks and assemble them into one
|
||||
// contiguous buffer. The shared `downloadHttp` owns the transport, the
|
||||
// incremental length check, and the Referer retry.
|
||||
const memorySink = (): DownloadSink<Uint8Array> => {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (!value) continue;
|
||||
total += value.byteLength;
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => { /* ignore */ });
|
||||
throw tooLarge(`${resourceName} too large: > ${maxBytes}`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
bytes.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return { bytes, fileName };
|
||||
return {
|
||||
write(chunk) { chunks.push(chunk); total += chunk.byteLength; },
|
||||
done() {
|
||||
const bytes = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
||||
return bytes;
|
||||
},
|
||||
discard() { chunks.length = 0; },
|
||||
};
|
||||
};
|
||||
|
||||
// First try with a browser UA only. On any non-size failure — a
|
||||
// network-level `fetch failed` (connection reset by an anti-bot
|
||||
// front-end) or a 403/4xx from anti-hotlink — retry once with a
|
||||
// Referer pointing at the resource itself, the common bypass for
|
||||
// same-origin hotlink checks. Mirrors NapCat's with/without-Referer
|
||||
// strategy.
|
||||
const baseHeaders: Record<string, string> = {
|
||||
'User-Agent': DOWNLOAD_USER_AGENT,
|
||||
Accept: '*/*',
|
||||
};
|
||||
try {
|
||||
return await attempt(baseHeaders);
|
||||
} catch (err) {
|
||||
if ((err as { noRetry?: boolean } | null)?.noRetry) throw err;
|
||||
try {
|
||||
return await attempt({ ...baseHeaders, Referer: source });
|
||||
} catch {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
const { result, fileName } = await downloadHttp(source, resourceName, maxBytes, memorySink);
|
||||
return { bytes: result, fileName };
|
||||
}
|
||||
|
||||
const filePath = resolveLocalFilePath(source);
|
||||
|
||||
Reference in new issue
Block a user