diff --git a/CHANGELOG.md b/CHANGELOG.md index 118329e..b4c9110 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [4.15.1] — 2026-10-20 — Media: a relay no longer dies when a player walks away + +### Fixed + +- **`@shade/media`: `FileMediaStore.body()` held a file handle for the whole + response.** It was closed only when the client read to the end or the runtime + called `cancel`. A player that seeks or closes mid-film often does neither, so + the handle was left to the garbage collector — which Bun 1.4 treats as fatal. + The Prism relay restarted five times in four hours this way. Each piece now + opens and closes the file itself; nothing is held between reads. Regression + test: `tests/fixtures/abandoned-body.ts`, run in its own process, checks that + no descriptor is open between reads (fails on 4.15.0 under any Bun). + ## [4.15.0] — 2026-10-18 — Media: films, video, images, audio and live streams, end to end New package **`@shade/media`** — see `docs/media.md`. diff --git a/packages/shade-media/package.json b/packages/shade-media/package.json index 2c9ddfa..887733d 100644 --- a/packages/shade-media/package.json +++ b/packages/shade-media/package.json @@ -1,6 +1,6 @@ { "name": "@shade/media", - "version": "4.15.0", + "version": "4.15.1", "description": "End-to-end encrypted media streaming for Shade — seekable sealed films, videos, images and audio, and live channels for logs, text and live video", "type": "module", "main": "src/index.ts", diff --git a/packages/shade-media/src/server/file-store.ts b/packages/shade-media/src/server/file-store.ts index 4f6cad0..8b4a587 100644 --- a/packages/shade-media/src/server/file-store.ts +++ b/packages/shade-media/src/server/file-store.ts @@ -15,7 +15,8 @@ * piece is sent again. All of it survives a restart. */ -import { mkdir, link, readdir, readFile, rename, rm, stat, unlink, writeFile, open } from 'node:fs/promises'; +import { access, mkdir, link, readdir, readFile, rename, rm, stat, unlink, writeFile, open } from 'node:fs/promises'; +import { constants } from 'node:fs'; import type { FileHandle } from 'node:fs/promises'; import { join } from 'node:path'; import { randomBytes, toHex } from '../bytes.js'; @@ -491,29 +492,37 @@ export class FileMediaStore implements MediaStore { // Read the range ourselves rather than handing `Bun.file().slice()` to a // Response: Bun's sendfile path ignored the slice for large files // (1.3.5) and sent the whole film to a Range request. - const fh = await open(this.objectPath(id), 'r'); + // + // Each piece opens and closes the file itself. A handle held for the + // stream's life is closed only if the client reads to the end or the + // runtime calls `cancel` — and a player that seeks or closes mid-film + // often gets neither. The handle is then closed by the garbage + // collector, which Bun 1.4 treats as fatal: the relay died that way. + const path = this.objectPath(id); + await access(path, constants.R_OK); let pos = start; const CHUNK = 1024 * 1024; return new ReadableStream({ async pull(controller) { if (pos >= end) { - await fh.close(); controller.close(); return; } const buf = new Uint8Array(Math.min(CHUNK, end - pos)); - const { bytesRead } = await fh.read(buf, 0, buf.length, pos); - if (bytesRead === 0) { + const fh = await open(path, 'r'); + let bytesRead: number; + try { + ({ bytesRead } = await fh.read(buf, 0, buf.length, pos)); + } finally { await fh.close(); + } + if (bytesRead === 0) { controller.error(new Error('media file shorter than its record')); return; } pos += bytesRead; controller.enqueue(buf.subarray(0, bytesRead)); }, - async cancel() { - await fh.close(); - }, }); } diff --git a/packages/shade-media/tests/file-store.test.ts b/packages/shade-media/tests/file-store.test.ts index 2e91852..cf72dfb 100644 --- a/packages/shade-media/tests/file-store.test.ts +++ b/packages/shade-media/tests/file-store.test.ts @@ -9,3 +9,13 @@ describe('FileMediaStore', () => { await expect(store.totalBytes()).rejects.toThrow(); }); }); + +describe('FileMediaStore bodies', () => { + test('a body nobody finishes reading holds no file for the garbage collector to close', async () => { + const proc = Bun.spawn(['bun', 'run', `${import.meta.dir}/fixtures/abandoned-body.ts`], { stdout: 'pipe', stderr: 'pipe' }); + const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + expect(err).not.toContain('closed during garbage collection'); + expect(out.trim()).toBe('survived'); + expect(code).toBe(0); + }, 30_000); +}); diff --git a/packages/shade-media/tests/fixtures/abandoned-body.ts b/packages/shade-media/tests/fixtures/abandoned-body.ts new file mode 100644 index 0000000..73a78a4 --- /dev/null +++ b/packages/shade-media/tests/fixtures/abandoned-body.ts @@ -0,0 +1,37 @@ +// Run as its own process by file-store.test.ts: a body a client walks away +// from must not leave anything for the garbage collector to close, because +// Bun treats a FileHandle closed by GC as fatal and the relay dies with it. +import { mkdirSync, mkdtempSync, readdirSync, readlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { FileMediaStore } from '../../src/server.js'; + +const dir = mkdtempSync(join(tmpdir(), 'shade-abandoned-')); +const id = 'ab'.repeat(16); +mkdirSync(join(dir, 'objects', 'ab'), { recursive: true }); +writeFileSync(join(dir, 'objects', 'ab', `${id}.smf`), new Uint8Array(3 * 1024 * 1024)); +const store = new FileMediaStore(dir); + +// Never read, read once and dropped: what a seek or a closed player leaves. +for (let i = 0; i < 20; i++) { + const body = await store.body(id, 0, 3 * 1024 * 1024); + if (i % 2 === 1) await body.getReader().read(); +} +// Between reads nothing may be open: a descriptor held here is one the +// garbage collector closes later, which Bun 1.4 turns into a crash. +const held = readdirSync('/proc/self/fd').filter((fd) => { + try { + return readlinkSync(`/proc/self/fd/${fd}`).endsWith(`${id}.smf`); + } catch { + return false; + } +}); +if (held.length > 0) { + console.log(`held ${held.length}`); + process.exit(1); +} +for (let i = 0; i < 5; i++) { + Bun.gc(true); + await new Promise((r) => setTimeout(r, 20)); +} +console.log('survived');