import { type ChildProcess, spawn } from "node:child_process"; import { tmpdir } from "node:os"; export interface WindowsReadLock { bytesHash: string; head: Buffer; isHeld: () => boolean; release: () => Promise; } const LOCK_START_TIMEOUT_MS = 30_000; // Hashing a large clip on slow storage may take minutes; it fails only after this long with no progress line. export const HASH_STALL_TIMEOUT_MS = 30_000; const OPENED_LINE = /^OPENED\r?$/m; const LOCK_STOP_TIMEOUT_MS = 2_000; const LOCKED_LINE = /^LOCKED ([0-9a-f]{64}) ([A-Za-z0-9+/=]*)\r?\n/m; // Opens with FileShare.Read (deny write/delete/rename), refuses reparse points, and hashes/reads the locked handle. export const LOCK_SCRIPT = [ "$ErrorActionPreference='Stop'", "$p=$env:HF_LOCK_PATH", "$fs=[System.IO.File]::Open($p,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::Read)", "try{[Console]::Out.WriteLine('OPENED');[Console]::Out.Flush();if(([int][System.IO.File]::GetAttributes($p) -band [int][System.IO.FileAttributes]::ReparsePoint) -ne 0){throw 'reparse'};$h=New-Object byte[] 64;$n=0;while($n -lt 64){$r=$fs.Read($h,$n,64-$n);if($r -le 0){break};$n+=$r};$fs.Position=0;$sha=[System.Security.Cryptography.SHA256]::Create();try{$buf=New-Object byte[] 4194304;$done=0;$last=[DateTime]::UtcNow;while(($r=$fs.Read($buf,0,$buf.Length)) -gt 0){$null=$sha.TransformBlock($buf,0,$r,$null,0);$done+=$r;if(([DateTime]::UtcNow-$last).TotalMilliseconds -ge 1000){[Console]::Out.WriteLine('HASHED '+$done);[Console]::Out.Flush();$last=[DateTime]::UtcNow}};$null=$sha.TransformFinalBlock($buf,0,0);$hash=[BitConverter]::ToString($sha.Hash).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()};$b64=[Convert]::ToBase64String($h,0,$n);[Console]::Out.WriteLine('LOCKED '+$hash+' '+$b64);[Console]::Out.Flush();$null=[Console]::In.ReadLine()}finally{$fs.Dispose()}", ].join(";"); function closeChild(child: ChildProcess): Promise { if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(); return new Promise((resolve) => { const done = () => { clearTimeout(timer); resolve(); }; const timer = setTimeout(() => { try { child.kill(); } catch {} }, LOCK_STOP_TIMEOUT_MS); timer.unref(); child.once("close", done); try { child.stdin?.end(); } catch { try { child.kill(); } catch {} } }); } /** The helper never took the lock (PowerShell refused, crashed or never started); after `OPENED`, a failure is null. */ export const LOCK_UNAVAILABLE = "unavailable"; function waitForLockReady( child: ChildProcess, signal: AbortSignal | undefined, ): Promise<{ bytesHash: string; head: Buffer } | typeof LOCK_UNAVAILABLE | null> { return new Promise((resolve) => { let stdout = ""; let settled = false; let opened = false; let timer = setTimeout(() => onFail(), LOCK_START_TIMEOUT_MS); timer.unref(); const restartTimer = (ms: number) => { clearTimeout(timer); timer = setTimeout(() => finish(null), ms); timer.unref(); }; const finish = ( ready: { bytesHash: string; head: Buffer } | typeof LOCK_UNAVAILABLE | null, ) => { if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener("abort", onAbort); child.stdout?.off("data", onData); child.off("error", onFail); child.off("close", onFail); resolve(ready); }; const onFail = () => finish(opened ? null : LOCK_UNAVAILABLE); const onAbort = () => finish(null); const onData = (chunk: Buffer) => { stdout += chunk.toString("utf8"); const match = LOCKED_LINE.exec(stdout); if (match) return finish({ bytesHash: match[1]!, head: Buffer.from(match[2]!, "base64") }); // The start deadline covers taking the lock; once it is held, any output is hashing progress. opened ||= OPENED_LINE.test(stdout); if (opened) restartTimer(HASH_STALL_TIMEOUT_MS); }; signal?.addEventListener("abort", onAbort, { once: true }); child.stdout?.on("data", onData); child.once("error", onFail); child.once("close", onFail); }); } /** Holds an NTFS deny-write, deny-delete lock on `filePath` while allowing concurrent readers (ffmpeg/ffprobe). */ export async function acquireWindowsReadLock( filePath: string, signal?: AbortSignal, ): Promise { if (signal?.aborted) return null; let child: ChildProcess; try { child = spawn( "powershell.exe", [ "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", LOCK_SCRIPT, ], { cwd: tmpdir(), env: { ...process.env, HF_LOCK_PATH: filePath }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, }, ); } catch { return LOCK_UNAVAILABLE; } const locked = await waitForLockReady(child, signal); if (!locked || locked === LOCK_UNAVAILABLE) { await closeChild(child); return locked; } let held = true; child.once("close", () => { held = false; }); let releasing: Promise | null = null; return { bytesHash: locked.bytesHash, head: locked.head, isHeld: () => held && child.exitCode === null && child.signalCode === null, release: () => { held = false; return (releasing ??= closeChild(child)); }, }; }