import { requireLocalRecordingMetadata } from "./localRecordingMetadata"; import path from "node:path"; import { link, lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { coerceExternalMediaReference, EXTERNAL_MEDIA_FILENAME } from "./localMedia"; import { writeExternalMediaReference } from "./externalMedia-server"; import { extractVideoId } from "./videoId"; import { parseVtt } from "./vtt"; export type LocalMediaCommitResult = { status: "imported" | "occupied" | "failed"; incomplete?: boolean; reason?: string; stagingCleanupFailed?: boolean; }; // TRANSACTION PRIMITIVE, not the application importer. The future controller // must supply a guarded, corpus-owned real data directory and freshly read, // validated source bytes. This helper has no source-media path and cannot copy // or delete the MP4. It validates its immutable input again before any writes. // // WHY NOT rename(staging, destination): POSIX rename can replace an existing // empty directory. Instead, mkdir reserves the destination exclusively, then // link publishes each complete staged file WITHOUT replacing an existing name. // Metadata is linked LAST because the indexer's discovery requires it. Staging // is a sibling of data/, never inside the indexer's recording directory walk. // These hard links are between CORPUS files only, never to external media. // // Failure after reservation leaves a metadata-less partial record for explicit // review. Do not recursively roll it back: another producer might have written // there meanwhile. A retry returns occupied, never merges/overwrites. This is // fail-safe retry handling, not automatic recovery. The caller must surface it. // No portable multi-file transaction promises crash durability or protection // against an unrelated writer concurrently replacing ancestor directories. export async function commitLocalMediaRecord(options: { dataDirectory: string; directoryId: string; metadata: string; transcript: string; reference: unknown; signal?: AbortSignal; }, testHooks: { afterReserve?: () => Promise } = {}): Promise { const { directoryId, metadata, transcript, signal } = options; if (!path.isAbsolute(options.dataDirectory) || !/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(directoryId) || directoryId.endsWith(".") || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(directoryId)) { throw new Error("Invalid corpus directory or recording ID"); } const reference = coerceExternalMediaReference(options.reference); if (!reference) throw new Error("Invalid external media reference"); if (Buffer.byteLength(metadata) > 32 * 1024 * 1024 || Buffer.byteLength(transcript) > 32 * 1024 * 1024) { throw new Error("Import text exceeds 32 MiB"); } let meta; try { meta = JSON.parse(metadata.replace(/^\uFEFF/, "")); } catch { throw new Error("Invalid metadata JSON"); } if (meta && typeof meta === "object" && "local_recording" in meta) { const local = requireLocalRecordingMetadata(meta); if (local.id !== directoryId) throw new Error("Local metadata identity does not match the recording"); } else if (!meta || typeof meta !== "object" || Array.isArray(meta) || "entries" in meta || (meta._type !== undefined && meta._type !== "video") || meta.id !== directoryId || typeof meta.webpage_url !== "string" || !/^https?:\/\//i.test(meta.webpage_url) || extractVideoId(meta.webpage_url) !== directoryId || typeof meta.title !== "string" || !meta.title.trim() || typeof meta.duration !== "number" || !Number.isFinite(meta.duration) || meta.duration <= 0 || typeof meta.upload_date !== "string" || !/^\d{8}$/.test(meta.upload_date)) { throw new Error("Metadata identity or required fields do not match the recording"); } const text = transcript.replace(/^\uFEFF/, ""); const cues = parseVtt(text); if (!/^WEBVTT(?:[ \t].*)?(?:\r?\n|$)/.test(text) || !cues.some((cue) => cue.end > cue.start) || cues.some((cue) => !Number.isFinite(cue.start) || !Number.isFinite(cue.end) || cue.start < 0 || cue.end < cue.start)) { throw new Error("Transcript has no usable cues or has reversed intervals"); } signal?.throwIfAborted(); const rootInfo = await lstat(options.dataDirectory); if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink()) throw new Error("Corpus data directory must be a real directory"); const root = await realpath(options.dataDirectory); const target = path.join(root, directoryId); const stage = await mkdtemp(path.join(path.dirname(root), ".local-media-import-")); let reserved = false; let result: LocalMediaCommitResult = { status: "failed" }; try { // Stage only validated immutable text, without serializing the original // metadata/transcript again. Bytes supplied by the controller are retained. await writeFile(path.join(stage, "metadata.info.json"), metadata, { flag: "wx" }); await writeFile(path.join(stage, "transcript.en.vtt"), transcript, { flag: "wx" }); // The declared sidecar's writer (lib/externalMedia-server.ts), into the // private staging dir; the hard link below publishes it. await writeExternalMediaReference(stage, reference); signal?.throwIfAborted(); try { await mkdir(target); reserved = true; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; result = { status: "occupied" }; return result; } // Fault-injection seam for transaction boundary tests; production callers // do not supply hooks. It runs before any canonical file is published. await testHooks.afterReserve?.(); for (const name of ["transcript.en.vtt", EXTERNAL_MEDIA_FILENAME, "metadata.info.json"]) { signal?.throwIfAborted(); const current = await lstat(target); if (!current.isDirectory() || current.isSymbolicLink()) throw new Error("Destination changed"); await link(path.join(stage, name), path.join(target, name)); } result = { status: "imported" }; return result; } catch (error) { result = { status: "failed", incomplete: reserved, reason: signal?.aborted ? "cancelled" : (error as NodeJS.ErrnoException).code || "publication-failed" }; return result; } finally { // Only our unique staging directory is eligible for cleanup. A cleanup // failure must not turn a committed record into an apparent failed import. try { await rm(stage, { recursive: true, force: true }); } catch { result.stagingCleanupFailed = true; } } }