From 28cd019ed12e2f9e84d727ecf041109295154e28 Mon Sep 17 00:00:00 2001 From: "eyevinn-developer[bot]" <343978855+eyevinn-developer[bot]@users.noreply.github.com> Date: Mon, 19 Oct 2026 10:29:42 +0000 Subject: [PATCH 1/2] feat(recording): connection-only recording target, downloads and upload outcome Lets an instance that stores recordings only in a storage connection create a recording output, list and download its recordings, and see why an upload failed (issue #534): - POST /api/v1/outputs accepts a recording output when MINIO_* is configured or its connectionId names an existing connection with a default bucket; otherwise 400 naming both options. POST and PATCH reject an unknown connectionId with 400 "Storage connection not found". - The recordings routes return stored recordings without MINIO_* env; 503 is kept for a database failure only. - Activation snapshots the recording's upload target on the production (recording: { outputId, connectionId?, startedAt }); deactivate uploads to it instead of re-reading output assignments. - Deactivate stores lastRecordingUpload (uploaded count, failed files, the connection used, and a reason) on the production. - RecordingDoc.durationMs is read from the MP4 header at upload; startedAt falls back to the activation start. - Each recording gets a downloadUrl (presigned GET with a signed response-content-disposition: attachment) and, when it cannot be signed, playbackUnavailable with the reason. Co-Authored-By: Claude Opus 5.5 --- docs/repo-patterns.md | 14 + docs/specs/storage-connections.md | 4 + docs/specs/vod-recording-minio.md | 44 ++- src/__tests__/mp4-duration.test.ts | 75 ++++ .../outputs-recording-target.test.ts | 165 +++++++++ .../recording-leftover-sweep.test.ts | 26 ++ src/__tests__/recording-upload-target.test.ts | 322 ++++++++++++++++++ .../recordings-routes-connection-only.test.ts | 179 ++++++++++ src/__tests__/recordings-routes.test.ts | 27 +- .../storage-connections-routes.test.ts | 9 + src/db/types.ts | 64 ++++ src/lib/flow-generator.ts | 5 + src/lib/mp4-duration.ts | 101 ++++++ src/lib/recording-uploader.ts | 25 +- src/routes/outputs.ts | 51 ++- src/routes/productions.ts | 304 +++++++++++------ src/routes/recordings.ts | 119 ++++--- 17 files changed, 1371 insertions(+), 163 deletions(-) create mode 100644 src/__tests__/mp4-duration.test.ts create mode 100644 src/__tests__/outputs-recording-target.test.ts create mode 100644 src/__tests__/recording-upload-target.test.ts create mode 100644 src/__tests__/recordings-routes-connection-only.test.ts create mode 100644 src/lib/mp4-duration.ts diff --git a/docs/repo-patterns.md b/docs/repo-patterns.md index f5ae8257..227908ec 100644 --- a/docs/repo-patterns.md +++ b/docs/repo-patterns.md @@ -432,3 +432,17 @@ back-charged if accrual started at `activatedAt`. Every `computeHourBuckets` cal start. A new accrual path that skips `accrualStartMs()` reintroduces the back-charge. The floor is `null` (no clamp) only when the sweep never started, which is why unit tests that call the accrual functions directly see raw `activatedAt`. + +## The recording upload target is the activation snapshot, not the current assignments + +Deactivate uploads a recording to `ProductionDoc.recording` (`{ outputId, connectionId?, +startedAt }`), written at activation next to `recorderBlockId` (issue #534). Do not re-read +`outputAssignments` at deactivate to find the target: assignments can change on a live production +and only take effect at the next activation, so re-reading would send (or silently drop) the +running recording's upload somewhere else. `firstRecordingOutput()` is only the fallback for a +production activated before the snapshot existed. Every deactivate with a recorder writes +`lastRecordingUpload` through `writeDeactivatedDoc` (not a separate write before the upload: the +uploader's `isStillRecording` guard compares `_rev`, and an extra write would make it skip the +delete-after-upload pass). Extra signed S3 query params such as `response-content-disposition` +sort after the `X-Amz-*` ones (lowercase after uppercase), so `presignGetUrl` appends them last; +the result was checked against botocore's `S3SigV4QueryAuth`. diff --git a/docs/specs/storage-connections.md b/docs/specs/storage-connections.md index 13d9988e..ed3d3a68 100644 --- a/docs/specs/storage-connections.md +++ b/docs/specs/storage-connections.md @@ -273,6 +273,10 @@ today). **`recording` output** (`OutputDoc`): add optional `connectionId?: string` to the recording output's config. Absent = default connection (env) — exactly as today. +*Amended by #534:* the `connectionId` must exist (`400 "Storage connection not found"` on `POST` +and `PATCH`), and a recording output is accepted without `MINIO_*` env when it names a +connection — see `vod-recording-minio.md` §"Connection-only targets, downloads and upload +outcome". **`RecordingDoc`** (`src/db/types.ts:352-367`): add optional `connectionId?: string`, recording which connection wrote the asset. Written at upload time from the output's `connectionId` (absent diff --git a/docs/specs/vod-recording-minio.md b/docs/specs/vod-recording-minio.md index 9ec65c67..bbebcd2b 100644 --- a/docs/specs/vod-recording-minio.md +++ b/docs/specs/vod-recording-minio.md @@ -68,9 +68,9 @@ start/stop endpoints are strictly required for v1; segment rollover reuses the e ``` GET /api/v1/productions/:id/recordings - 200 → [ { id, productionId, key, sizeBytes, durationMs?, startedAt, endedAt?, playbackUrl } ] + 200 → [ { id, productionId, key, sizeBytes, durationMs?, startedAt, endedAt?, playbackUrl?, downloadUrl?, playbackUnavailable? } ] 404 → { error: 'Production not found' } - 503 → { error: 'Object storage unavailable' } + 503 → { error: 'Database unavailable' } (#534: no longer returned for missing MINIO_* env) GET /api/v1/recordings (optional: list across all productions) 200 → [ RecordingAsset, ... ] @@ -84,6 +84,44 @@ GET /api/v1/recordings/:id the bucket is public) — see Open Question 2. Field naming mirrors existing docs: `id`, `createdAt`/`updatedAt` ISO strings, camelCase. +### Connection-only targets, downloads and upload outcome (#534) + +Amendment for recording end to end from Studio (issue #534). All changes are additive. + +- **Creating a recording output** (`POST /api/v1/outputs`, `outputType: "recording"`) needs a + storage target: the `MINIO_*` env store (no `connectionId`, or `"default"`) or a storage + connection (`connectionId`, see `storage-connections.md`). With neither → + `400 "Recording needs object storage: set the MINIO_* environment variables or choose a storage connection (connectionId)"`. + An unknown `connectionId` on `POST` or `PATCH` → `400 "Storage connection not found"`; a + connection without a default bucket → `400 "Storage connection has no default bucket"`. + Nothing is written in either case. A recording output with no target at all (disk-only, PR + #404) stays refused. +- **Recordings routes** no longer return `503 "Object storage unavailable"` when the `MINIO_*` + env is incomplete: they return the stored `RecordingDoc`s (or `[]`). `503` is kept for a + database failure only (all three routes). +- **Each recording** carries, next to `playbackUrl`, a `downloadUrl`: the same presigned GET + (same TTL) with `response-content-disposition=attachment; filename=".mp4"` in the + signed query, so a browser saves the file under the object key's basename. When neither URL + can be signed, `playbackUnavailable` gives the reason instead: `connection-missing`, + `connection-no-bucket`, `storage-not-configured` (default-connection recording, no `MINIO_*`), + `bucket-mismatch` (default-connection recording in a bucket other than `MINIO_BUCKET`) or + `signing-failed`. +- **`durationMs`** is written on new recordings, read from the MP4 movie header (`moov/mvhd`, or + `mvex/mehd` for a fragmented file) at upload. `startedAt` comes from the segment's file name + (#407), falling back to the activation start. +- **Upload target snapshot.** At activation, next to `recorderBlockId`, the production stores + `recording: { outputId, connectionId?, startedAt }`. Deactivate uploads to that target rather + than re-reading the output assignments, so removing or re-pointing the recording output on a + live production cannot change or drop the running recording's upload. Cleared on deactivate. + A production activated before this field existed falls back to its current assignments. +- **Upload outcome.** Each deactivate that had a recorder stores + `lastRecordingUpload: { finishedAt, outputId?, connectionId?, bucket?, uploaded, failed: [{ file, error }], reason?, message? }` + on the production, returned by `GET /api/v1/productions/:id` and kept until the next such + deactivate. `reason` is one of `no-storage-target`, `connection-not-found`, + `connection-no-bucket`, `auth-error` (the store rejected the key; sweep aborted) or + `upload-error`. Files that failed stay on Strom for the next sweep. No secrets or presigned + URLs are stored. + ### Error codes | Code | Condition | @@ -92,7 +130,7 @@ the bucket is public) — see Open Question 2. Field naming mirrors existing doc | 401 | missing/invalid `API_KEY` bearer (when configured) | | 404 | production or recording not found | | 409 | recording output already assigned / active conflict | -| 503 | CouchDB or object storage unreachable | +| 503 | CouchDB unreachable (the recordings routes no longer 503 on a missing `MINIO_*` env, #534) | ## Data Model diff --git a/src/__tests__/mp4-duration.test.ts b/src/__tests__/mp4-duration.test.ts new file mode 100644 index 00000000..0de6d947 --- /dev/null +++ b/src/__tests__/mp4-duration.test.ts @@ -0,0 +1,75 @@ +/** + * mp4DurationMs — reads a recording's duration from its MP4 movie header + * (issue #534). Boxes are built by hand so no media fixture is needed. + */ +import { describe, it, expect } from 'vitest'; +import { mp4DurationMs } from '../lib/mp4-duration.js'; + +function box(type: string, ...payload: Buffer[]): Buffer { + const body = Buffer.concat(payload); + const header = Buffer.alloc(8); + header.writeUInt32BE(8 + body.length, 0); + header.write(type, 4, 'latin1'); + return Buffer.concat([header, body]); +} + +function mvhdV0(timescale: number, duration: number): Buffer { + const p = Buffer.alloc(100); + p.writeUInt32BE(0, 0); // version 0 + flags + p.writeUInt32BE(timescale, 12); + p.writeUInt32BE(duration, 16); + return box('mvhd', p); +} + +function mvhdV1(timescale: number, duration: bigint): Buffer { + const p = Buffer.alloc(112); + p.writeUInt8(1, 0); + p.writeUInt32BE(timescale, 20); + p.writeBigUInt64BE(duration, 24); + return box('mvhd', p); +} + +function mehdV0(duration: number): Buffer { + const p = Buffer.alloc(8); + p.writeUInt32BE(duration, 4); + return box('mehd', p); +} + +const ftyp = box('ftyp', Buffer.from('isom\0\0\0\0isomiso2avc1mp41', 'latin1')); + +describe('mp4DurationMs', () => { + it('reads a version-0 mvhd after a large mdat', () => { + const mdat = box('mdat', Buffer.alloc(4096)); + const file = Buffer.concat([ftyp, mdat, box('moov', mvhdV0(1000, 61_234), box('trak'))]); + expect(mp4DurationMs(file)).toBe(61_234); + }); + + it('reads a version-1 mvhd and converts from the timescale', () => { + const file = Buffer.concat([ftyp, box('moov', mvhdV1(90_000, 90_000n * 125n))]); + expect(mp4DurationMs(file)).toBe(125_000); + }); + + it('falls back to mvex/mehd for a fragmented file with a zero mvhd duration', () => { + const file = Buffer.concat([ftyp, box('moov', mvhdV0(600, 0), box('mvex', mehdV0(600 * 42)))]); + expect(mp4DurationMs(file)).toBe(42_000); + }); + + it('handles a 64-bit largesize box before moov', () => { + const payload = Buffer.alloc(32); + const header = Buffer.alloc(16); + header.writeUInt32BE(1, 0); + header.write('mdat', 4, 'latin1'); + header.writeBigUInt64BE(BigInt(16 + payload.length), 8); + const file = Buffer.concat([ftyp, header, payload, box('moov', mvhdV0(1000, 5_000))]); + expect(mp4DurationMs(file)).toBe(5_000); + }); + + it('returns undefined for no moov, a truncated file, a zero timescale or no duration', () => { + expect(mp4DurationMs(Buffer.concat([ftyp, box('mdat', Buffer.alloc(16))]))).toBeUndefined(); + expect(mp4DurationMs(Buffer.from('not an mp4 at all'))).toBeUndefined(); + expect(mp4DurationMs(Buffer.concat([ftyp, box('moov', mvhdV0(1000, 5_000))]).subarray(0, 60))).toBeUndefined(); + expect(mp4DurationMs(Buffer.concat([ftyp, box('moov', mvhdV0(0, 5_000))]))).toBeUndefined(); + expect(mp4DurationMs(Buffer.concat([ftyp, box('moov', mvhdV0(1000, 0))]))).toBeUndefined(); + expect(mp4DurationMs(Buffer.alloc(0))).toBeUndefined(); + }); +}); diff --git a/src/__tests__/outputs-recording-target.test.ts b/src/__tests__/outputs-recording-target.test.ts new file mode 100644 index 00000000..026e97e6 --- /dev/null +++ b/src/__tests__/outputs-recording-target.test.ts @@ -0,0 +1,165 @@ +/** + * A `recording` output needs a storage target (issue #534): the MINIO_* env + * store, or a storage connection that exists. No `MINIO_*` env is set here, so + * only a storage connection makes a recording output valid. CouchDB is mocked. + */ +import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'; +import type { FastifyInstance } from 'fastify'; +import type { OutputDoc, StorageConnectionDoc } from '../db/types.js'; + +const TEST_API_KEY = 'test-secret-key'; +process.env['API_KEY'] = TEST_API_KEY; +delete process.env['MINIO_ENDPOINT']; +delete process.env['MINIO_ACCESS_KEY']; +delete process.env['MINIO_SECRET_KEY']; +delete process.env['MINIO_BUCKET']; + +const outputs = new Map(); +const connections = new Map(); + +const outputsDb = { + get: vi.fn(async (id: string) => { + const doc = outputs.get(id); + if (!doc) throw Object.assign(new Error('not_found'), { statusCode: 404 }); + return doc; + }), + insert: vi.fn(async (doc: OutputDoc) => { + outputs.set(doc._id, doc); + return { ok: true, id: doc._id, rev: '1-x' }; + }), + find: vi.fn(async () => ({ docs: Array.from(outputs.values()) })), + destroy: vi.fn(), +}; + +vi.mock('../db/index.js', () => ({ + getOutputsDb: () => outputsDb, + getStorageConnectionsDb: () => ({ + get: vi.fn(async (id: string) => { + const doc = connections.get(id); + if (!doc) throw Object.assign(new Error('not_found'), { statusCode: 404 }); + return doc; + }), + }), + getDb: () => ({ get: vi.fn(), find: vi.fn(async () => ({ docs: [] })), findTrusted: vi.fn(async () => ({ docs: [] })) }), + getSourcesDb: () => ({ get: vi.fn(), insert: vi.fn(), find: vi.fn(async () => ({ docs: [] })), findTrusted: vi.fn(async () => ({ docs: [] })), destroy: vi.fn() }), + getGatewaysDb: () => ({ get: vi.fn(), insert: vi.fn(), find: vi.fn(), destroy: vi.fn() }), + connectDb: vi.fn().mockResolvedValue(undefined), + isDbReady: vi.fn().mockResolvedValue(true), + isDbConnected: vi.fn().mockReturnValue(true), +})); + +vi.mock('../ws/controller.js', () => ({ + default: async () => {}, clearAudioState: vi.fn(), clearPipState: vi.fn(), clearFxState: vi.fn(), +})); + +const AUTH = { authorization: `Bearer ${TEST_API_KEY}` }; +let app: FastifyInstance; + +function connection(id: string, over: Partial = {}): StorageConnectionDoc { + return { + _id: id, type: 'storage-connection', name: id, endpoint: 's3.example.com', useSsl: true, + region: 'eu-west-1', accessKey: 'AK', secretKeyEnc: 'encv1:zzz', defaultBucket: 'vod', + role: 'recording', createdAt: 'x', updatedAt: 'x', ...over, + }; +} + +beforeAll(async () => { + const { buildServer } = await import('../server.js'); + app = await buildServer(); +}); + +beforeEach(() => { + outputs.clear(); + connections.clear(); + outputsDb.insert.mockClear(); +}); + +describe('POST /api/v1/outputs (recording)', () => { + it('creates a recording output on a storage connection when MINIO_* is not set', async () => { + connections.set('stconn-C', connection('stconn-C')); + const res = await app.inject({ + method: 'POST', url: '/api/v1/outputs', headers: AUTH, + payload: { name: 'VOD', outputType: 'recording', connectionId: 'stconn-C' }, + }); + expect(res.statusCode).toBe(201); + expect(res.json().connectionId).toBe('stconn-C'); + expect(res.json().outputType).toBe('recording'); + }); + + it('400s without a connectionId, naming both MINIO_* and storage connections', async () => { + const res = await app.inject({ + method: 'POST', url: '/api/v1/outputs', headers: AUTH, + payload: { name: 'VOD', outputType: 'recording' }, + }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toContain('MINIO_*'); + expect(res.json().error).toContain('storage connection'); + expect(outputsDb.insert).not.toHaveBeenCalled(); + }); + + it('400s with the reserved "default" connection when MINIO_* is not set', async () => { + const res = await app.inject({ + method: 'POST', url: '/api/v1/outputs', headers: AUTH, + payload: { name: 'VOD', outputType: 'recording', connectionId: 'default' }, + }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toContain('MINIO_*'); + }); + + it('400s "Storage connection not found" for an unknown connectionId and writes nothing', async () => { + const res = await app.inject({ + method: 'POST', url: '/api/v1/outputs', headers: AUTH, + payload: { name: 'VOD', outputType: 'recording', connectionId: 'stconn-nope' }, + }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toBe('Storage connection not found'); + expect(outputsDb.insert).not.toHaveBeenCalled(); + }); + + it('400s for a connection with no default bucket', async () => { + connections.set('stconn-nobucket', connection('stconn-nobucket', { defaultBucket: undefined })); + const res = await app.inject({ + method: 'POST', url: '/api/v1/outputs', headers: AUTH, + payload: { name: 'VOD', outputType: 'recording', connectionId: 'stconn-nobucket' }, + }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toBe('Storage connection has no default bucket'); + }); +}); + +describe('PATCH /api/v1/outputs/:id (recording connectionId)', () => { + beforeEach(() => { + outputs.set('output-rec', { + _id: 'output-rec', type: 'output', name: 'VOD', outputType: 'recording', + connectionId: 'stconn-C', createdAt: 'x', updatedAt: 'x', + }); + connections.set('stconn-C', connection('stconn-C')); + connections.set('stconn-D', connection('stconn-D')); + }); + + it('re-points the output at another existing connection', async () => { + const res = await app.inject({ + method: 'PATCH', url: '/api/v1/outputs/output-rec', headers: AUTH, payload: { connectionId: 'stconn-D' }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().connectionId).toBe('stconn-D'); + }); + + it('400s "Storage connection not found" for an unknown connectionId and writes nothing', async () => { + const res = await app.inject({ + method: 'PATCH', url: '/api/v1/outputs/output-rec', headers: AUTH, payload: { connectionId: 'stconn-nope' }, + }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toBe('Storage connection not found'); + expect(outputsDb.insert).not.toHaveBeenCalled(); + expect(outputs.get('output-rec')!.connectionId).toBe('stconn-C'); + }); + + it('still allows a rename without touching the connection', async () => { + const res = await app.inject({ + method: 'PATCH', url: '/api/v1/outputs/output-rec', headers: AUTH, payload: { name: 'Renamed' }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().name).toBe('Renamed'); + }); +}); diff --git a/src/__tests__/recording-leftover-sweep.test.ts b/src/__tests__/recording-leftover-sweep.test.ts index 89cd6bdf..d83d4ad1 100644 --- a/src/__tests__/recording-leftover-sweep.test.ts +++ b/src/__tests__/recording-leftover-sweep.test.ts @@ -135,3 +135,29 @@ describe('deactivate — RecordingDoc.startedAt for segments left by earlier ses }); }); }); + +describe('deactivate — RecordingDoc.durationMs (issue #534)', () => { + it('stamps durationMs read from each MP4 header; omits it when the header is unreadable', async () => { + // ftyp + moov/mvhd (version 0, timescale 1000, duration 61 234). + const mvhd = Buffer.alloc(108); + mvhd.writeUInt32BE(108, 0); + mvhd.write('mvhd', 4, 'latin1'); + mvhd.writeUInt32BE(1000, 20); + mvhd.writeUInt32BE(61_234, 24); + const moov = Buffer.concat([Buffer.from([0, 0, 0, 116]), Buffer.from('moov', 'latin1'), mvhd]); + const ftyp = Buffer.concat([Buffer.from([0, 0, 0, 16]), Buffer.from('ftypisom\0\0\0\0', 'latin1')]); + const mp4 = Buffer.concat([ftyp, moov]); + vi.stubGlobal('fetch', vi.fn(async (url: string, init?: { method?: string }) => { + if (init?.method === 'PUT') return new Response('', { status: 200 }); + return new Response(new Uint8Array(String(url).includes('legacy') ? [1, 2, 3] : mp4), { status: 200 }); + })); + mockGet.mockResolvedValue(prod()); + const app = await buildServer(); + await app.inject({ method: 'POST', url: '/api/v1/productions/prod-rec-1/deactivate' }); + + const docs = mockRecordingInsert.mock.calls.map((c) => c[0] as { key: string; durationMs?: number }); + const byKey = Object.fromEntries(docs.map((d) => [d.key, d.durationMs])); + expect(byKey['prod-rec-1/recording_20260301_100002_00000.mp4']).toBe(61_234); + expect(byKey['prod-rec-1/legacy_00000.mp4']).toBeUndefined(); + }); +}); diff --git a/src/__tests__/recording-upload-target.test.ts b/src/__tests__/recording-upload-target.test.ts new file mode 100644 index 00000000..c7906448 --- /dev/null +++ b/src/__tests__/recording-upload-target.test.ts @@ -0,0 +1,322 @@ +/** + * Recording upload target and outcome (issue #534). + * + * - Activation snapshots the recording output's storage connection on the + * production (`recording`), and deactivate uploads to that snapshot even when + * the output was removed from the production while it was live. + * - Deactivate stores `lastRecordingUpload` (uploaded count, failed files, the + * connection used, and a reason when nothing or not everything was uploaded). + * + * No `MINIO_*` env is set: the instance stores recordings only in a storage + * connection. CouchDB, Strom, the flow generator and the uploader are mocked. + */ +import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest'; +import type { OutputDoc, ProductionDoc, RecordingDoc, StorageConnectionDoc } from '../db/types.js'; + +delete process.env['MINIO_ENDPOINT']; +delete process.env['MINIO_ACCESS_KEY']; +delete process.env['MINIO_SECRET_KEY']; +delete process.env['MINIO_BUCKET']; +process.env['STORAGE_CONNECTION_KEY'] = Buffer.alloc(32, 7).toString('base64'); + +const productions = new Map(); +const outputs = new Map(); +const connections = new Map(); +const recordingInserts: RecordingDoc[] = []; +const productionInserts: ProductionDoc[] = []; +let rev = 1; + +function notFound(): Error { + return Object.assign(new Error('not_found'), { statusCode: 404 }); +} + +vi.mock('../db/index.js', () => ({ + getDb: () => ({ + get: vi.fn(async (id: string) => { + const doc = productions.get(id); + if (!doc) throw notFound(); + return structuredClone(doc); + }), + insert: vi.fn(async (doc: ProductionDoc) => { + const stored = JSON.parse(JSON.stringify({ ...doc, _rev: `${++rev}-x` })) as ProductionDoc; + productions.set(doc._id, stored); + productionInserts.push(stored); + return { ok: true, id: doc._id, rev: stored._rev }; + }), + find: vi.fn(async () => ({ docs: [] })), + findTrusted: vi.fn(async () => ({ docs: [] })), + }), + getOutputsDb: () => ({ + get: vi.fn(async (id: string) => { + const doc = outputs.get(id); + if (!doc) throw notFound(); + return doc; + }), + find: vi.fn(), insert: vi.fn(), destroy: vi.fn(), + }), + getRecordingsDb: () => ({ + get: vi.fn(), find: vi.fn(), + insert: vi.fn(async (doc: RecordingDoc) => { + recordingInserts.push(doc); + return { ok: true, id: doc._id, rev: '1-x' }; + }), + }), + getStorageConnectionsDb: () => ({ + get: vi.fn(async (id: string) => { + const doc = connections.get(id); + if (!doc) throw notFound(); + return doc; + }), + }), + getSourcesDb: () => ({ get: vi.fn(async () => { throw notFound(); }) }), + getGuestInvitesDb: () => ({ find: vi.fn(async () => ({ docs: [] })), destroy: vi.fn() }), + getGuestSessionsDb: () => ({ find: vi.fn(async () => ({ docs: [] })), insert: vi.fn() }), + connectDb: vi.fn().mockResolvedValue(undefined), + isDbReady: vi.fn().mockResolvedValue(true), + isDbConnected: vi.fn().mockReturnValue(true), +})); + +vi.mock('../ws/controller.js', () => ({ + default: async () => {}, + clearAudioState: vi.fn(), + clearPipState: vi.fn(), + clearFxState: vi.fn(), + clearClipStateForProduction: vi.fn(), + reinitConnectedControllers: vi.fn().mockResolvedValue(undefined), +})); + +const mockActivateStromFlow = vi.fn(); +const mockDeactivateStromFlow = vi.fn().mockResolvedValue(undefined); +vi.mock('../lib/flow-generator.js', () => ({ + activateStromFlow: (...args: unknown[]) => mockActivateStromFlow(...args), + deactivateStromFlow: (...args: unknown[]) => mockDeactivateStromFlow(...args), +})); + +vi.mock('../lib/strom-token.js', () => ({ getStromToken: vi.fn().mockResolvedValue('test-token') })); + +vi.mock('../lib/strom.js', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + StromClient: class { + flows = { get: vi.fn().mockResolvedValue({ flow: { id: 'flow-1', running: true, blocks: [] } }) }; + mixer = { multiviewEndpoint: vi.fn().mockResolvedValue(null) }; + recorder = { splitNow: vi.fn().mockResolvedValue(undefined) }; + }, + }; +}); + +vi.mock('../services/guest-sweep.js', () => ({ sweepGuestsOnProductionEnd: vi.fn().mockResolvedValue(undefined) })); + +const mockUploadRecordings = vi.fn(); +vi.mock('../lib/recording-uploader.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, uploadRecordings: (...args: unknown[]) => mockUploadRecordings(...args) }; +}); + +const { buildServer } = await import('../server.js'); +const { encryptStorageSecret } = await import('../lib/storage-connection-crypto.js'); + +const NOW = '2026-10-19T10:00:00.000Z'; + +function production(over: Partial = {}): ProductionDoc { + return { + _id: 'prod-1', + _rev: '1-x', + type: 'production', + name: 'Show', + status: 'inactive', + sources: [], + outputAssignments: [{ outputId: 'output-rec' }], + tally: { pgm: null, pvw: null }, + createdAt: NOW, + updatedAt: NOW, + ...over, + } as ProductionDoc; +} + +function activationResult() { + return { + flowId: 'flow-1', + mixerBlockId: null, + audioMixerBlockId: null, + loudnessMainBlockId: null, + recorderBlockId: 'b-out-rec', + recorderOutputId: 'output-rec', + whepOutputEntries: undefined, + pgmWhepEndpointId: undefined, + warnings: [], + sourceOffsetBlockIds: {}, + sourceAudioOffsetBlockIds: {}, + clipPlayerBlockIds: {}, + returnBuses: [], + returnWhepEntries: [], + mixerInputMap: {}, + }; +} + +beforeEach(() => { + productions.clear(); + outputs.clear(); + connections.clear(); + recordingInserts.length = 0; + productionInserts.length = 0; + mockUploadRecordings.mockReset(); + mockActivateStromFlow.mockReset(); + outputs.set('output-rec', { + _id: 'output-rec', type: 'output', name: 'VOD', outputType: 'recording', + connectionId: 'stconn-C', createdAt: NOW, updatedAt: NOW, + }); + connections.set('stconn-C', { + _id: 'stconn-C', type: 'storage-connection', name: 'Tenant S3', endpoint: 's3.tenant.example.com', + useSsl: true, region: 'eu-west-1', accessKey: 'AKTENANT', secretKeyEnc: encryptStorageSecret('tenant-secret'), + defaultBucket: 'tenant-vod', role: 'recording', createdAt: NOW, updatedAt: NOW, + }); +}); + +afterAll(() => { + delete process.env['STORAGE_CONNECTION_KEY']; +}); + +describe('recording upload target snapshot (issue #534)', () => { + it('uploads to the activation-time connection after the output is removed from the live production', async () => { + productions.set('prod-1', production()); + mockActivateStromFlow.mockResolvedValue(activationResult()); + mockUploadRecordings.mockResolvedValue({ + uploaded: [{ + key: 'prod-1/prod-1_20261019_100000_00000.mp4', + sizeBytes: 2048, + stromPath: 'recordings/prod-1/prod-1_20261019_100000_00000.mp4', + startedAt: '2026-10-19T10:00:00.000Z', + durationMs: 61_000, + }], + failed: [], + }); + + const app = await buildServer(); + await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/activate' }); + await vi.waitFor(() => expect(productions.get('prod-1')?.status).toBe('active')); + + const live = productions.get('prod-1')!; + expect(live.recording).toMatchObject({ outputId: 'output-rec', connectionId: 'stconn-C' }); + expect(Date.parse(live.recording!.startedAt)).not.toBeNaN(); + + // The operator removes the recording output while the production is live. + productions.set('prod-1', { ...live, outputAssignments: [] }); + + const res = await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(res.statusCode).toBe(200); + + expect(mockUploadRecordings).toHaveBeenCalledTimes(1); + const args = mockUploadRecordings.mock.calls[0]![0] as { target: { bucket: string; endpoint: string; accessKey: string } }; + expect(args.target).toMatchObject({ bucket: 'tenant-vod', endpoint: 's3.tenant.example.com', accessKey: 'AKTENANT' }); + + expect(recordingInserts).toHaveLength(1); + expect(recordingInserts[0]).toMatchObject({ + productionId: 'prod-1', + outputId: 'output-rec', + connectionId: 'stconn-C', + bucket: 'tenant-vod', + durationMs: 61_000, + startedAt: '2026-10-19T10:00:00.000Z', + }); + + const stopped = productions.get('prod-1')!; + expect(stopped.recording).toBeUndefined(); + expect(stopped.lastRecordingUpload).toMatchObject({ + outputId: 'output-rec', + connectionId: 'stconn-C', + bucket: 'tenant-vod', + uploaded: 1, + failed: [], + }); + expect(stopped.lastRecordingUpload!.reason).toBeUndefined(); + + // Returned by GET /api/v1/productions/:id, with no secrets in it. + const got = await app.inject({ method: 'GET', url: '/api/v1/productions/prod-1' }); + expect(got.json().lastRecordingUpload.uploaded).toBe(1); + expect(JSON.stringify(got.json().lastRecordingUpload)).not.toContain('tenant-secret'); + await app.close(); + }); + + it('falls back to the recording session start from the activation when the file name carries none', async () => { + productions.set('prod-1', production({ + status: 'active', stromFlowId: 'flow-1', recorderBlockId: 'b-out-rec', + recording: { outputId: 'output-rec', connectionId: 'stconn-C', startedAt: '2026-10-19T09:59:58.000Z' }, + })); + mockUploadRecordings.mockResolvedValue({ + uploaded: [{ key: 'prod-1/seg.mp4', sizeBytes: 1, stromPath: 'recordings/prod-1/seg.mp4' }], + failed: [], + }); + const app = await buildServer(); + await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(recordingInserts[0]!.startedAt).toBe('2026-10-19T09:59:58.000Z'); + expect(recordingInserts[0]!.durationMs).toBeUndefined(); + await app.close(); + }); + + it('records an auth-error reason and the failed file when the store rejects the key', async () => { + productions.set('prod-1', production({ + status: 'active', stromFlowId: 'flow-1', recorderBlockId: 'b-out-rec', + recording: { outputId: 'output-rec', connectionId: 'stconn-C', startedAt: NOW }, + })); + const file = 'recordings/prod-1/prod-1_20261019_100000_00000.mp4'; + mockUploadRecordings.mockResolvedValue({ + uploaded: [], + failed: [{ file, error: 'S3 PutObject failed: 403 AccessDenied' }], + abortedOnAuthError: { file, code: 'AccessDenied' }, + }); + + const app = await buildServer(); + const res = await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(res.statusCode).toBe(200); + expect(mockDeactivateStromFlow).toHaveBeenCalled(); + expect(recordingInserts).toHaveLength(0); + + const summary = productions.get('prod-1')!.lastRecordingUpload!; + expect(summary.uploaded).toBe(0); + expect(summary.failed).toEqual([{ file, error: expect.stringContaining('AccessDenied') }]); + expect(summary.reason).toBe('auth-error'); + expect(summary.message).toContain('AccessDenied'); + expect(summary.connectionId).toBe('stconn-C'); + await app.close(); + }); + + it('records connection-not-found and uploads nothing when the snapshot connection is gone', async () => { + connections.clear(); + productions.set('prod-1', production({ + status: 'active', stromFlowId: 'flow-1', recorderBlockId: 'b-out-rec', + recording: { outputId: 'output-rec', connectionId: 'stconn-C', startedAt: NOW }, + })); + const app = await buildServer(); + await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(mockUploadRecordings).not.toHaveBeenCalled(); + expect(productions.get('prod-1')!.lastRecordingUpload).toMatchObject({ + uploaded: 0, failed: [], reason: 'connection-not-found', + }); + await app.close(); + }); + + it('records no-storage-target when the output has no connection and MINIO_* is not configured', async () => { + productions.set('prod-1', production({ + status: 'active', stromFlowId: 'flow-1', recorderBlockId: 'b-out-rec', + recording: { outputId: 'output-rec', startedAt: NOW }, + })); + const app = await buildServer(); + await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(mockUploadRecordings).not.toHaveBeenCalled(); + const summary = productions.get('prod-1')!.lastRecordingUpload!; + expect(summary.reason).toBe('no-storage-target'); + expect(summary.message).toContain('MINIO_*'); + await app.close(); + }); + + it('keeps the previous summary when a deactivate has no recording', async () => { + const previous = { finishedAt: NOW, uploaded: 2, failed: [] }; + productions.set('prod-1', production({ status: 'active', stromFlowId: 'flow-1', lastRecordingUpload: previous })); + const app = await buildServer(); + await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(productions.get('prod-1')!.lastRecordingUpload).toEqual(previous); + await app.close(); + }); +}); diff --git a/src/__tests__/recordings-routes-connection-only.test.ts b/src/__tests__/recordings-routes-connection-only.test.ts new file mode 100644 index 00000000..8776ccff --- /dev/null +++ b/src/__tests__/recordings-routes-connection-only.test.ts @@ -0,0 +1,179 @@ +/** + * Recordings routes on an instance with no `MINIO_*` env (issue #534): the + * stored recordings are listed (not 503), a recording on a storage connection + * gets `playbackUrl` + `downloadUrl`, and an unsignable one says why with + * `playbackUnavailable`. A database failure still returns 503. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; +import type { FastifyInstance } from 'fastify'; +import type { RecordingDoc, StorageConnectionDoc } from '../db/types.js'; + +const TEST_API_KEY = 'test-secret-key'; +process.env['API_KEY'] = TEST_API_KEY; +delete process.env['MINIO_ENDPOINT']; +delete process.env['MINIO_ACCESS_KEY']; +delete process.env['MINIO_SECRET_KEY']; +delete process.env['MINIO_BUCKET']; +process.env['STORAGE_CONNECTION_KEY'] = Buffer.alloc(32, 9).toString('base64'); + +const recordings = new Map(); +const connections = new Map(); +let dbDown = false; + +function notFound(): Error { + return Object.assign(new Error('not_found'), { statusCode: 404 }); +} + +vi.mock('../db/index.js', () => ({ + getDb: () => ({ + get: vi.fn(async (id: string) => { + if (id !== 'prod-1') throw notFound(); + return { _id: 'prod-1' }; + }), + insert: vi.fn(), find: vi.fn(), findTrusted: vi.fn(), + }), + getRecordingsDb: () => ({ + get: vi.fn(async (id: string) => { + if (dbDown) throw Object.assign(new Error('ECONNREFUSED'), { code: 'ECONNREFUSED' }); + const doc = recordings.get(id); + if (!doc) throw notFound(); + return doc; + }), + find: vi.fn(async (query: { selector: { productionId?: string } }) => { + if (dbDown) throw new Error('ECONNREFUSED'); + const all = Array.from(recordings.values()); + const pid = query.selector.productionId; + return { docs: pid ? all.filter((r) => r.productionId === pid) : all }; + }), + insert: vi.fn(), + }), + getStorageConnectionsDb: () => ({ + get: vi.fn(async (id: string) => { + const doc = connections.get(id); + if (!doc) throw notFound(); + return doc; + }), + }), + getSourcesDb: () => ({ get: vi.fn(), insert: vi.fn(), find: vi.fn(), destroy: vi.fn() }), + getOutputsDb: () => ({ get: vi.fn(), insert: vi.fn(), find: vi.fn(), destroy: vi.fn() }), + getGatewaysDb: () => ({ get: vi.fn(), insert: vi.fn(), find: vi.fn(), destroy: vi.fn() }), + connectDb: vi.fn().mockResolvedValue(undefined), + isDbReady: vi.fn().mockResolvedValue(true), + isDbConnected: vi.fn().mockReturnValue(true), +})); + +vi.mock('../ws/controller.js', () => ({ + default: async () => {}, clearAudioState: vi.fn(), clearPipState: vi.fn(), clearFxState: vi.fn(), +})); + +const AUTH = { authorization: `Bearer ${TEST_API_KEY}` }; +let app: FastifyInstance; + +function recording(over: Partial = {}): RecordingDoc { + const now = '2026-10-19T10:00:00.000Z'; + return { + _id: `recording-${Math.random().toString(16).slice(2)}`, + type: 'recording', + productionId: 'prod-1', + connectionId: 'stconn-C', + bucket: 'tenant-vod', + key: 'prod-1/prod-1_20261019_100000_00000.mp4', + sizeBytes: 1234, + durationMs: 61000, + startedAt: now, + endedAt: now, + createdAt: now, + updatedAt: now, + ...over, + }; +} + +beforeAll(async () => { + const { buildServer } = await import('../server.js'); + const { encryptStorageSecret } = await import('../lib/storage-connection-crypto.js'); + connections.set('stconn-C', { + _id: 'stconn-C', type: 'storage-connection', name: 'Tenant', endpoint: 's3.tenant.example.com', + useSsl: true, region: 'eu-west-1', accessKey: 'AKTENANT', secretKeyEnc: encryptStorageSecret('tenant-secret'), + defaultBucket: 'tenant-vod', role: 'recording', createdAt: 'x', updatedAt: 'x', + }); + app = await buildServer(); +}); + +beforeEach(() => { + recordings.clear(); + dbDown = false; +}); + +afterAll(() => { + delete process.env['STORAGE_CONNECTION_KEY']; +}); + +describe('recordings routes without MINIO_* (connection-only instance)', () => { + it('GET /api/v1/recordings returns [] (not 503) when there are none', async () => { + const res = await app.inject({ method: 'GET', url: '/api/v1/recordings', headers: AUTH }); + expect(res.statusCode).toBe(200); + expect(res.json()).toEqual([]); + }); + + it('lists a connection recording with playbackUrl and downloadUrl', async () => { + const rec = recording(); + recordings.set(rec._id, rec); + const res = await app.inject({ method: 'GET', url: '/api/v1/productions/prod-1/recordings', headers: AUTH }); + expect(res.statusCode).toBe(200); + const [item] = res.json(); + expect(item.durationMs).toBe(61000); + expect(item.playbackUrl).toContain('https://s3.tenant.example.com/tenant-vod/prod-1/prod-1_20261019_100000_00000.mp4?'); + expect(item.playbackUrl).not.toContain('response-content-disposition'); + expect(item.downloadUrl).toContain('/tenant-vod/prod-1/prod-1_20261019_100000_00000.mp4?'); + expect(item.downloadUrl).toContain( + 'response-content-disposition=attachment%3B%20filename%3D%22prod-1_20261019_100000_00000.mp4%22', + ); + expect(item.downloadUrl).toContain('X-Amz-Expires=3600'); + expect(item.downloadUrl).toContain('X-Amz-Signature='); + expect(item.playbackUnavailable).toBeUndefined(); + expect(JSON.stringify(item)).not.toContain('tenant-secret'); + }); + + it('GET /api/v1/recordings/:id works and says connection-missing when the connection is gone', async () => { + const rec = recording({ connectionId: 'stconn-deleted' }); + recordings.set(rec._id, rec); + const res = await app.inject({ method: 'GET', url: `/api/v1/recordings/${rec._id}`, headers: AUTH }); + expect(res.statusCode).toBe(200); + expect(res.json().playbackUrl).toBeUndefined(); + expect(res.json().downloadUrl).toBeUndefined(); + expect(res.json().playbackUnavailable).toBe('connection-missing'); + }); + + it('says storage-not-configured for a default-connection recording', async () => { + const rec = recording({ connectionId: undefined, bucket: 'openlive-vod' }); + recordings.set(rec._id, rec); + const res = await app.inject({ method: 'GET', url: '/api/v1/recordings', headers: AUTH }); + expect(res.statusCode).toBe(200); + expect(res.json()[0].playbackUnavailable).toBe('storage-not-configured'); + }); + + it('returns 503 on a database failure', async () => { + dbDown = true; + const list = await app.inject({ method: 'GET', url: '/api/v1/recordings', headers: AUTH }); + expect(list.statusCode).toBe(503); + const perProd = await app.inject({ method: 'GET', url: '/api/v1/productions/prod-1/recordings', headers: AUTH }); + expect(perProd.statusCode).toBe(503); + const one = await app.inject({ method: 'GET', url: '/api/v1/recordings/recording-x', headers: AUTH }); + expect(one.statusCode).toBe(503); + }); + + it('returns 404 for a missing recording', async () => { + const res = await app.inject({ method: 'GET', url: '/api/v1/recordings/recording-missing', headers: AUTH }); + expect(res.statusCode).toBe(404); + }); +}); + +describe('downloadFileName', () => { + it('uses the key basename, keeps .mp4, and strips header-unsafe characters', async () => { + const { downloadFileName } = await import('../routes/recordings.js'); + expect(downloadFileName('vod/prod-1/prod-1_20261019_100000_00000.mp4')).toBe('prod-1_20261019_100000_00000.mp4'); + expect(downloadFileName('a/b"c;d.mp4')).toBe('b_c_d.mp4'); + expect(downloadFileName('a/segment.mkv')).toBe('segment.mp4'); + expect(downloadFileName('a/noext')).toBe('noext.mp4'); + }); +}); diff --git a/src/__tests__/recordings-routes.test.ts b/src/__tests__/recordings-routes.test.ts index fde20798..31d3b0a3 100644 --- a/src/__tests__/recordings-routes.test.ts +++ b/src/__tests__/recordings-routes.test.ts @@ -6,7 +6,9 @@ * attaches a presigned playbackUrl, and 404s for an unknown production. * - GET /api/v1/recordings — lists across all productions. * - GET /api/v1/recordings/:id — fetch one; 404 when missing. - * - 503 when object storage is not configured. + * - downloadUrl (attachment disposition) next to playbackUrl, and the + * bucket-mismatch playbackUnavailable reason (issue #534). The no-env case + * lives in recordings-routes-connection-only.test.ts. * * CouchDB is mocked and the MinIO SigV4 presigner runs for real (no bucket * needed — presignGetUrl is pure crypto), so playbackUrl is asserted structurally. @@ -158,6 +160,29 @@ describe('GET /api/v1/recordings', () => { }); }); +describe('downloadUrl and playbackUnavailable (issue #534)', () => { + it('adds a downloadUrl that saves the object under its basename', async () => { + const rec = makeRecording(); + recordingsStore.set(rec._id, rec); + const res = await app.inject({ method: 'GET', url: `/api/v1/recordings/${rec._id}`, headers: AUTH }); + const body = res.json(); + expect(body.downloadUrl).toContain('/openlive-vod/prod-1/segment_00001.mp4?'); + expect(body.downloadUrl).toContain('response-content-disposition=attachment%3B%20filename%3D%22segment_00001.mp4%22'); + expect(body.downloadUrl).not.toBe(body.playbackUrl); + expect(body.playbackUnavailable).toBeUndefined(); + }); + + it('says bucket-mismatch for a default recording in a bucket other than MINIO_BUCKET', async () => { + const rec = makeRecording({ bucket: 'old-bucket' }); + recordingsStore.set(rec._id, rec); + const res = await app.inject({ method: 'GET', url: `/api/v1/recordings/${rec._id}`, headers: AUTH }); + expect(res.statusCode).toBe(200); + expect(res.json().playbackUrl).toBeUndefined(); + expect(res.json().downloadUrl).toBeUndefined(); + expect(res.json().playbackUnavailable).toBe('bucket-mismatch'); + }); +}); + describe('GET /api/v1/recordings/:id', () => { it('fetches a single recording with a playbackUrl', async () => { const rec = makeRecording(); diff --git a/src/__tests__/storage-connections-routes.test.ts b/src/__tests__/storage-connections-routes.test.ts index 7eaf8558..f4bfef87 100644 --- a/src/__tests__/storage-connections-routes.test.ts +++ b/src/__tests__/storage-connections-routes.test.ts @@ -193,6 +193,15 @@ describe('DELETE /api/v1/storage-connections/:id (referential integrity)', () => expect(store.has(id)).toBe(true); }); + it('409s when referenced by a recording output (regression, issue #534)', async () => { + const id = seed(); + outputsDocs.push({ _id: 'output-rec', outputType: 'recording', connectionId: id }); + const res = await app.inject({ method: 'DELETE', url: `/api/v1/storage-connections/${id}`, headers: AUTH }); + expect(res.statusCode).toBe(409); + expect(res.json().references.outputs).toBe(1); + expect(store.has(id)).toBe(true); + }); + it('409s when referenced by an s3 clip source (connectionId inside the address JSON)', async () => { const id = seed(); sourcesDocs.push({ address: JSON.stringify({ type: 's3', bucket: 'b', key: 'k', connectionId: id }) }); diff --git a/src/db/types.ts b/src/db/types.ts index 66ebe956..045fa26f 100644 --- a/src/db/types.ts +++ b/src/db/types.ts @@ -380,6 +380,7 @@ export interface RecordingDoc { bucket: string; key: string; // object key, e.g. "/.mp4" sizeBytes?: number; + /** Media duration read from the MP4 movie header at upload (issue #534); absent when unreadable. */ durationMs?: number; startedAt: string; // ISO 8601 — when the recording session began, from the segment's file name endedAt?: string; // ISO 8601 — when the segment was finalized/uploaded @@ -387,6 +388,54 @@ export interface RecordingDoc { updatedAt: string; } +/** + * The recording output a production's recorder block was wired for, captured + * at activation (issue #534). + */ +export interface ActiveRecording { + /** The `recording` OutputDoc wired into the recorder block. */ + outputId: string; + /** That output's storage connection at activation; absent = the default (env) connection. */ + connectionId?: string; + /** ISO 8601 — when the activation that built the recorder block started. */ + startedAt: string; +} + +/** + * Why a deactivate's recording upload uploaded nothing or stopped early (issue #534): + * - `no-storage-target`: no connection on the output and the `MINIO_*` env is incomplete; + * - `connection-not-found`: the output's storage connection no longer exists; + * - `connection-no-bucket`: the connection has no default bucket to write to; + * - `auth-error`: the store rejected the credentials or permission (sweep aborted); + * - `upload-error`: listing the recordings on Strom or the upload pass itself failed. + */ +export type RecordingUploadReason = + | 'no-storage-target' + | 'connection-not-found' + | 'connection-no-bucket' + | 'auth-error' + | 'upload-error'; + +/** Summary of a deactivate's recording upload, stored on the production (issue #534). */ +export interface RecordingUploadSummary { + /** ISO 8601 — when the upload step finished. */ + finishedAt: string; + /** The recording output the upload was for, when known. */ + outputId?: string; + /** Storage connection used; absent = the default (env) connection. */ + connectionId?: string; + /** Bucket written to, when a target was resolved. */ + bucket?: string; + /** Number of files uploaded (and listed as recordings). */ + uploaded: number; + /** Files that failed to upload; they stay on Strom for the next sweep. */ + failed: Array<{ file: string; error: string }>; + /** Set when nothing was attempted or the sweep stopped early. */ + reason?: RecordingUploadReason; + /** Human-readable explanation accompanying `reason`. */ + message?: string; +} + // --------------- Guest calling types (issue #299, epic #208) --------------- /** @@ -758,6 +807,21 @@ export interface ProductionDoc { stromFlowId?: string; /** ID of the builtin.recorder block — set on activate when a 'recording' output is assigned, cleared on deactivate */ recorderBlockId?: string; + /** + * Upload target of the running recording, snapshotted at activation next to + * {@link recorderBlockId} (issue #534). Deactivate uploads to this target + * instead of re-reading the production's current output assignments, so + * removing or re-pointing the recording output on a live production cannot + * change where the running recording goes or drop its upload. Cleared on + * deactivate. + */ + recording?: ActiveRecording; + /** + * Outcome of the most recent deactivate that had a recording to upload (issue + * #534). Kept until the next such deactivate replaces it. Never holds secrets + * or presigned URLs. + */ + lastRecordingUpload?: RecordingUploadSummary; /** WHEP multiview endpoint URL — set when flow reaches 'playing' state, cleared on deactivate */ whepEndpoint?: string; /** WHEP PGM output endpoint URL — set when flow reaches 'playing' state, cleared on deactivate */ diff --git a/src/lib/flow-generator.ts b/src/lib/flow-generator.ts index 98fa2ad0..9298d1aa 100644 --- a/src/lib/flow-generator.ts +++ b/src/lib/flow-generator.ts @@ -36,6 +36,8 @@ export interface ActivationResult { * open-live uploads them to MinIO after deactivate (see recording-uploader.ts). */ recorderBlockId?: string; + /** ID of the 'recording' OutputDoc the recorder block was built for (issue #534). */ + recorderOutputId?: string; /** * Relative media directory the recorder writes into (output_dir property). Used * post-deactivate to locate the recorded segments via Strom's media API. @@ -1039,6 +1041,7 @@ export async function activateStromFlow( // Inject output blocks for each assigned OutputDoc const whepOutputEntries: Array<{ outputId: string; endpointId: string }> = []; let recorderBlockId: string | undefined; + let recorderOutputId: string | undefined; let recorderOutputDir: string | undefined; const warnings: ActivationWarning[] = []; let outputBlockIndex = 0; @@ -1094,6 +1097,7 @@ export async function activateStromFlow( flow.links.push({ from: `${audioEncId}:encoded_out`, to: `${blockId}:audio_in_0` }); } recorderBlockId = blockId; + recorderOutputId = outputDoc._id; recorderOutputDir = outputDir; outputBlockIndex++; } else if (outputDoc.outputType === 'whep') { @@ -1315,6 +1319,7 @@ export async function activateStromFlow( whepOutputEntries: whepOutputEntries.length > 0 ? whepOutputEntries : undefined, pgmWhepEndpointId, recorderBlockId, + recorderOutputId, recorderOutputDir, warnings, sourceOffsetBlockIds, diff --git a/src/lib/mp4-duration.ts b/src/lib/mp4-duration.ts new file mode 100644 index 00000000..fff3996d --- /dev/null +++ b/src/lib/mp4-duration.ts @@ -0,0 +1,101 @@ +/** + * Reads a recording's duration from its MP4 header (issue #534), so the + * recordings list can show `durationMs` without probing the object later. + * + * Walks the ISO BMFF box tree of an in-memory file (the uploader already holds + * each segment as a Buffer) to `moov/mvhd` and returns `duration / timescale` + * in milliseconds. A fragmented MP4 whose `mvhd` duration is 0 falls back to + * `moov/mvex/mehd`'s fragment duration. Returns undefined for anything it + * cannot read (no `moov`, truncated box, zero timescale) — the caller then + * simply omits `durationMs`. + */ + +interface Box { + type: string; + /** Offset of the box payload (after the size/type header). */ + start: number; + /** Offset one past the end of the box. */ + end: number; +} + +/** Iterates the boxes in `buf[from, to)`; stops at the first malformed one. */ +function* boxes(buf: Buffer, from: number, to: number): Generator { + let pos = from; + while (pos + 8 <= to) { + let size = buf.readUInt32BE(pos); + const type = buf.toString('latin1', pos + 4, pos + 8); + let header = 8; + if (size === 1) { + if (pos + 16 > to) return; + const large = buf.readBigUInt64BE(pos + 8); + if (large > BigInt(Number.MAX_SAFE_INTEGER)) return; + size = Number(large); + header = 16; + } else if (size === 0) { + size = to - pos; // box extends to the end of its container + } + if (size < header || pos + size > to) return; + yield { type, start: pos + header, end: pos + size }; + pos += size; + } +} + +function child(buf: Buffer, parent: { start: number; end: number }, type: string): Box | undefined { + for (const box of boxes(buf, parent.start, parent.end)) { + if (box.type === type) return box; + } + return undefined; +} + +/** Reads `(timescale, duration)` from an `mvhd` payload. */ +function readMvhd(buf: Buffer, box: Box): { timescale: number; duration: number } | undefined { + const version = buf.readUInt8(box.start); + if (version === 1) { + // version/flags(4) creation(8) modification(8) timescale(4) duration(8) + if (box.start + 32 > box.end) return undefined; + return { + timescale: buf.readUInt32BE(box.start + 20), + duration: Number(buf.readBigUInt64BE(box.start + 24)), + }; + } + // version/flags(4) creation(4) modification(4) timescale(4) duration(4) + if (box.start + 20 > box.end) return undefined; + return { + timescale: buf.readUInt32BE(box.start + 12), + duration: buf.readUInt32BE(box.start + 16), + }; +} + +/** Reads the fragment duration from an `mehd` payload. */ +function readMehd(buf: Buffer, box: Box): number | undefined { + const version = buf.readUInt8(box.start); + if (version === 1) { + if (box.start + 12 > box.end) return undefined; + return Number(buf.readBigUInt64BE(box.start + 4)); + } + if (box.start + 8 > box.end) return undefined; + return buf.readUInt32BE(box.start + 4); +} + +/** Duration of an MP4 file in milliseconds, or undefined when it cannot be read. */ +export function mp4DurationMs(buf: Buffer): number | undefined { + try { + const moov = child(buf, { start: 0, end: buf.length }, 'moov'); + if (!moov) return undefined; + const mvhdBox = child(buf, moov, 'mvhd'); + if (!mvhdBox || mvhdBox.end - mvhdBox.start < 1) return undefined; + const mvhd = readMvhd(buf, mvhdBox); + if (!mvhd || mvhd.timescale === 0) return undefined; + let duration = mvhd.duration; + // 0 (or all-ones "unknown") in a fragmented file: use the movie-extends header. + if (duration === 0 || duration === 0xffffffff) { + const mvex = child(buf, moov, 'mvex'); + const mehdBox = mvex ? child(buf, mvex, 'mehd') : undefined; + duration = mehdBox ? readMehd(buf, mehdBox) ?? 0 : 0; + } + if (!duration || !Number.isFinite(duration)) return undefined; + return Math.round((duration * 1000) / mvhd.timescale); + } catch { + return undefined; + } +} diff --git a/src/lib/recording-uploader.ts b/src/lib/recording-uploader.ts index 44e8e371..17d5d542 100644 --- a/src/lib/recording-uploader.ts +++ b/src/lib/recording-uploader.ts @@ -33,6 +33,7 @@ import { createHash, createHmac } from 'crypto'; import { config } from '../config.js'; import type { StromClient } from './strom.js'; +import { mp4DurationMs } from './mp4-duration.js'; export interface MinioTarget { endpoint: string; // host[:port], no scheme @@ -59,6 +60,11 @@ export interface UploadedSegment { * carries none. */ startedAt?: string; + /** + * Media duration in milliseconds, read from the MP4 movie header (issue + * #534). Undefined for a non-MP4 file or a header that cannot be read. + */ + durationMs?: number; } export interface UploadResult { @@ -177,6 +183,14 @@ function sha256Hex(data: Buffer | string): string { return createHash('sha256').update(data).digest('hex'); } +/** RFC 3986 percent-encoding, as required for SigV4 canonical query values. */ +function rfc3986(value: string): string { + return encodeURIComponent(value).replace( + /[!'()*]/g, + (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase(), + ); +} + /** Encodes an object key path segment-by-segment for use in an S3 URI. */ function encodeKey(key: string): string { return key @@ -277,6 +291,7 @@ export function presignGetUrl( key: string, expiresInSeconds: number, now: Date = new Date(), + opts: { contentDisposition?: string } = {}, ): string { const scheme = target.useSsl ? 'https' : 'http'; const host = target.endpoint; @@ -294,7 +309,13 @@ export function presignGetUrl( `&X-Amz-Credential=${encodeURIComponent(`${target.accessKey}/${credentialScope}`)}` + `&X-Amz-Date=${amzDate}` + `&X-Amz-Expires=${expiresInSeconds}` + - `&X-Amz-SignedHeaders=${signedHeaders}`; + `&X-Amz-SignedHeaders=${signedHeaders}` + + // S3 response-header override, signed like every other query param. It + // sorts after the X-Amz-* params (lowercase after uppercase in byte order), + // so appending keeps the canonical query sorted (issue #534). + (opts.contentDisposition !== undefined + ? `&response-content-disposition=${rfc3986(opts.contentDisposition)}` + : ''); const canonicalRequest = [ 'GET', @@ -431,11 +452,13 @@ export async function uploadRecordings(args: UploadRecordingsArgs): Promise { }); } +/** + * Why a `recording` output with this `connectionId` has nowhere to upload to, + * or null when it does (issue #534). A real connection must exist and name a + * bucket; no connection (or the reserved `"default"`) needs the MINIO_* env. + */ +async function recordingTargetError(connectionId: string | undefined): Promise { + if (!connectionId || connectionId === DEFAULT_CONNECTION_ID) { + return isRecordingEnabled() + ? null + : 'Recording needs object storage: set the MINIO_* environment variables or choose a storage connection (connectionId)'; + } + let conn: StorageConnectionDoc; + try { + conn = await getStorageConnectionsDb().get(connectionId); + } catch (err) { + // 404, or an id that names a document of another type (the type guard). + const notFound = (err as { statusCode?: number } | null)?.statusCode === 404 + || (err instanceof Error && err.message.startsWith('Document type mismatch')); + if (notFound) return 'Storage connection not found'; + throw err; + } + // Recordings upload into the connection's default bucket (resolveStorageTarget). + return conn.defaultBucket ? null : 'Storage connection has no default bucket'; +} + // RTMP destination fields on create/patch. `streamKey` is write-only (accepted // here, never returned); `ingestUrl` is only honoured for the 'custom' platform // — named presets resolve their ingest URL server-side from the static table. @@ -92,8 +118,8 @@ const OutputInput = z.object({ url: z.string().optional(), rtmp: RtmpInput.optional(), // Optional storage connection for a `recording` output (issue #520). Absent = - // the default (env) connection, exactly as today. A connectionId that no - // longer resolves surfaces at upload time, where a bad bucket does today. + // the default (env) connection, exactly as today. Must exist (checked in the + // handler, issue #534) so a bad id is a 400 here, not a silent upload failure. connectionId: z.string().min(1).max(128).optional(), }).superRefine((data, ctx) => { const isRtmp = data.outputType === 'rtmp'; @@ -211,12 +237,13 @@ const outputsRoutes: FastifyPluginAsync = async (fastify) => { fastify.post('/api/v1/outputs', async (req, reply) => { const body = OutputInput.parse(req.body); - // A 'recording' output only makes sense when MinIO/S3 is configured — Strom's - // recorder writes local files that open-live uploads to object storage. Reject - // the type at creation time when recording is disabled so the feature degrades - // cleanly (spec: vod-recording-minio.md, issue #41). - if (body.outputType === 'recording' && !isRecordingEnabled()) { - return reply.status(400).send({ error: 'Recording is disabled — MinIO/S3 is not configured', statusCode: 400 }); + // A 'recording' output needs somewhere to upload to — Strom's recorder writes + // local files that open-live uploads to object storage on deactivate. Accept + // it when the named storage connection resolves, or (no connection) when the + // MINIO_* env store is configured; otherwise 400 (issues #41, #534). + if (body.outputType === 'recording') { + const targetError = await recordingTargetError(body.connectionId); + if (targetError) return reply.status(400).send({ error: targetError, statusCode: 400 }); } const id = `output-${randomUUID()}`; // RTMP is an outbound connect to the platform — it leases NO SRT listener @@ -317,6 +344,10 @@ const outputsRoutes: FastifyPluginAsync = async (fastify) => { if (body.connectionId !== undefined && doc.outputType !== 'recording') { return reply.status(400).send({ error: 'connectionId is only valid on a recording output', statusCode: 400 }); } + if (body.connectionId !== undefined) { + const targetError = await recordingTargetError(body.connectionId); + if (targetError) return reply.status(400).send({ error: targetError, statusCode: 400 }); + } // ---- RTMP patch: re-resolve ingestUrl, re-encrypt/clear/keep key ---- let rtmpDoc: RtmpDestination | undefined = doc.rtmp; diff --git a/src/routes/productions.ts b/src/routes/productions.ts index 9e0c22ac..b0e1141f 100644 --- a/src/routes/productions.ts +++ b/src/routes/productions.ts @@ -3,7 +3,7 @@ import { randomUUID } from 'crypto'; import { z } from 'zod'; import { getDb, getOutputsDb, getRecordingsDb } from '../db/index.js'; import { sweepGuestsOnProductionEnd } from '../services/guest-sweep.js'; -import type { ProductionDoc, ProductionSourceAssignment, ProductionGraphicAssignment, ProductionOutputAssignment, OutputDoc, RecordingDoc } from '../db/types.js'; +import type { ProductionDoc, ProductionSourceAssignment, ProductionGraphicAssignment, ProductionOutputAssignment, OutputDoc, RecordingDoc, ActiveRecording, RecordingUploadSummary } from '../db/types.js'; import { StromClient, StromClientError } from '../lib/strom.js'; import { getStromToken } from '../lib/strom-token.js'; import { stromBrowserBaseUrl } from '../lib/strom-public-url.js'; @@ -15,8 +15,8 @@ import { clearPipState, clearAudioState, clearFxState, clearClipStateForProducti import { forceStopMeterRelay } from '../services/meter-relay.js'; import { forceStopClipRelay } from '../services/clip-relay.js'; import { config, isRecordingEnabled } from '../config.js'; -import { uploadRecordings } from '../lib/recording-uploader.js'; -import { resolveStorageTarget } from '../lib/storage-connection.js'; +import { uploadRecordings, type MinioTarget } from '../lib/recording-uploader.js'; +import { DEFAULT_CONNECTION_ID, resolveStorageTarget, StorageConnectionNotFoundError } from '../lib/storage-connection.js'; import { isIntercomEnabled, teardownIntercomProduction } from '../lib/intercom-manager.js'; import { getIdleSince, getIdleExpiresAt, notifyProductionActivated, notifyProductionDeactivated } from '../services/idle-watchdog.js'; import { buildProductionStatusEvent, deriveOutputSnapshot, stoppedStatus, type OutputStatusEntry } from '../lib/production-health.js'; @@ -197,6 +197,7 @@ const inFlightDeactivations = new Map>(); function deactivatedDoc( doc: ProductionDoc, stopped?: Pick, + lastRecordingUpload?: RecordingUploadSummary, ): ProductionDoc { const status = stopped?.status ?? stoppedStatus(doc.status); // Settle shared-GPU usage up to now (including the final partial hour) and @@ -214,6 +215,9 @@ function deactivatedDoc( audioMixerBlockId: undefined, loudnessMainBlockId: undefined, recorderBlockId: undefined, + recording: undefined, + // Replaced only by a deactivate that had a recording to upload (issue #534). + ...(lastRecordingUpload ? { lastRecordingUpload } : {}), sourceOffsetBlockIds: undefined, sourceAudioOffsetBlockIds: undefined, clipPlayerBlockIds: undefined, @@ -247,8 +251,9 @@ function deactivatedDoc( async function writeDeactivatedDoc( doc: ProductionDoc, log: FastifyBaseLogger, + lastRecordingUpload?: RecordingUploadSummary, ): Promise<{ doc: ProductionDoc; rev: string }> { - let updated = deactivatedDoc(doc); + let updated = deactivatedDoc(doc, undefined, lastRecordingUpload); for (let attempt = 0; ; attempt++) { try { const response = await getDb().insert(updated); @@ -261,10 +266,10 @@ async function writeDeactivatedDoc( (current.intercomProductionId === undefined || current.intercomProductionId === doc.intercomProductionId); if (!tornDown) throw err; if (current.status === doc.status && current.stromFlowId === doc.stromFlowId) { - updated = deactivatedDoc(current); + updated = deactivatedDoc(current, undefined, lastRecordingUpload); } else if ((current.status === 'inactive' || current.status === 'ended') && !current.stromFlowId) { log.info({ productionId: doc._id, status: current.status }, 'Production already stopped by another writer — keeping its status'); - updated = deactivatedDoc(current, current); + updated = deactivatedDoc(current, current, lastRecordingUpload); } else { throw err; } @@ -295,6 +300,167 @@ async function firstRecordingOutput( return undefined; } +/** + * Uploads the recordings of the activation being torn down and summarises the + * outcome for `ProductionDoc.lastRecordingUpload` (issue #534). Never throws. + * + * The target is the activation-time snapshot (`doc.recording`), so changing the + * production's output assignments while it is live cannot change or drop the + * upload. A production activated before the snapshot existed falls back to its + * current assignments, as before. + */ +async function uploadProductionRecording( + doc: ProductionDoc, + stromFlowId: string, + recorderBlockId: string, + strom: StromClient, + stromToken: string | undefined, + log: FastifyBaseLogger, +): Promise { + let outputId: string | undefined; + let connectionId: string | undefined; + if (doc.recording) { + ({ outputId, connectionId } = doc.recording); + } else { + const output = await firstRecordingOutput(doc, log); + outputId = output?._id; + connectionId = output?.connectionId; + } + const summarise = (fields: Partial): RecordingUploadSummary => ({ + finishedAt: new Date().toISOString(), + ...(outputId ? { outputId } : {}), + ...(connectionId ? { connectionId } : {}), + uploaded: 0, + failed: [], + ...fields, + }); + + const nothingUploaded = (reason: RecordingUploadSummary['reason'], message: string): RecordingUploadSummary => { + log.warn({ productionId: doc._id, reason }, `VOD recording not uploaded — ${message}`); + return summarise({ reason, message: `${message} The recording stays on Strom.` }); + }; + + // Resolve the target. Absent (or "default") connectionId = the env default (MINIO_*). + const namedConnection = !!connectionId && connectionId !== DEFAULT_CONNECTION_ID; + if (!namedConnection && !isRecordingEnabled()) { + return nothingUploaded( + 'no-storage-target', + 'No storage connection is set on the recording output and MINIO_* object storage is not configured.', + ); + } + let target: MinioTarget | null; + try { + target = await resolveStorageTarget(connectionId); + } catch (err) { + if (err instanceof StorageConnectionNotFoundError) { + return nothingUploaded('connection-not-found', `Storage connection "${connectionId}" was not found.`); + } + log.error({ err, productionId: doc._id }, 'could not resolve storage target for recording upload'); + return nothingUploaded('upload-error', 'The storage target could not be resolved.'); + } + if (!target) { + return namedConnection + ? nothingUploaded('connection-no-bucket', `Storage connection "${connectionId}" has no default bucket.`) + : nothingUploaded('no-storage-target', 'MINIO_* object storage is not configured.'); + } + + let uploadRes: Awaited>; + try { + await strom.recorder.splitNow(stromFlowId, recorderBlockId).catch(() => undefined); + uploadRes = await uploadRecordings({ + strom, + stromUrl: config.stromUrl, + stromToken, + outputDir: `recordings/${doc._id}`, + productionId: doc._id, + target, + // Guard (issue #366): re-check the production doc immediately before + // uploadRecordings' delete-after-upload pass. Nothing else in the + // deactivate handler writes to the production doc before its own final + // status update, which runs after this — so `doc._rev` cannot + // legitimately change between the read at the top of the handler and + // here. A different _rev means something else (most plausibly a + // reactivation) touched the doc while the upload was in flight; treat + // the activation as still live and skip deletion rather than risk + // deleting recordings it still needs. + isStillRecording: async () => { + try { + const current = await getDb().get(doc._id); + return current._rev !== doc._rev; + } catch { + // Doc gone entirely — nothing left to protect. + return false; + } + }, + }); + } catch (err) { + log.error({ err, productionId: doc._id }, 'VOD recording upload failed — continuing deactivation'); + return summarise({ + bucket: target.bucket, + reason: 'upload-error', + message: `The recording upload failed: ${err instanceof Error ? err.message : String(err)}. The recording stays on Strom.`, + }); + } + + // Persist one RecordingDoc per uploaded object so #42's listing/playback + // endpoint can enumerate and presign recordings without round-tripping the + // bucket. Best-effort: a failed persist must not block teardown. + const finalizedAt = new Date().toISOString(); + for (const seg of uploadRes.uploaded) { + try { + const recDoc: RecordingDoc = { + _id: `recording-${randomUUID()}`, + type: 'recording', + productionId: doc._id, + ...(outputId ? { outputId } : {}), + // Record which connection wrote the asset (issue #520); absent = the + // default (env) connection — no backfill on old docs. + ...(connectionId ? { connectionId } : {}), + bucket: target.bucket, + key: seg.key, + sizeBytes: seg.sizeBytes, + ...(seg.durationMs !== undefined ? { durationMs: seg.durationMs } : {}), + // The sweep also uploads segments earlier sessions left on Strom, so + // take the start from each segment's own name; otherwise this + // activation's start (issue #534), then the legacy doc.updatedAt. + startedAt: seg.startedAt ?? doc.recording?.startedAt ?? doc.updatedAt, + endedAt: finalizedAt, + createdAt: finalizedAt, + updatedAt: finalizedAt, + }; + await getRecordingsDb().insert(recDoc); + } catch (persistErr) { + log.error({ persistErr, productionId: doc._id, key: seg.key }, 'RecordingDoc persist failed — object uploaded but unlisted'); + } + } + + let reason: RecordingUploadSummary['reason']; + let message: string | undefined; + if (uploadRes.abortedOnAuthError) { + // The store rejected our credentials, so the sweep stopped after the first + // rejection instead of grinding through every segment (#465). + reason = 'auth-error'; + message = + `The object store rejected the credentials or permission (${uploadRes.abortedOnAuthError.code}); ` + + 'the upload stopped and the remaining files stay on Strom.'; + log.warn( + { productionId: doc._id, code: uploadRes.abortedOnAuthError.code, file: uploadRes.abortedOnAuthError.file }, + 'VOD recording upload sweep aborted on object-store auth/permission error — skipping remaining segments; deactivation continues', + ); + } + log.info( + { productionId: doc._id, uploaded: uploadRes.uploaded.length, failed: uploadRes.failed.length }, + 'VOD recordings uploaded to object storage', + ); + return summarise({ + bucket: target.bucket, + uploaded: uploadRes.uploaded.length, + failed: uploadRes.failed, + ...(reason ? { reason } : {}), + ...(message ? { message } : {}), + }); +} + /** * Derive the per-output health snapshot for a production from its own state * (issue #255). The signal is flow-level, so every assigned output shares the @@ -397,6 +563,9 @@ async function runActivationFlow( // Step 1: Start the Strom flow if (signal.aborted) return; + // When the recorder block (if any) starts recording — the flow is created + // and started by the call below. + const activationStartedAt = new Date().toISOString(); const activation = await activateStromFlow(doc, strom, config.stromUrl, outputDocs.length > 0 ? outputDocs : undefined); stromFlowId = activation.flowId; mixerBlockId = activation.mixerBlockId ?? undefined; @@ -413,8 +582,23 @@ async function runActivationFlow( await deactivateStromFlow(stromFlowId, strom).catch(() => undefined); return; } + // Snapshot the recording's upload target with the recorder block (issue + // #534): deactivate uploads to this, not to whatever the assignments say by + // then. Written as undefined when there is no recorder so a stale snapshot + // from an earlier activation never leaks into this one. + const recordingOutput = activation.recorderOutputId + ? outputDocs.find((o) => o._id === activation.recorderOutputId) + : undefined; + const recording: ActiveRecording | undefined = activation.recorderBlockId && recordingOutput + ? { + outputId: recordingOutput._id, + ...(recordingOutput.connectionId ? { connectionId: recordingOutput.connectionId } : {}), + startedAt: activationStartedAt, + } + : undefined; await updateProductionDoc(productionId, { stromFlowId, + recording, ...(mixerBlockId !== undefined && { mixerBlockId }), ...(audioMixerBlockId !== undefined && { audioMixerBlockId }), ...(loudnessMainBlockId !== undefined && { loudnessMainBlockId }), @@ -1062,111 +1246,17 @@ const productionsRoutes: FastifyPluginAsync = async (fastify) => { // group assignments — these are live-only and must not survive deactivation. broadcast(doc._id, { type: 'GRP_STATE_RESET' }); broadcast(doc._id, { type: 'PRODUCTION_DEACTIVATED' }); + let lastRecordingUpload: RecordingUploadSummary | undefined; if (doc.stromFlowId) { const stromToken = await getStromToken(config.stromToken).catch((err) => { log.error({ errMsg: err instanceof Error ? err.message : String(err) }, "SAT exchange failed — proceeding without auth"); return undefined; }); const strom = new StromClient({ baseUrl: config.stromUrl, token: stromToken }); // VOD recording (issue #41): when a recorder block is active, finalise - // the current segment (recorder.splitNow) then upload Strom's local - // recordings to MinIO — Strom's recorder has no native S3 sink, so - // open-live pulls the segments and pushes them to object storage. - // Best-effort: a failed upload must not block deactivation/teardown. - // Resolve the recording output first: a `recording` output may carry a - // storage connectionId (issue #520) that routes its segments to a store - // other than the env default. Absent connectionId = the env default, - // exactly as before (gated by isRecordingEnabled). - const recordingOutput = doc.recorderBlockId ? await firstRecordingOutput(doc, log) : undefined; - const recordingConnectionId = recordingOutput?.connectionId; - if (doc.recorderBlockId && (isRecordingEnabled() || recordingConnectionId)) { - const target = await resolveStorageTarget(recordingConnectionId).catch((err) => { - log.error({ err, productionId: doc._id }, 'could not resolve storage connection for recording upload'); - return null; - }); - if (target) { - try { - await strom.recorder.splitNow(doc.stromFlowId, doc.recorderBlockId).catch(() => undefined); - const uploadRes = await uploadRecordings({ - strom, - stromUrl: config.stromUrl, - stromToken, - outputDir: `recordings/${doc._id}`, - productionId: doc._id, - target, - // Guard (issue #366): re-check the production doc immediately - // before uploadRecordings' delete-after-upload pass. Nothing - // else in this handler writes to the production doc before its - // own final status update below, which runs after this block — - // so `doc._rev` cannot legitimately change between the read at - // the top of this handler and here. A different _rev means - // something else (most plausibly a reactivation) touched the - // doc while the upload was in flight; treat the activation as - // still live and skip deletion rather than risk deleting - // recordings it still needs. - isStillRecording: async () => { - try { - const current = await getDb().get(doc._id); - return current._rev !== doc._rev; - } catch { - // Doc gone entirely — nothing left to protect. - return false; - } - }, - }); - // Persist one RecordingDoc per uploaded object so #42's listing/ - // playback endpoint can enumerate and presign recordings without - // round-tripping the bucket. Best-effort: a failed persist must not - // block teardown, mirroring the upload's non-fatal contract. - const recordingOutputId = recordingOutput?._id; - const finalizedAt = new Date().toISOString(); - for (const seg of uploadRes.uploaded) { - try { - const recId = `recording-${randomUUID()}`; - const recDoc: RecordingDoc = { - _id: recId, - type: 'recording', - productionId: doc._id, - ...(recordingOutputId ? { outputId: recordingOutputId } : {}), - // Record which connection wrote the asset (issue #520); absent - // = the default (env) connection — no backfill on old docs. - ...(recordingConnectionId ? { connectionId: recordingConnectionId } : {}), - bucket: target.bucket, - key: seg.key, - sizeBytes: seg.sizeBytes, - // The sweep also uploads segments earlier sessions left on - // Strom, so take the start from each segment's own name; - // doc.updatedAt is this activation's start. - startedAt: seg.startedAt ?? doc.updatedAt, - endedAt: finalizedAt, - createdAt: finalizedAt, - updatedAt: finalizedAt, - }; - await getRecordingsDb().insert(recDoc); - } catch (persistErr) { - log.error({ persistErr, productionId: doc._id, key: seg.key }, 'RecordingDoc persist failed — object uploaded but unlisted'); - } - } - if (uploadRes.abortedOnAuthError) { - // Best-effort upload is bounded by time, not just failures: the - // store rejected our credentials, so the sweep stopped after the - // first rejection instead of grinding through every segment. - // Teardown (deactivateStromFlow + guest sweep, below) continues. - log.warn( - { - productionId: doc._id, - code: uploadRes.abortedOnAuthError.code, - file: uploadRes.abortedOnAuthError.file, - }, - 'VOD recording upload sweep aborted on object-store auth/permission error — skipping remaining segments; deactivation continues', - ); - } - log.info( - { productionId: doc._id, uploaded: uploadRes.uploaded.length, failed: uploadRes.failed.length }, - 'VOD recordings uploaded to object storage', - ); - } catch (err) { - log.error({ err, productionId: doc._id }, 'VOD recording upload failed — continuing deactivation'); - } - } + // the current segment and upload Strom's local recordings to object + // storage. Best-effort: a failed upload must not block teardown. The + // outcome is stored on the production as `lastRecordingUpload` (#534). + if (doc.recorderBlockId) { + lastRecordingUpload = await uploadProductionRecording(doc, doc.stromFlowId, doc.recorderBlockId, strom, stromToken, log); } await deactivateStromFlow(doc.stromFlowId, strom); @@ -1190,7 +1280,7 @@ const productionsRoutes: FastifyPluginAsync = async (fastify) => { // deactivation, matching the Strom/intercom teardown contract. await sweepGuestsOnProductionEnd(doc._id, log); - const { doc: stored, rev } = await writeDeactivatedDoc(doc, log); + const { doc: stored, rev } = await writeDeactivatedDoc(doc, log, lastRecordingUpload); notifyProductionDeactivated(doc._id); emitProductionStatus(stored); return { id: stored._id, name: stored.name, status: stored.status, _rev: rev }; diff --git a/src/routes/recordings.ts b/src/routes/recordings.ts index cd5a37cb..864ef806 100644 --- a/src/routes/recordings.ts +++ b/src/routes/recordings.ts @@ -12,27 +12,46 @@ * GET /api/v1/recordings list recordings across productions * GET /api/v1/recordings/:id fetch a single recording * - * When object storage is not configured the endpoints return 503 rather than - * pretending recordings exist, mirroring how the `recording` output type is - * rejected at assignment time (issue #41). + * The routes work whether or not the `MINIO_*` env store is configured: a + * recording written to a storage connection (issue #520) is signed against + * that connection, so a connection-only instance lists and plays its + * recordings (issue #534). Only a database failure returns 503. + * + * Each recording carries `playbackUrl` and `downloadUrl` (the same presigned + * GET, plus a signed `response-content-disposition: attachment` so a browser + * saves it under the object's basename). When neither can be signed, + * `playbackUnavailable` says why instead. */ import type { FastifyBaseLogger, FastifyPluginAsync } from 'fastify'; import { getDb, getRecordingsDb } from '../db/index.js'; import type { RecordingDoc } from '../db/types.js'; -import { config, isRecordingEnabled } from '../config.js'; +import { config } from '../config.js'; import { minioTargetFromConfig, presignGetUrl, type MinioTarget } from '../lib/recording-uploader.js'; -import { resolveStorageTarget } from '../lib/storage-connection.js'; +import { resolveStorageTarget, StorageConnectionNotFoundError } from '../lib/storage-connection.js'; + +/** Why a recording has no `playbackUrl` / `downloadUrl` (issue #534). */ +export type PlaybackUnavailableReason = + | 'connection-missing' // its storage connection no longer exists + | 'connection-no-bucket' // the connection resolves to no bucket + | 'storage-not-configured' // default-connection recording, MINIO_* not configured + | 'bucket-mismatch' // default-connection recording in a bucket other than MINIO_BUCKET + | 'signing-failed'; // anything else went wrong while signing + +/** + * File name a downloaded recording is saved under: the object key's basename, + * restricted to a header-safe character set, with an `.mp4` extension. + */ +export function downloadFileName(key: string): string { + const base = key.split('/').pop() || 'recording'; + const safe = base.replace(/[^A-Za-z0-9._-]/g, '_'); + return /\.mp4$/i.test(safe) ? safe : `${safe.replace(/\.[^.]*$/, '')}.mp4`; +} /** * Maps a stored RecordingDoc to the public API shape: `_id` → `id`, drops the - * CouchDB envelope, and attaches a presigned `playbackUrl`. The presign is - * derived on read (never persisted) so the URL is always freshly time-boxed. - * - * A recording that carries a `connectionId` (issue #520) is presigned against - * that connection's target (bucket from the doc). One without (every pre-#520 - * recording) keeps the current default-bucket-matched path, so old recordings - * are unaffected. When presigning is not possible (storage misconfigured, or a - * since-deleted connection) `playbackUrl` is omitted rather than mis-signed. + * CouchDB envelope, and attaches presigned `playbackUrl` + `downloadUrl` (or a + * `playbackUnavailable` reason). Presigns are derived on read (never persisted) + * so the URLs are always freshly time-boxed. */ async function toApi( doc: RecordingDoc, @@ -41,33 +60,53 @@ async function toApi( ): Promise> { const { _id, _rev, type, ...rest } = doc; const api: Record = { id: _id, ...rest }; - const url = await presignRecording(doc, defaultTarget, log); - if (url) api['playbackUrl'] = url; + const signed = await presignRecording(doc, defaultTarget, log); + if ('reason' in signed) { + api['playbackUnavailable'] = signed.reason; + } else { + api['playbackUrl'] = signed.playbackUrl; + api['downloadUrl'] = signed.downloadUrl; + } return api; } +/** + * Resolves the target a recording was written to and signs both URLs. + * + * A recording with a `connectionId` (issue #520) is signed against that + * connection (bucket from the doc). One without (every pre-#520 recording) + * keeps the default-bucket-matched path: it is only signed when the stored + * bucket matches the configured one, since a since-reconfigured bucket cannot + * be signed with the current credentials (unchanged from #42). + */ async function presignRecording( doc: RecordingDoc, defaultTarget: MinioTarget | null, log: FastifyBaseLogger, -): Promise { +): Promise<{ playbackUrl: string; downloadUrl: string } | { reason: PlaybackUnavailableReason }> { + let target: MinioTarget; try { if (doc.connectionId) { - // Presign against the connection that wrote the asset (bucket from the - // doc). A since-deleted connection throws → omit playbackUrl, exactly as - // the default-path bucket mismatch below degrades. - const target = await resolveStorageTarget(doc.connectionId, doc.bucket); - if (!target) return undefined; - return presignGetUrl(target, doc.key, config.recordingPresignTtlS); + const resolved = await resolveStorageTarget(doc.connectionId, doc.bucket); + if (!resolved) return { reason: 'connection-no-bucket' }; + target = resolved; + } else { + if (!defaultTarget) return { reason: 'storage-not-configured' }; + if (doc.bucket !== defaultTarget.bucket) return { reason: 'bucket-mismatch' }; + target = defaultTarget; } - // Default path: only presign when the stored bucket matches the configured - // one — a recording persisted against a different (since-reconfigured) - // bucket cannot be signed with the current credentials (unchanged from #42). - if (!defaultTarget || doc.bucket !== defaultTarget.bucket) return undefined; - return presignGetUrl(defaultTarget, doc.key, config.recordingPresignTtlS); + const now = new Date(); + const ttl = config.recordingPresignTtlS; + return { + playbackUrl: presignGetUrl(target, doc.key, ttl, now), + downloadUrl: presignGetUrl(target, doc.key, ttl, now, { + contentDisposition: `attachment; filename="${downloadFileName(doc.key)}"`, + }), + }; } catch (err) { + if (err instanceof StorageConnectionNotFoundError) return { reason: 'connection-missing' }; log.warn({ err, key: doc.key }, 'recordings — presign failed, omitting playbackUrl'); - return undefined; + return { reason: 'signing-failed' }; } } @@ -76,9 +115,6 @@ const recordingsRoutes: FastifyPluginAsync = async (fastify) => { fastify.get<{ Params: { id: string } }>( '/api/v1/productions/:id/recordings', async (req, reply) => { - if (!isRecordingEnabled()) { - return reply.status(503).send({ error: 'Object storage unavailable', statusCode: 503 }); - } // 404 when the production itself does not exist, matching the other // production sub-resource routes. try { @@ -107,9 +143,6 @@ const recordingsRoutes: FastifyPluginAsync = async (fastify) => { // List recordings across all productions. fastify.get('/api/v1/recordings', async (_req, reply) => { - if (!isRecordingEnabled()) { - return reply.status(503).send({ error: 'Object storage unavailable', statusCode: 503 }); - } const defaultTarget = minioTargetFromConfig(); let result: Awaited['find']>>; try { @@ -127,16 +160,20 @@ const recordingsRoutes: FastifyPluginAsync = async (fastify) => { // Fetch a single recording. fastify.get<{ Params: { id: string } }>('/api/v1/recordings/:id', async (req, reply) => { - if (!isRecordingEnabled()) { - return reply.status(503).send({ error: 'Object storage unavailable', statusCode: 503 }); - } const defaultTarget = minioTargetFromConfig(); + let doc: RecordingDoc; try { - const doc = await getRecordingsDb().get(req.params.id); - return reply.send(await toApi(doc, defaultTarget, fastify.log)); - } catch { - return reply.status(404).send({ error: 'Recording not found', statusCode: 404 }); + doc = await getRecordingsDb().get(req.params.id); + } catch (err) { + // A missing doc (or an id naming another document type) is a 404; any + // other failure is the database being unavailable. + const notFound = (err as { statusCode?: number } | null)?.statusCode === 404 + || (err instanceof Error && err.message.startsWith('Document type mismatch')); + if (notFound) return reply.status(404).send({ error: 'Recording not found', statusCode: 404 }); + fastify.log.warn({ err }, 'GET /api/v1/recordings/:id — DB read failed'); + return reply.status(503).send({ error: 'Database unavailable', statusCode: 503 }); } + return reply.send(await toApi(doc, defaultTarget, fastify.log)); }); }; From 24b364ef08655a9f84c70c2d0d19461f6f293944 Mon Sep 17 00:00:00 2001 From: "eyevinn-developer[bot]" <343978855+eyevinn-developer[bot]@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:22:59 +0000 Subject: [PATCH 2/2] fix(recording): return 503 when the production lookup fails on a DB outage GET /api/v1/productions/:id/recordings mapped any failure of the production lookup to 404, so a CouchDB outage returned 404 instead of 503. Split not-found from unavailable with a shared isDocNotFoundError helper (also used by /recordings/:id and the output storage check), and make the test's dbDown flag fail the production lookup too. Add tests for the legacy upload-target fallback (no recording snapshot, assigned output on a storage connection) and for the #366 _rev guard passed to uploadRecordings. Document what lastRecordingUpload.failed[].error may contain. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/recording-upload-target.test.ts | 49 +++++++++++++++++++ .../recordings-routes-connection-only.test.ts | 8 +++ src/db/types.ts | 8 ++- src/lib/db-errors.ts | 15 ++++++ src/routes/outputs.ts | 5 +- src/routes/recordings.ts | 14 ++++-- 6 files changed, 90 insertions(+), 9 deletions(-) create mode 100644 src/lib/db-errors.ts diff --git a/src/__tests__/recording-upload-target.test.ts b/src/__tests__/recording-upload-target.test.ts index c7906448..97d0a7b0 100644 --- a/src/__tests__/recording-upload-target.test.ts +++ b/src/__tests__/recording-upload-target.test.ts @@ -311,6 +311,55 @@ describe('recording upload target snapshot (issue #534)', () => { await app.close(); }); + it('falls back to the assigned output connection for a production activated before the snapshot existed', async () => { + // Legacy shape: recorderBlockId set, no `recording` snapshot. The assigned + // recording output names stconn-C, so the upload must go there. + productions.set('prod-1', production({ + status: 'active', stromFlowId: 'flow-1', recorderBlockId: 'b-out-rec', + })); + expect(productions.get('prod-1')!.recording).toBeUndefined(); + mockUploadRecordings.mockResolvedValue({ + uploaded: [{ key: 'prod-1/seg.mp4', sizeBytes: 1, stromPath: 'recordings/prod-1/seg.mp4' }], + failed: [], + }); + const app = await buildServer(); + const res = await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(res.statusCode).toBe(200); + expect(mockUploadRecordings).toHaveBeenCalledTimes(1); + const args = mockUploadRecordings.mock.calls[0]![0] as { target: { bucket: string; endpoint: string; accessKey: string } }; + expect(args.target).toMatchObject({ bucket: 'tenant-vod', endpoint: 's3.tenant.example.com', accessKey: 'AKTENANT' }); + expect(recordingInserts[0]).toMatchObject({ outputId: 'output-rec', connectionId: 'stconn-C', bucket: 'tenant-vod' }); + expect(productions.get('prod-1')!.lastRecordingUpload).toMatchObject({ + outputId: 'output-rec', connectionId: 'stconn-C', uploaded: 1, + }); + await app.close(); + }); + + it('passes an isStillRecording guard that reports true once the stored _rev changes (#366)', async () => { + productions.set('prod-1', production({ + status: 'active', stromFlowId: 'flow-1', recorderBlockId: 'b-out-rec', + recording: { outputId: 'output-rec', connectionId: 'stconn-C', startedAt: NOW }, + })); + let guardBefore: boolean | undefined; + let guardAfter: boolean | undefined; + mockUploadRecordings.mockImplementation(async (opts: { isStillRecording: () => Promise }) => { + // Unchanged _rev: the activation being torn down is not live any more. + guardBefore = await opts.isStillRecording(); + // Something (e.g. a reactivation) writes the production mid-upload. + const current = productions.get('prod-1')!; + productions.set('prod-1', { ...current, _rev: `${++rev}-reactivated` }); + guardAfter = await opts.isStillRecording(); + return { uploaded: [], failed: [] }; + }); + const app = await buildServer(); + const res = await app.inject({ method: 'POST', url: '/api/v1/productions/prod-1/deactivate' }); + expect(res.statusCode).toBe(200); + expect(mockUploadRecordings).toHaveBeenCalledTimes(1); + expect(guardBefore).toBe(false); + expect(guardAfter).toBe(true); + await app.close(); + }); + it('keeps the previous summary when a deactivate has no recording', async () => { const previous = { finishedAt: NOW, uploaded: 2, failed: [] }; productions.set('prod-1', production({ status: 'active', stromFlowId: 'flow-1', lastRecordingUpload: previous })); diff --git a/src/__tests__/recordings-routes-connection-only.test.ts b/src/__tests__/recordings-routes-connection-only.test.ts index 8776ccff..aa07c493 100644 --- a/src/__tests__/recordings-routes-connection-only.test.ts +++ b/src/__tests__/recordings-routes-connection-only.test.ts @@ -27,6 +27,8 @@ function notFound(): Error { vi.mock('../db/index.js', () => ({ getDb: () => ({ get: vi.fn(async (id: string) => { + // Same CouchDB as the recordings DB: an outage fails this lookup first. + if (dbDown) throw Object.assign(new Error('ECONNREFUSED'), { code: 'ECONNREFUSED' }); if (id !== 'prod-1') throw notFound(); return { _id: 'prod-1' }; }), @@ -162,6 +164,12 @@ describe('recordings routes without MINIO_* (connection-only instance)', () => { expect(one.statusCode).toBe(503); }); + it('returns 404 for a missing production', async () => { + const res = await app.inject({ method: 'GET', url: '/api/v1/productions/prod-missing/recordings', headers: AUTH }); + expect(res.statusCode).toBe(404); + expect(res.json().error).toBe('Production not found'); + }); + it('returns 404 for a missing recording', async () => { const res = await app.inject({ method: 'GET', url: '/api/v1/recordings/recording-missing', headers: AUTH }); expect(res.statusCode).toBe(404); diff --git a/src/db/types.ts b/src/db/types.ts index 045fa26f..e26eb930 100644 --- a/src/db/types.ts +++ b/src/db/types.ts @@ -428,7 +428,13 @@ export interface RecordingUploadSummary { bucket?: string; /** Number of files uploaded (and listed as recordings). */ uploaded: number; - /** Files that failed to upload; they stay on Strom for the next sweep. */ + /** + * Files that failed to upload; they stay on Strom for the next sweep. + * `error` includes up to the first 200 characters of the S3 error body. It + * never holds the secret key or a presigned URL (PUT uses header auth). For + * some codes S3 echoes ``/`` later in the body; + * the 200-character cut normally drops those. + */ failed: Array<{ file: string; error: string }>; /** Set when nothing was attempted or the sweep stopped early. */ reason?: RecordingUploadReason; diff --git a/src/lib/db-errors.ts b/src/lib/db-errors.ts new file mode 100644 index 00000000..69f1986a --- /dev/null +++ b/src/lib/db-errors.ts @@ -0,0 +1,15 @@ +/** + * Classifies a CouchDB `.get()` failure. + * + * A document is "not found" when CouchDB answers 404, or when the id names a + * document of another type (the `withTypeGuard` mismatch in `src/db/index.ts`). + * Anything else (connection refused, timeout, 5xx) is the database being + * unavailable, which callers should report as 503 rather than 404. + * + * Kept outside `src/db/index.ts` on purpose: many tests replace that module + * wholesale with `vi.mock`, which would drop this helper. + */ +export function isDocNotFoundError(err: unknown): boolean { + if ((err as { statusCode?: number } | null)?.statusCode === 404) return true; + return err instanceof Error && err.message.startsWith('Document type mismatch'); +} diff --git a/src/routes/outputs.ts b/src/routes/outputs.ts index 99842f93..8f8727c6 100644 --- a/src/routes/outputs.ts +++ b/src/routes/outputs.ts @@ -12,6 +12,7 @@ import { resolveIngestUrl, validateStreamKey } from '../lib/rtmp.js'; import { resolveSrtConnect } from '../lib/srt-connect.js'; import { config, isRecordingEnabled } from '../config.js'; import { DEFAULT_CONNECTION_ID } from '../lib/storage-connection.js'; +import { isDocNotFoundError } from '../lib/db-errors.js'; import { getPortReservation } from '../services/port-reservation.js'; import { clashesAfterWrite, listenerPortRequest, resolveListenerAddress, usedListenerPorts } from '../services/listener-ports.js'; @@ -94,9 +95,7 @@ async function recordingTargetError(connectionId: string | undefined): Promise { async (req, reply) => { // 404 when the production itself does not exist, matching the other // production sub-resource routes. + // Any other lookup failure is the database being unavailable (503). try { await getDb().get(req.params.id); - } catch { - return reply.status(404).send({ error: 'Production not found', statusCode: 404 }); + } catch (err) { + if (isDocNotFoundError(err)) { + return reply.status(404).send({ error: 'Production not found', statusCode: 404 }); + } + fastify.log.warn({ err }, 'GET /api/v1/productions/:id/recordings — production lookup failed'); + return reply.status(503).send({ error: 'Database unavailable', statusCode: 503 }); } const defaultTarget = minioTargetFromConfig(); let result: Awaited['find']>>; @@ -167,9 +173,7 @@ const recordingsRoutes: FastifyPluginAsync = async (fastify) => { } catch (err) { // A missing doc (or an id naming another document type) is a 404; any // other failure is the database being unavailable. - const notFound = (err as { statusCode?: number } | null)?.statusCode === 404 - || (err instanceof Error && err.message.startsWith('Document type mismatch')); - if (notFound) return reply.status(404).send({ error: 'Recording not found', statusCode: 404 }); + if (isDocNotFoundError(err)) return reply.status(404).send({ error: 'Recording not found', statusCode: 404 }); fastify.log.warn({ err }, 'GET /api/v1/recordings/:id — DB read failed'); return reply.status(503).send({ error: 'Database unavailable', statusCode: 503 }); }