import { open, rename, mkdir, unlink } from 'node:fs/promises' import { readFileSync, unlinkSync } from 'node:fs' import { dirname } from 'node:path' // A checkpoint's contents never become partially visible; serialize writers too. export function checkpointWriter(path) { let queue=Promise.resolve() return value=>{ const text=JSON.stringify(value) queue=queue.then(async()=>{ await mkdir(dirname(path),{recursive:true,mode:0o700}) const file=await open(path+'.tmp','w',0o600) try{await file.writeFile(text);await file.sync()}finally{await file.close()} await rename(path+'.tmp',path) }) return queue } } // A crashed process can be resumed; a live peer cannot run the same job twice. export async function lockCheckpoint(path) { await mkdir(dirname(path),{recursive:true,mode:0o700}) const lock=path+'.lock' try { const f=await open(lock,'wx',0o600) try{await f.writeFile(String(process.pid));await f.sync()}finally{await f.close()} } catch(e) { if(e.code!=='EEXIST')throw e const pid=Number(readFileSync(lock,'utf8')) if(!Number.isSafeInteger(pid)||pid<=0)throw new Error('Checkpoint lock is incomplete; inspect it before retrying') try{process.kill(pid,0);throw new Error('This upload already has a running owner')}catch(error){if(error.code!=='ESRCH')throw error} throw new Error('Previous upload process stopped. Inspect the checkpoint, then remove only its .lock file before resuming; no upload was started') } let released=false const release=()=>{if(released)return;released=true;try{if(readFileSync(lock,'utf8')===String(process.pid))unlinkSync(lock)}catch{}} process.once('exit',release) return release }