import { isAbsolute, join, relative } from 'node:path'; import { type BlobWritten, getActiveBlobStore, readBlobRange, streamChunks, writeBlobStream } from './blob-store.ts'; import { readBranchMeta } from './log.ts'; import { worldPaths } from './storage.ts'; /** Read a resource payload at this branch, then its retained ancestors. */ export async function readResourceBlob(service: string, key: string, root?: string): Promise { assertResourceKey(key); for (const dir of resourceChain(service, root)) { const bytes = await getActiveBlobStore().get(resourceBlobFile(dir, key)); if (bytes !== null) return bytes; } return null; } /** Write a resource payload on this branch (a stored object's bytes), where a read finds it first. */ export async function writeResourceBlob(service: string, key: string, bytes: Uint8Array, root?: string): Promise { assertResourceKey(key); await getActiveBlobStore().put(resourceBlobFile(worldPaths(service, root).resources, key), bytes); } /** Write a resource payload on this branch from a body as it arrives (a model's weights, an upload's bytes), kept only * when `accept` holds for its size and SHA-256 (the blob seam's `writeBlobStream`). True when kept. */ export async function writeResourceBlobStream(service: string, key: string, body: ReadableStream | AsyncIterable, accept: (written: BlobWritten) => boolean, root?: string): Promise { assertResourceKey(key); const chunks = body instanceof ReadableStream ? streamChunks(body) : body; return writeBlobStream(resourceBlobFile(worldPaths(service, root).resources, key), chunks, accept); } /** Remove this branch's copy of a resource payload; an ancestor's stays its own (the row that named it is what a * deletion ends). */ export async function removeResourceBlob(service: string, key: string, root?: string): Promise { assertResourceKey(key); await getActiveBlobStore().remove(resourceBlobFile(worldPaths(service, root).resources, key)); } /** A service's resources dir at this branch, then at each retained ancestor's: where a read resolves a payload, and * what a listing that mints ids covers, so a branch serves bytes its parent received and never re-mints a parent's id. */ export function resourceChain(service: string, root?: string): string[] { const out: string[] = []; const seen = new Set(); let current = worldPaths(service, root).root; for (;;) { if (seen.has(current)) throw new Error('Cyclic resource blob ancestry'); seen.add(current); out.push(worldPaths(service, current).resources); const parent = readBranchMeta(service, current)?.parent; if (!parent) return out; current = parent.at; } } /** Where a resource blob's key is kept under a resources directory. A key is a relative path, its parts joined by '/'. * On Windows a part may hold a character no file name can: a ':' there names an NTFS stream of the file before it, so * `asset:` wrote into a stream of a file named `asset` and the store's rename failed (EINVAL). There each of * `<>:"|?*`, a control character and '%' itself is written as %XX, one name per key; elsewhere the key is the path. */ export function resourceBlobFile(dir: string, key: string): string { return join(dir, process.platform === 'win32' ? key.replace(/[%<>:"|?*\x00-\x1f]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`) : key); } /** The key a file under a resources directory holds: resourceBlobFile's inverse, its parts joined by '/'. */ export function resourceBlobKey(dir: string, path: string): string { const key = relative(dir, path).split('\\').join('/'); return process.platform === 'win32' ? key.replace(/%([0-9A-F]{2})/g, (_, hex: string) => String.fromCharCode(parseInt(hex, 16))) : key; } function assertResourceKey(key: string): void { if (isAbsolute(key) || key.includes('\0') || key.split(/[\\/]/).includes('..')) throw new Error('Invalid relative resource blob key'); } /** The key's full path at the first of this branch and its retained ancestors that holds it. */ async function resolveResourceBlob(service: string, key: string, root?: string): Promise { assertResourceKey(key); for (const dir of resourceChain(service, root)) { const path = resourceBlobFile(dir, key); if (await getActiveBlobStore().exists(path)) return path; } return null; } /** Size of a resource payload at this branch or its ancestors, or null. */ export async function resourceBlobSize(service: string, key: string, root?: string): Promise { const path = await resolveResourceBlob(service, key, root); return path === null ? null : getActiveBlobStore().size(path); } /** A byte range of a resource payload at this branch or its ancestors (a ranged read where the * store has one), or null when absent. */ export async function readResourceBlobRange(service: string, key: string, start: number, endInclusive: number, root?: string): Promise { const path = await resolveResourceBlob(service, key, root); return path === null ? null : readBlobRange(path, start, endInclusive); }