Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/repo-patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
4 changes: 4 additions & 0 deletions docs/specs/storage-connections.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
44 changes: 41 additions & 3 deletions docs/specs/vod-recording-minio.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, ... ]
Expand All @@ -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="<basename>.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 |
Expand All @@ -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

Expand Down
75 changes: 75 additions & 0 deletions src/__tests__/mp4-duration.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
165 changes: 165 additions & 0 deletions src/__tests__/outputs-recording-target.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, OutputDoc>();
const connections = new Map<string, StorageConnectionDoc>();

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> = {}): 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');
});
});
26 changes: 26 additions & 0 deletions src/__tests__/recording-leftover-sweep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
Loading
Loading