diff --git a/CHANGELOG.md b/CHANGELOG.md index 83f815f..6851348 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,7 +73,10 @@ New package **`@shade/media`** — see `docs/media.md`. pieces in flight: the client asks how far the upload got and sends the rest. Uploads under way survive restarts (`uploads/` on disk, `shade_media_uploads` beside the S3 multipart upload), count against quota and are swept after - 24 h without a piece. `media put` shows progress. Above all, a relay's + 24 h without a piece. `media put` shows progress, and resumes across runs: + after Ctrl-C or a long outage the same command goes on with the same + media id (sealed copy and job under `$XDG_CONFIG_HOME/shade/media-pending/`), + and a file already up gives its link again instead of a second copy. Above all, a relay's memory no longer grows with the film (see Fixed). - **`shade live video --input`** a film, `/dev/video0` or `rtsp://…`: ffmpeg is run for you, H.264/AAC copied (a camera's own encoder) and anything else diff --git a/docs/media.md b/docs/media.md index 605a13d..e906842 100644 --- a/docs/media.md +++ b/docs/media.md @@ -125,6 +125,16 @@ in the bucket, so: - An upload counts against the owner's quota from its start. One with no new piece for 24 hours is dropped by the sweep. +**Across runs, too.** Ctrl-C, a laptop that sleeps, or a relay gone for longer than +the retries wait: run the same `shade media put` again and it goes on with the same +media id. Each file being put has a job under `$XDG_CONFIG_HOME/shade/media-pending/` +(keyed by server, path, size, mtime and options) holding the sealed copy and what a +rerun needs (`job.json`, 0600: it holds the file key, like the library). Once the +relay has the file, the copy is removed and the grant is kept: putting the same file +again gives the same link while the relay still serves it. So running a season's put +again after it stopped at episode 7 sends only episodes 7 to 10. Jobs untouched for +30 days are removed. + A file of at most one piece still goes up as one `PUT /v1/media/:id`. The full exchange is described in `packages/shade-media/src/upload.ts`. diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index 1988649..880f999 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -15,7 +15,7 @@ * `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure. */ -import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, watch, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, watch, writeFile } from 'node:fs/promises'; import { createWriteStream } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { basename, dirname, extname, join } from 'node:path'; @@ -35,6 +35,8 @@ import { IMAGE_MIME, ImageStreamSplitter } from './image-stream.js'; import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js'; import { liveEncodePlan, prepareForWeb, probeLive, webIssues } from './web-prep.js'; import { MediaLibrary } from './library.js'; +import { PutJobs, stillServed } from './put-jobs.js'; +import type { PutJob } from './put-jobs.js'; import type { SubtitleTrack } from './subtitles.js'; import type { LiveContainer } from './splitter.js'; @@ -187,7 +189,14 @@ async function mediaServe(flags: Flags, hooks: MediaCliHooks): Promise { async function mediaPut(pos: string[], flags: Flags): Promise { if (pos.length === 0) throw new UsageError('usage: shade media put … --server URL [--album T]'); const server = need(flags, 'server', 'SHADE_MEDIA_SERVER'); - const ctx: PutCtx = { client: new MediaClient(server, await loadOwnerKey()), server, library: await openLibrary() }; + const ctx: PutCtx = { + client: new MediaClient(server, await loadOwnerKey()), + server, + library: await openLibrary(), + jobs: new PutJobs(join(configDir(), 'media-pending')), + }; + const pruned = await ctx.jobs.prune(); + if (pruned > 0) err(`removed ${pruned} upload job(s) untouched for 30 days`); const started = Date.now(); const albumTitle = str(flags, 'album'); const oneDir = pos.length === 1 && (await stat(pos[0]!)).isDirectory(); @@ -215,6 +224,7 @@ interface PutCtx { client: MediaClient; server: string; library: MediaLibrary; + jobs: PutJobs; } async function putAlbum(ctx: PutCtx, title: string, items: Grant[], flags: Flags): Promise { @@ -283,8 +293,38 @@ function putOpts(flags: Flags): { readToken?: null } { return flags.public === true ? { readToken: null } : {}; } -/** `as` overrides name and type — only for the one file named on the command line. */ -async function putFile(ctx: PutCtx, file: string, flags: Flags, as: { name?: string; mime?: string } = {}): Promise { +/** + * `as` overrides name and type — only for the one file named on the command + * line. `ephemeral`: a file this run made (subtitles pulled out by `--web`), + * not worth resuming. + */ +type PutAs = { name?: string; mime?: string; ephemeral?: boolean }; + +/** Put one file, resuming an earlier run's upload of it (see `put-jobs.ts`). */ +async function putFile(ctx: PutCtx, file: string, flags: Flags, as: PutAs = {}): Promise { + if (as.ephemeral === true) return sealAndPut(ctx, file, flags, as, null); + const variant = JSON.stringify({ web: flags.web === true, public: flags.public === true, name: as.name, mime: as.mime }); + const key = await ctx.jobs.key(ctx.server, file, variant); + const release = await ctx.jobs.claim(key); + try { + const job = await ctx.jobs.load(key); + if (job?.grant !== undefined) { + if (await stillServed(job.grant)) { + err(`${job.meta.name ?? basename(file)}: already on the relay, same link`); + return job.grant; + } + // Deleted since (`media rm`), or a relay that lost it: put it again. + } else if (job !== null) { + err(`resuming ${job.meta.name ?? basename(file)}: sealed by an earlier run, sending what the relay does not have yet`); + return await upload(ctx, file, job, ctx.jobs.sealedPath(key), key); + } + return await sealAndPut(ctx, file, flags, as, key); + } finally { + await release(); + } +} + +async function sealAndPut(ctx: PutCtx, file: string, flags: Flags, as: PutAs, key: string | null): Promise { let meta: MediaMeta = { name: as.name ?? basename(file) }; const mime = as.mime ?? guessMime(file); if (mime !== undefined) meta.mime = mime; @@ -302,7 +342,7 @@ async function putFile(ctx: PutCtx, file: string, flags: Flags, as: { name?: str meta = { name: as.name ?? `${stem}.mp4`, mime: prep.mime }; for (const sub of prep.subtitles) { const name = `${stem}${sub.lang !== undefined ? `.${sub.lang}` : ''}.srt`; - const grant = await putFile(ctx, sub.path, flags, { name, mime: 'text/plain; charset=utf-8' }); + const grant = await putFile(ctx, sub.path, flags, { name, mime: 'text/plain; charset=utf-8', ephemeral: true }); tracks.push({ grant, ...(sub.lang !== undefined ? { lang: sub.lang } : {}), ...(sub.title !== undefined ? { label: sub.title } : {}) }); } } else { @@ -314,26 +354,46 @@ async function putFile(ctx: PutCtx, file: string, flags: Flags, as: { name?: str if (tracks.length > 0) meta = withSubtitles(meta, tracks); } const size = (await stat(source)).size; - const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`); + // A job's sealed copy is kept for the next run; anything else is temporary. + const sealed = key !== null ? ctx.jobs.sealedPath(key) : join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`); try { err(`sealing ${meta.name ?? basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`); - const result = await sealFile(source, tmp, { meta }); - const progress = uploadProgress(meta.name ?? basename(file), result.sealedSize); - const grant = await ctx.client.putSealed(result, Bun.file(tmp), { - meta, - ...putOpts(flags), - ...(progress !== undefined ? { onProgress: progress } : {}), - }); - await ctx.library.add(ctx.server, grant, result.sealedSize); - return grant; + // Under its final name only once whole: a run cut off mid-seal leaves nothing to resume. + const result = await sealFile(source, `${sealed}.part`, { meta }); + await rename(`${sealed}.part`, sealed); + const job: PutJob = { result, readToken: flags.public === true ? null : randomBytes(32), meta }; + if (key !== null) await ctx.jobs.save(key, file, job); + return await upload(ctx, file, job, sealed, key); } finally { - await rm(tmp, { force: true }); + await rm(`${sealed}.part`, { force: true }); + if (key === null) await rm(sealed, { force: true }); } } finally { if (work !== null) await rm(work, { recursive: true, force: true }); } } +async function upload(ctx: PutCtx, file: string, job: PutJob, sealed: string, key: string | null): Promise { + const name = job.meta.name ?? basename(file); + const progress = uploadProgress(name, job.result.sealedSize); + let grant: MediaGrant; + try { + grant = await ctx.client.putSealed(job.result, Bun.file(sealed), { + meta: job.meta, + readToken: job.readToken, + ...(progress !== undefined ? { onProgress: progress } : {}), + }); + } catch (e) { + if (key !== null) { + err(`! ${name}: upload stopped. Run the same command again to resume; the sealed copy waits in ${dirname(sealed)} (delete it to give up).`); + } + throw e; + } + await ctx.library.add(ctx.server, grant, job.result.sealedSize); + if (key !== null) await ctx.jobs.done(key, file, job, grant); + return grant; +} + /** * `media get [-o path|-]`: a file is written to `path` (default: its * own name); an album becomes a directory of its items, nested albums as @@ -796,6 +856,7 @@ export const MEDIA_HELP = ` --web: make films play in any browser first (ffmpeg): copy what browsers play, AC-3/DTS audio → AAC, HEVC → H.264, embedded text subtitles → subtitle tracks. + Stopped (Ctrl-C, no network)? Run it again: it resumes. media get [-o file|dir|-] Download and decrypt a sealed file (an album: a directory) media ls --server URL Your uploads on that server, named from this machine's library diff --git a/packages/shade-media/src/put-jobs.ts b/packages/shade-media/src/put-jobs.ts new file mode 100644 index 0000000..2a4b1db --- /dev/null +++ b/packages/shade-media/src/put-jobs.ts @@ -0,0 +1,193 @@ +/** + * `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; + } +} diff --git a/packages/shade-media/tests/put-jobs.test.ts b/packages/shade-media/tests/put-jobs.test.ts new file mode 100644 index 0000000..736a5fc --- /dev/null +++ b/packages/shade-media/tests/put-jobs.test.ts @@ -0,0 +1,98 @@ +import { describe, test, expect, afterAll } from 'bun:test'; +import { mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { JobBusyError, PutJobs } from '../src/put-jobs.js'; +import { mediaGrantFrom } from '../src/grant.js'; +import { randomBytes } from '../src/bytes.js'; + +const dirs: string[] = []; +async function tempDir(): Promise { + const d = await mkdtemp(join(tmpdir(), 'shade-jobs-')); + dirs.push(d); + return d; +} +afterAll(async () => { + for (const d of dirs) await rm(d, { recursive: true, force: true }); +}); + +const result = () => ({ + mediaId: randomBytes(16), + mediaKey: randomBytes(32), + rootDigest: randomBytes(32), + plaintextSize: 10, + sealedSize: 100, + segmentSize: 65536, + segmentCount: 1, +}); + +describe('PutJobs', () => { + test('a job is the server, the file as it is now, and the options; a changed file is another job', async () => { + const d = await tempDir(); + const jobs = new PutJobs(join(d, 'jobs')); + const film = join(d, 'film.mkv'); + await writeFile(film, 'one'); + const k = await jobs.key('http://relay/', film, 'web'); + expect(await jobs.key('http://relay', film, 'web')).toBe(k); + expect(await jobs.key('http://other', film, 'web')).not.toBe(k); + expect(await jobs.key('http://relay', film, 'plain')).not.toBe(k); + await writeFile(film, 'two!'); + expect(await jobs.key('http://relay', film, 'web')).not.toBe(k); + }); + + test('resumable only with a whole sealed copy; done keeps the grant and drops the copy; the key file is 0600', async () => { + const d = await tempDir(); + const jobs = new PutJobs(d); + const key = 'a'.repeat(32); + const release = await jobs.claim(key); + const job = { result: result(), readToken: randomBytes(32), meta: { name: 'Film.mkv' } }; + await jobs.save(key, '/films/Film.mkv', job); + expect(await jobs.load(key)).toBeNull(); // no sealed copy yet + await writeFile(jobs.sealedPath(key), new Uint8Array(99)); + expect(await jobs.load(key)).toBeNull(); // cut short + await writeFile(jobs.sealedPath(key), new Uint8Array(100)); + const back = (await jobs.load(key))!; + expect(back.result.mediaKey).toEqual(job.result.mediaKey); + expect(back.readToken).toEqual(job.readToken); + expect(((await stat(join(d, key, 'job.json'))).mode & 0o777).toString(8)).toBe('600'); + + const grant = mediaGrantFrom(job.result, { url: 'http://relay/v1/media/x', readToken: job.readToken, meta: job.meta }); + await jobs.done(key, '/films/Film.mkv', job, grant); + expect(await stat(jobs.sealedPath(key)).catch(() => null)).toBeNull(); + expect((await jobs.load(key))!.grant!.mediaKey).toEqual(job.result.mediaKey); + await release(); + }); + + test('one run per job; a lock left by a dead run is taken over', async () => { + const d = await tempDir(); + const jobs = new PutJobs(d); + const key = 'b'.repeat(32); + const release = await jobs.claim(key); + await expect(jobs.claim(key)).rejects.toBeInstanceOf(JobBusyError); + await release(); + await writeFile(join(d, key, 'lock'), '999999999'); // no such process + const again = await jobs.claim(key); + await again(); + }); + + test('prune: jobs untouched for 30 days, and half-sealed leftovers after an hour', async () => { + const d = await tempDir(); + const jobs = new PutJobs(d); + const old = 'c'.repeat(32); + const fresh = 'd'.repeat(32); + const half = 'e'.repeat(32); + for (const k of [old, fresh]) { + await (await jobs.claim(k))(); + await jobs.save(k, '/f', { result: result(), readToken: null, meta: {} }); + } + await (await jobs.claim(half))(); + const now = Date.now(); + const daysAgo = (n: number) => new Date(now - n * 86400_000); + await utimes(join(d, old, 'job.json'), daysAgo(31), daysAgo(31)); + await utimes(join(d, half), daysAgo(0.1), daysAgo(0.1)); + expect(await jobs.prune(now)).toBe(2); + expect(await stat(join(d, fresh)).catch(() => null)).not.toBeNull(); + expect(await stat(join(d, old)).catch(() => null)).toBeNull(); + expect(await stat(join(d, half)).catch(() => null)).toBeNull(); + }); +});