/** * `media put` across runs: a film sealed once is uploaded once. * * An upload already survives a dropped connection within one run (the * client retries, see `upload.ts`). This covers what a run cannot: Ctrl-C, a * laptop that sleeps, a relay that is gone for longer than the retries wait. * Each file being put has a job directory, keyed by the server, the file's * path, size and mtime and the options that change what is sealed: * * sealed.smf the sealed copy, kept until the relay has all of it * job.json what a rerun needs to send the same file again: the seal * result (with the file key — 0600, as the library), the read * token and the metadata (subtitle grants included) * lock the pid of the run working on it * * Run the same command again and it picks up where the upload stopped: the * same media id, so the relay already has most of it. Once the relay stored * the file, the sealed copy goes and the grant stays in `job.json`: putting * the same file again (the episodes of a season already up, when the * season's put is run again) gives the same link while the relay still has * it. A changed file is a different job. Jobs untouched for 30 days are * removed. */ import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { fromB64u, sha256, toB64u, toHex } from './bytes.js'; import { encodeGrant, parseGrant } from './grant.js'; import type { MediaGrant } from './grant.js'; import { READ_TOKEN_HEADER } from './owner.js'; import type { MediaMeta, SealResult } from './sealed.js'; const MAX_AGE_MS = 30 * 24 * 3600 * 1000; export interface PutJob { result: SealResult; /** Null for public ciphertext. */ readToken: Uint8Array | null; meta: MediaMeta; /** Set once the relay stored the file. */ grant?: MediaGrant; } interface JobFile { v: 1; file: string; result: { mediaId: string; mediaKey: string; rootDigest: string; plaintextSize: number; sealedSize: number; segmentSize: number; segmentCount: number }; readToken: string | null; meta: MediaMeta; grant?: string; } export class JobBusyError extends Error { override readonly name = 'JobBusyError'; } function alive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; } } export class PutJobs { constructor(private readonly dir: string) {} /** The job for putting `file` to `server` with options `variant` (anything that changes what is sealed). */ async key(server: string, file: string, variant: string): Promise { const s = await stat(file); const id = JSON.stringify([server.replace(/\/$/, ''), resolve(file), s.size, Math.floor(s.mtimeMs), variant]); return toHex((await sha256(new TextEncoder().encode(id))).subarray(0, 16)); } private path(key: string, name: string): string { return join(this.dir, key, name); } sealedPath(key: string): string { return this.path(key, 'sealed.smf'); } /** Take the job for this run, or throw `JobBusyError` if another live run has it. */ async claim(key: string): Promise<() => Promise> { await mkdir(join(this.dir, key), { recursive: true, mode: 0o700 }); const lock = this.path(key, 'lock'); for (let tries = 0; ; tries++) { try { const fh = await open(lock, 'wx', 0o600); await fh.write(String(process.pid)); await fh.close(); return () => rm(lock, { force: true }); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'EEXIST' || tries > 0) throw e; const pid = Number(await readFile(lock, 'utf8').catch(() => '')); if (Number.isInteger(pid) && pid > 0 && alive(pid)) { throw new JobBusyError(`another \`media put\` (pid ${pid}) is uploading this file`); } await rm(lock, { force: true }); // left by a run that died } } } /** The job, if an earlier run got as far as sealing — and its sealed copy is whole, unless it is done. */ async load(key: string): Promise { let j: JobFile; try { j = JSON.parse(await readFile(this.path(key, 'job.json'), 'utf8')) as JobFile; } catch { return null; } if (j.v !== 1) return null; const result: SealResult = { ...j.result, mediaId: fromB64u(j.result.mediaId), mediaKey: fromB64u(j.result.mediaKey), rootDigest: fromB64u(j.result.rootDigest), }; const job: PutJob = { result, readToken: j.readToken === null ? null : fromB64u(j.readToken), meta: j.meta }; if (j.grant !== undefined) { const g = parseGrant(j.grant); if (g.kind === 'shade.media-grant/v1') job.grant = g; return job; } const sealed = await stat(this.sealedPath(key)).catch(() => null); return sealed?.size === result.sealedSize ? job : null; } async save(key: string, file: string, job: PutJob): Promise { const r = job.result; const out: JobFile = { v: 1, file: resolve(file), result: { mediaId: toB64u(r.mediaId), mediaKey: toB64u(r.mediaKey), rootDigest: toB64u(r.rootDigest), plaintextSize: r.plaintextSize, sealedSize: r.sealedSize, segmentSize: r.segmentSize, segmentCount: r.segmentCount, }, readToken: job.readToken === null ? null : toB64u(job.readToken), meta: job.meta, ...(job.grant !== undefined ? { grant: encodeGrant(job.grant) } : {}), }; const tmp = this.path(key, 'job.json.tmp'); await writeFile(tmp, JSON.stringify(out), { mode: 0o600 }); await rename(tmp, this.path(key, 'job.json')); } /** The relay has it: keep the grant, drop the sealed copy. */ async done(key: string, file: string, job: PutJob, grant: MediaGrant): Promise { await this.save(key, file, { ...job, grant }); await rm(this.sealedPath(key), { force: true }); } async forget(key: string): Promise { await rm(join(this.dir, key), { recursive: true, force: true }); } /** Remove jobs nobody touched for 30 days, and half-sealed copies no job names. */ async prune(now = Date.now()): Promise { let n = 0; for (const key of await readdir(this.dir).catch(() => [] as string[])) { if (!/^[0-9a-f]{32}$/.test(key)) continue; const jobFile = await stat(this.path(key, 'job.json')).catch(() => null); const lock = await readFile(this.path(key, 'lock'), 'utf8').catch(() => null); if (lock !== null && alive(Number(lock))) continue; const touched = jobFile?.mtimeMs ?? (await stat(join(this.dir, key)).catch(() => null))?.mtimeMs ?? 0; if (now - touched > MAX_AGE_MS || (jobFile === null && now - touched > 3600_000)) { await this.forget(key); n++; } } return n; } } /** Whether the relay still serves the file a grant opens (not deleted since). */ export async function stillServed(grant: MediaGrant, fetchFn: typeof fetch = fetch): Promise { if (grant.url === undefined) return false; try { const res = await fetchFn(grant.url, { method: 'HEAD', headers: grant.readToken !== undefined ? { [READ_TOKEN_HEADER]: toB64u(grant.readToken) } : {}, }); return res.status === 200; } catch { return false; } }