// A disposable lookup cache, not a byte store. Only owning World files retain payloads. import { createHash } from 'node:crypto'; import { closeSync, constants, fstatSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeFileSync, type Stats } from 'node:fs'; import { isAbsolute, join, resolve } from 'node:path'; const MAX_BUCKET_BYTES = 128 * 1024; const MAX_ENTRIES = 32; const MAX_PATHS = 4; type Index = Record; function privateFile(stat: Stats): boolean { return stat.isFile() && stat.nlink === 1 && (!process.getuid || stat.uid === process.getuid()) && (stat.mode & 0o077) === 0; } function privateDirectory(root: string): boolean { try { const stat = lstatSync(root); return stat.isDirectory() && (stat.mode & 0o077) === 0 && (!process.getuid || stat.uid === process.getuid()); } catch { return false; } } function readIndex(file: string): Index { let fd: number | undefined; try { fd = openSync(file, constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0)); const stat = fstatSync(fd); if (!privateFile(stat) || stat.size > MAX_BUCKET_BYTES) return {}; const parsed: unknown = JSON.parse(readFileSync(fd, 'utf8')); if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}; const index: Index = {}; for (const [key, paths] of Object.entries(parsed).slice(-MAX_ENTRIES)) { if (!/^\d+:[a-f0-9]{64}$/.test(key) || !Array.isArray(paths)) continue; index[key] = paths.filter((path): path is string => typeof path === 'string' && path.length <= 4096 && isAbsolute(path)).slice(0, MAX_PATHS); } return index; } catch { return {}; } finally { if (fd !== undefined) closeSync(fd); } } function digestFile(file: string, size: number): string | null { const fd = openSync(file, 'r'); try { const hash = createHash('sha256'); const buffer = Buffer.allocUnsafe(64 * 1024); let remaining = size; while (remaining > 0) { const length = readSync(fd, buffer, 0, Math.min(buffer.length, remaining), null); if (!length) return null; hash.update(buffer.subarray(0, length)); remaining -= length; } if (readSync(fd, buffer, 0, 1, null)) return null; return hash.digest('hex'); } finally { closeSync(fd); } } export function sharedBlobIndex(root: string, destinationDevice: number, digest: string): { reuse(temporary: string, size: number): boolean; record(key: string): void; } { // 256 buckets with bounded entries/bytes keep metadata bounded across roots and devices. const file = join(root, `${digest.slice(0, 2)}.json`); const entry = `${destinationDevice}:${digest}`; return { reuse(temporary, size) { if (!privateDirectory(root)) return false; for (const candidate of readIndex(file)[entry] ?? []) { try { const source = lstatSync(candidate); if (!source.isFile() || source.dev !== destinationDevice || source.size !== size || (process.getuid && source.uid !== process.getuid())) continue; linkSync(candidate, temporary); // Check the actual linked file, not a source path that could have been replaced. const linked = lstatSync(temporary); if (linked.isFile() && linked.dev === destinationDevice && linked.size === size && (!process.getuid || linked.uid === process.getuid()) && digestFile(temporary, size) === digest) return true; } catch { /* A cache miss, stale path, unsupported link, or corrupt candidate. */ } rmSync(temporary, { force: true }); } return false; }, record(key) { try { const path = resolve(key); if (path.length > 4096) return; const index = readIndex(file); const paths = [path, ...(index[entry] ?? []).filter((old) => old !== path)].slice(0, MAX_PATHS); delete index[entry]; index[entry] = paths; let text = JSON.stringify(index); while (Object.keys(index).length > MAX_ENTRIES || Buffer.byteLength(text) > MAX_BUCKET_BYTES) { delete index[Object.keys(index)[0]!]; text = JSON.stringify(index); } mkdirSync(root, { recursive: true, mode: 0o700 }); if (!privateDirectory(root)) return; // A torn/concurrent index update is just a cache miss. Writing the bounded // bucket directly avoids retaining metadata temp files after SIGKILL. const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0), 0o600); try { if (!privateFile(fstatSync(fd))) return; ftruncateSync(fd, 0); writeFileSync(fd, text); } finally { closeSync(fd); } } catch { /* Index storage is optional: the World already owns its complete bytes. */ } }, }; }