Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: retain recording sources and resume processing durably

Richie McIlroy9da226849951
diff --git a/apps/web/__tests__/unit/desktop-recording-job-status.test.ts b/apps/web/__tests__/unit/desktop-recording-job-status.test.ts
index b9443bf43..b2c29c690 100644
--- a/apps/web/__tests__/unit/desktop-recording-job-status.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-job-status.test.ts
@@ -1,5 +1,8 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { reconcileDesktopRecordingJob } from "@/lib/desktop-recording-job-status";
+import {
+ observeDesktopRecordingJob,
+ reconcileDesktopRecordingJob,
+} from "@/lib/desktop-recording-job-status";
const input = {
videoId: "video",
@@ -69,4 +72,59 @@ describe("recording job completion reconciliation", () => {
vi.stubGlobal("fetch", fetcher);
expect(await reconcileDesktopRecordingJob(input)).toBe(false);
});
+
+ it.each([
+ { generation: "old", attemptId: "attempt", inventorySha256: "inventory" },
+ {
+ generation: "generation",
+ attemptId: "old",
+ inventorySha256: "inventory",
+ },
+ { generation: "generation", attemptId: "attempt", inventorySha256: "old" },
+ {},
+ ])(
+ "never forwards a completion outside the current immutable attempt %j",
+ async (context) => {
+ const fetcher = vi.fn().mockResolvedValueOnce(
+ Response.json({
+ jobId: "job",
+ videoId: "video",
+ phase: "complete",
+ ...context,
+ }),
+ );
+ vi.stubGlobal("fetch", fetcher);
+ expect(
+ await observeDesktopRecordingJob({
+ ...input,
+ generation: "generation",
+ attemptId: "attempt",
+ inventorySha256: "inventory",
+ }),
+ ).toEqual({ status: "unavailable", delivered: false });
+ expect(fetcher).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("distinguishes a positively observed active attempt from a lost worker", async () => {
+ const context = {
+ generation: "generation",
+ attemptId: "attempt",
+ inventorySha256: "inventory",
+ };
+ const fetcher = vi.fn().mockResolvedValueOnce(
+ Response.json({
+ jobId: "job",
+ videoId: "video",
+ phase: "processing",
+ ...context,
+ }),
+ );
+ vi.stubGlobal("fetch", fetcher);
+ expect(await observeDesktopRecordingJob({ ...input, ...context })).toEqual({
+ status: "active",
+ delivered: false,
+ });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/web/__tests__/unit/desktop-recording-jobs.test.ts b/apps/web/__tests__/unit/desktop-recording-jobs.test.ts
new file mode 100644
index 000000000..e63fe8a3d
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-recording-jobs.test.ts
@@ -0,0 +1,682 @@
+import type { User, Video } from "@cap/web-domain";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ attachRemoteJob,
+ claimProcessingAttempt,
+ type DesktopRecordingAttemptFence,
+ type DesktopRecordingJob,
+ ensureSegmentProcessingJob,
+ getDesktopRecordingRetryDelay,
+ heartbeatAttempt,
+ initializeSourceCommitCheckpoint,
+ isDesktopRecordingJobRecoverable,
+ markSourceBlocked,
+ persistCommittedSource,
+ persistSourceCommitCheckpoint,
+ retireDesktopRecordingJobForOutputReplacement,
+ scheduleRetry,
+} from "@/lib/desktop-recording-jobs";
+import type { RecordingVerification } from "@/lib/desktop-recording-verification";
+
+const mocks = vi.hoisted(() => ({ db: vi.fn() }));
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/database/schema", () => {
+ const table = (name: string, fields: string[]) =>
+ Object.fromEntries([
+ ["table", name],
+ ...fields.map((field) => [field, `${name}.${field}`]),
+ ]);
+ return {
+ videos: table("videos", ["id", "ownerId", "source"]),
+ videoUploads: table("uploads", ["videoId"]),
+ videoProcessingJobs: table("jobs", [
+ "videoId",
+ "ownerId",
+ "generation",
+ "state",
+ "attemptId",
+ "attemptCount",
+ "source",
+ "nextRetryAt",
+ "leaseExpiresAt",
+ "remoteJobId",
+ ]),
+ };
+});
+vi.mock("drizzle-orm", () => ({
+ and: (...args: unknown[]) => ({ op: "and", args }),
+ or: (...args: unknown[]) => ({ op: "or", args }),
+ eq: (column: string, value: unknown) => ({ op: "eq", column, value }),
+ ne: (column: string, value: unknown) => ({ op: "ne", column, value }),
+ lte: (column: string, value: unknown) => ({ op: "lte", column, value }),
+ gt: (column: string, value: unknown) => ({ op: "gt", column, value }),
+ inArray: (column: string, value: unknown[]) => ({ op: "in", column, value }),
+ isNull: (column: string) => ({ op: "null", column }),
+ asc: (column: string) => column,
+ getTableColumns: (table: Record<string, string>) => table,
+}));
+
+type Row = Record<string, unknown>;
+type Table = { table: string };
+type Condition = {
+ op: string;
+ args?: (Condition | undefined)[];
+ column?: string;
+ value?: unknown;
+};
+
+const videoId = "video" as Video.VideoId;
+const userId = "user" as User.UserId;
+const now = new Date("2026-09-02T12:00:00.000Z");
+const manifestSha256 = "a".repeat(64);
+const source = {
+ version: 1 as const,
+ kind: "segments" as const,
+ manifestSha256,
+ inventorySha256: "b".repeat(64),
+ inventoryKey: "user/video/.recording/sources/generation/inventory.json",
+ requiredAudio: true,
+};
+const verification: RecordingVerification = {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256 },
+ requiredAudio: true,
+};
+
+let rows: Record<string, Row[]>;
+let lockingOperations: string[];
+
+function matches(row: Row, condition?: Condition): boolean {
+ if (!condition) return true;
+ if (condition.op === "and")
+ return (condition.args ?? []).every((part) => matches(row, part));
+ if (condition.op === "or")
+ return (condition.args ?? []).some((part) => matches(row, part));
+ const value = row[condition.column?.split(".")[1] ?? ""];
+ if (condition.op === "eq") return value === condition.value;
+ if (condition.op === "ne") return value !== condition.value;
+ if (condition.op === "null") return value === null || value === undefined;
+ if (condition.op === "in")
+ return Array.isArray(condition.value) && condition.value.includes(value);
+ if (condition.op === "lte") return Number(value) <= Number(condition.value);
+ if (condition.op === "gt") return Number(value) > Number(condition.value);
+ throw new Error(`Unexpected condition ${condition.op}`);
+}
+
+function createClient() {
+ const client = {
+ select(fields?: Record<string, string>) {
+ let table = "";
+ let condition: Condition | undefined;
+ const run = () =>
+ (rows[table] ?? [])
+ .filter((row) => matches(row, condition))
+ .map((row) => {
+ if (!fields) return { ...row };
+ return Object.fromEntries(
+ Object.entries(fields).map(([name, column]) => [
+ name,
+ row[column.split(".")[1] ?? ""],
+ ]),
+ );
+ });
+ const query = {
+ from(value: Table) {
+ table = value.table;
+ return query;
+ },
+ where(value: Condition) {
+ condition = value;
+ return query;
+ },
+ for: async () => {
+ lockingOperations.push(`select:${table}`);
+ return run();
+ },
+ limit: async (limit: number) => run().slice(0, limit),
+ };
+ return query;
+ },
+ update(table: Table) {
+ return {
+ set(values: Row) {
+ return {
+ where: async (condition: Condition) => {
+ const matching = (rows[table.table] ?? []).filter((row) =>
+ matches(row, condition),
+ );
+ for (const row of matching) Object.assign(row, values);
+ return [{ affectedRows: matching.length }];
+ },
+ };
+ },
+ };
+ },
+ insert(table: Table) {
+ return {
+ values(values: Row) {
+ const run = async (update?: Row) => {
+ lockingOperations.push(
+ `${update ? "upsert" : "insert"}:${table.table}`,
+ );
+ const stored = (rows[table.table] ?? []).find(
+ (row) => row.videoId === values.videoId,
+ );
+ if (stored) {
+ if (!update) throw new Error("Duplicate row");
+ Object.assign(stored, update);
+ } else {
+ rows[table.table]?.push({ ...values });
+ }
+ return [{ affectedRows: 1 }];
+ };
+ let updates: Row | undefined;
+ const pending = Promise.resolve().then(() => run(updates));
+ return Object.assign(pending, {
+ onDuplicateKeyUpdate: ({ set }: { set: Row }) => {
+ updates = set;
+ return pending;
+ },
+ });
+ },
+ };
+ },
+ };
+ let tail = Promise.resolve();
+ return {
+ ...client,
+ async transaction(callback: (tx: typeof client) => Promise<unknown>) {
+ const previous = tail;
+ let release = () => {};
+ tail = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await previous;
+ const before = structuredClone(rows);
+ try {
+ return await callback(client);
+ } catch (error) {
+ rows = before;
+ throw error;
+ } finally {
+ release();
+ }
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(now);
+ lockingOperations = [];
+ rows = {
+ videos: [
+ { id: videoId, ownerId: userId, source: { type: "desktopSegments" } },
+ ],
+ jobs: [],
+ uploads: [],
+ };
+ mocks.db.mockReturnValue(createClient());
+});
+
+afterEach(() => vi.useRealTimers());
+
+async function createAttempt(withVerification = true) {
+ const { job } = await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification: withVerification ? verification : undefined,
+ });
+ const attempt = await claimProcessingAttempt({
+ videoId,
+ generation: job.generation,
+ });
+ if (!attempt) throw new Error("Fixture attempt was not claimed");
+ return attempt;
+}
+
+describe("durable recording job ownership", () => {
+ it("establishes the job row before taking locking reads to prevent concurrent first-insert deadlocks", async () => {
+ await ensureSegmentProcessingJob({ videoId, userId });
+ expect(lockingOperations.slice(0, 3)).toEqual([
+ "upsert:jobs",
+ "select:jobs",
+ "select:videos",
+ ]);
+ });
+
+ it("creates one logical generation for concurrent completion requests", async () => {
+ const results = await Promise.all([
+ ensureSegmentProcessingJob({ videoId, userId, verification }),
+ ensureSegmentProcessingJob({ videoId, userId, verification }),
+ ]);
+ expect(results.filter((result) => result.created)).toHaveLength(1);
+ expect(new Set(results.map((result) => result.job.generation)).size).toBe(
+ 1,
+ );
+ expect(rows.jobs).toHaveLength(1);
+ });
+
+ it("claims only one attempt when two workflows wake together", async () => {
+ const { job } = await ensureSegmentProcessingJob({ videoId, userId });
+ const results = await Promise.all([
+ claimProcessingAttempt({ videoId, generation: job.generation }),
+ claimProcessingAttempt({ videoId, generation: job.generation }),
+ ]);
+ expect(results.filter(Boolean)).toHaveLength(1);
+ expect(rows.jobs?.[0]?.attemptCount).toBe(1);
+ });
+
+ it("rejects stale attempt heartbeats, remote jobs, and errors after a retry takes over", async () => {
+ const old = await createAttempt();
+ vi.setSystemTime(new Date(now.getTime() + 6 * 60_000));
+ const next = await claimProcessingAttempt({
+ videoId,
+ generation: old.generation,
+ });
+ expect(next?.attemptId).not.toBe(old.attemptId);
+ expect(await heartbeatAttempt(old)).toBe(false);
+ expect(await attachRemoteJob({ ...old, remoteJobId: "stale-worker" })).toBe(
+ false,
+ );
+ expect(
+ await scheduleRetry({
+ ...old,
+ errorCode: "stale-error",
+ errorMessage: "old callback",
+ }),
+ ).toBe(false);
+ expect(rows.jobs?.[0]?.attemptId).toBe(next?.attemptId);
+ });
+
+ it("does not mutate an upload owned by another account", async () => {
+ await expect(
+ ensureSegmentProcessingJob({ videoId, userId: "other" as User.UserId }),
+ ).rejects.toThrow("does not exist");
+ expect(rows.jobs).toEqual([]);
+ });
+
+ it("does not revive an expired attempt before another worker has claimed it", async () => {
+ const expired = await createAttempt();
+ const checkpoint = await initializeSourceCommitCheckpoint(expired);
+ if (!checkpoint) throw new Error("Missing checkpoint");
+ vi.setSystemTime(new Date(now.getTime() + 6 * 60_000));
+ expect(await heartbeatAttempt(expired)).toBe(false);
+ expect(
+ await attachRemoteJob({ ...expired, remoteJobId: "late-worker" }),
+ ).toBe(false);
+ expect(await persistCommittedSource(expired, source)).toBe(false);
+ expect(
+ await persistSourceCommitCheckpoint(expired, {
+ ...checkpoint,
+ revision: 1,
+ }),
+ ).toBe(false);
+ expect(rows.jobs?.[0]).toMatchObject({
+ attemptId: expired.attemptId,
+ source: null,
+ remoteJobId: null,
+ output: checkpoint,
+ });
+ const next = await claimProcessingAttempt({
+ videoId,
+ generation: expired.generation,
+ });
+ if (!next) throw new Error("Expired attempt was not recoverable");
+ expect(next.attemptId).not.toBe(expired.attemptId);
+ expect(await initializeSourceCommitCheckpoint(next)).toEqual(checkpoint);
+ });
+});
+
+describe("late verification and source commitment", () => {
+ it("retains bounded source-copy progress across retries and rejects stale checkpoint writes", async () => {
+ const first = await createAttempt(false);
+ const checkpoint = await initializeSourceCommitCheckpoint(first);
+ if (!checkpoint) throw new Error("Missing checkpoint");
+ const advanced = {
+ ...checkpoint,
+ revision: 1,
+ phase: "enumerate" as const,
+ };
+ expect(await persistSourceCommitCheckpoint(first, advanced)).toBe(true);
+ expect(await persistSourceCommitCheckpoint(first, advanced)).toBe(false);
+ await scheduleRetry({
+ ...first,
+ errorCode: "worker-lost",
+ errorMessage: "interrupted",
+ });
+ vi.setSystemTime(new Date(now.getTime() + 60_000));
+ const second = await claimProcessingAttempt({
+ videoId,
+ generation: first.generation,
+ });
+ if (!second) throw new Error("Missing replacement attempt");
+ expect(await initializeSourceCommitCheckpoint(second)).toEqual(advanced);
+ expect(
+ await persistSourceCommitCheckpoint(first, { ...advanced, revision: 2 }),
+ ).toBe(false);
+ expect(
+ await persistSourceCommitCheckpoint(second, { ...advanced, revision: 2 }),
+ ).toBe(true);
+ const late = await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification,
+ });
+ expect(late.job.generation).toBe(first.generation);
+ expect(await persistCommittedSource(second, source)).toBe(true);
+ expect(rows.jobs?.[0]).toMatchObject({
+ source,
+ verification,
+ output: null,
+ });
+ expect(
+ await persistSourceCommitCheckpoint(second, { ...advanced, revision: 3 }),
+ ).toBe(false);
+ });
+
+ it("starts a fresh uncommitted plan after missing or replaced source objects are repaired", async () => {
+ const first = await createAttempt(false);
+ const checkpoint = await initializeSourceCommitCheckpoint(first);
+ if (!checkpoint) throw new Error("Missing checkpoint");
+ await markSourceBlocked({
+ ...first,
+ errorCode: "source-changed",
+ errorMessage: "Original object was replaced",
+ });
+ const reopened = await ensureSegmentProcessingJob({ videoId, userId });
+ expect(reopened.job).toMatchObject({
+ generation: first.generation,
+ source: null,
+ output: null,
+ });
+ const second = await claimProcessingAttempt({
+ videoId,
+ generation: first.generation,
+ });
+ if (!second) throw new Error("Missing repaired-source attempt");
+ const replacement = await initializeSourceCommitCheckpoint(second);
+ expect(replacement?.snapshotId).not.toBe(checkpoint.snapshotId);
+ expect(
+ await persistSourceCommitCheckpoint(first, {
+ ...checkpoint,
+ revision: 1,
+ }),
+ ).toBe(false);
+ });
+
+ it("discards an obsolete checkpoint when a proof changes during a resumed source commit", async () => {
+ const attempt = await createAttempt(false);
+ await initializeSourceCommitCheckpoint(attempt);
+ await ensureSegmentProcessingJob({ videoId, userId, verification });
+ expect(
+ await persistCommittedSource(attempt, {
+ ...source,
+ manifestSha256: "e".repeat(64),
+ }),
+ ).toBe(false);
+ expect(rows.jobs?.[0]).toMatchObject({
+ source: null,
+ output: null,
+ state: "retry",
+ errorCode: "source-intent-changed",
+ });
+ });
+
+ it("attaches a matching proof arriving during a legacy snapshot to the same generation", async () => {
+ const attempt = await createAttempt(false);
+ const attached = await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification,
+ });
+ expect(attached.created).toBe(false);
+ expect(attached.job.generation).toBe(attempt.generation);
+ expect(attached.job.attemptId).toBe(attempt.attemptId);
+ expect(await persistCommittedSource(attempt, source)).toBe(true);
+ expect(rows.jobs?.[0]).toMatchObject({
+ generation: attempt.generation,
+ state: "processing",
+ source,
+ verification,
+ });
+ });
+
+ it("retries the snapshot instead of accepting a copy made before the completed intent changed", async () => {
+ const attempt = await createAttempt(false);
+ await ensureSegmentProcessingJob({ videoId, userId, verification });
+ expect(
+ await persistCommittedSource(attempt, {
+ ...source,
+ manifestSha256: "c".repeat(64),
+ }),
+ ).toBe(false);
+ expect(rows.jobs?.[0]).toMatchObject({
+ generation: attempt.generation,
+ source: null,
+ state: "retry",
+ errorCode: "source-intent-changed",
+ });
+ });
+
+ it("requires missing audio to be reconciled before committing a late strict segmented request", async () => {
+ const attempt = await createAttempt(false);
+ await ensureSegmentProcessingJob({ videoId, userId, verification });
+ expect(
+ await persistCommittedSource(attempt, {
+ ...source,
+ requiredAudio: false,
+ }),
+ ).toBe(false);
+ expect(rows.jobs?.[0]?.source).toBeNull();
+ });
+
+ it("adds the late strict MP4 duration to an identical already-copied source", async () => {
+ const video = rows.videos?.[0];
+ if (video) video.source = { type: "desktopMP4" };
+ const attempt = await createAttempt(false);
+ const request: RecordingVerification = {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: 1000,
+ duration: 91.6,
+ objectIdentity: '"original"',
+ },
+ requiredAudio: true,
+ };
+ await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification: request,
+ });
+ expect(
+ await persistCommittedSource(attempt, {
+ ...source,
+ kind: "mp4",
+ manifestSha256: undefined,
+ requiredAudio: false,
+ mp4: { fileSize: 1000, objectIdentity: '"original"' },
+ }),
+ ).toBe(true);
+ expect(rows.jobs?.[0]?.source).toMatchObject({
+ requiredAudio: true,
+ mp4: { fileSize: 1000, duration: 91.6, objectIdentity: '"original"' },
+ });
+ });
+
+ it("keeps stronger audio verification when an older client repeats a weaker request", async () => {
+ const attempt = await createAttempt();
+ await persistCommittedSource(attempt, source);
+ const weak = { ...verification, requiredAudio: false };
+ const result = await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification: weak,
+ });
+ expect(result.job.verification?.requiredAudio).toBe(true);
+ expect(result.job.generation).toBe(attempt.generation);
+ });
+
+ it("fences an old attempt when an authenticated completion identifies a new artifact", async () => {
+ const old = await createAttempt();
+ await persistCommittedSource(old, source);
+ const next = await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification: {
+ ...verification,
+ artifact: { kind: "segments", manifestSha256: "f".repeat(64) },
+ },
+ });
+ expect(next.job.generation).not.toBe(old.generation);
+ expect(await persistCommittedSource(old, source)).toBe(false);
+ expect(next.job.source).toBeNull();
+ });
+});
+
+describe("retained-source retry policy", () => {
+ it.each([null, source])(
+ "does not recreate a recording while deletion is pending",
+ async (retainedSource) => {
+ const attempt = await createAttempt();
+ const deleting = {
+ ...attempt,
+ generation: "deletion-generation",
+ state: "source-blocked" as const,
+ source: retainedSource,
+ leaseExpiresAt: null,
+ nextRetryAt: now,
+ errorCode: "video-deleting",
+ };
+ rows.jobs = [deleting];
+ expect(isDesktopRecordingJobRecoverable(deleting, now)).toBe(false);
+ expect(await heartbeatAttempt(attempt)).toBe(false);
+ await expect(
+ ensureSegmentProcessingJob({ videoId, userId, verification }),
+ ).rejects.toThrow("being deleted");
+ expect(rows.jobs?.[0]).toMatchObject({
+ generation: "deletion-generation",
+ source: retainedSource,
+ errorCode: "video-deleting",
+ });
+ },
+ );
+
+ it("fences old workers and automatic retries after an intentional edit while retaining the source", async () => {
+ const attempt = await createAttempt();
+ await persistCommittedSource(attempt, source);
+ await mocks
+ .db()
+ .transaction(
+ (
+ tx: Parameters<
+ typeof retireDesktopRecordingJobForOutputReplacement
+ >[0],
+ ) =>
+ retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId,
+ userId,
+ }),
+ );
+ expect(rows.jobs?.[0]).toMatchObject({
+ source,
+ state: "source-blocked",
+ errorCode: "output-replaced",
+ attemptId: null,
+ });
+ expect(rows.jobs?.[0]?.generation).not.toBe(attempt.generation);
+ expect(await heartbeatAttempt(attempt)).toBe(false);
+ await expect(
+ ensureSegmentProcessingJob({ videoId, userId, verification }),
+ ).rejects.toThrow("intentionally edited or replaced");
+ });
+
+ it("keeps a replacement tombstone even when the original predated durable jobs", async () => {
+ await mocks
+ .db()
+ .transaction(
+ (
+ tx: Parameters<
+ typeof retireDesktopRecordingJobForOutputReplacement
+ >[0],
+ ) =>
+ retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId,
+ userId,
+ }),
+ );
+ expect(rows.jobs?.[0]).toMatchObject({
+ source: null,
+ errorCode: "output-replaced",
+ });
+ await expect(
+ ensureSegmentProcessingJob({ videoId, userId }),
+ ).rejects.toThrow("intentionally edited or replaced");
+ });
+ it("keeps worker failures processing without exposing reupload-required errors", async () => {
+ const attempt = await createAttempt();
+ await persistCommittedSource(attempt, source);
+ expect(
+ await scheduleRetry({
+ ...attempt,
+ errorCode: "worker-lost",
+ errorMessage: "worker restarted",
+ }),
+ ).toBe(true);
+ expect(rows.jobs?.[0]).toMatchObject({
+ state: "retry",
+ source,
+ errorCode: "worker-lost",
+ });
+ expect(rows.uploads?.[0]).toMatchObject({
+ phase: "processing",
+ processingError: null,
+ });
+ });
+
+ it("recovers old jobs regardless of recording age or previous attempt count", async () => {
+ const attempt = await createAttempt();
+ const job: DesktopRecordingJob = {
+ ...attempt,
+ state: "retry",
+ source,
+ leaseExpiresAt: null,
+ attemptCount: 500,
+ createdAt: new Date("2020-01-01T00:00:00Z"),
+ nextRetryAt: now,
+ };
+ expect(isDesktopRecordingJobRecoverable(job, now)).toBe(true);
+ expect(
+ isDesktopRecordingJobRecoverable({ ...job, state: "verified" }, now),
+ ).toBe(false);
+ expect(
+ isDesktopRecordingJobRecoverable(
+ { ...job, state: "source-blocked" },
+ now,
+ ),
+ ).toBe(false);
+ expect(
+ isDesktopRecordingJobRecoverable(
+ { ...job, state: "source-blocked", source: null },
+ now,
+ ),
+ ).toBe(true);
+ });
+
+ it("caps retry backoff without overflowing after many worker restarts", () => {
+ expect(getDesktopRecordingRetryDelay(1)).toBe(15_000);
+ expect(getDesktopRecordingRetryDelay(100_000)).toBe(3_600_000);
+ });
+
+ it("does not let a different generation attach a processing job", async () => {
+ const attempt = await createAttempt();
+ const fence: DesktopRecordingAttemptFence = {
+ ...attempt,
+ generation: "other",
+ };
+ expect(await attachRemoteJob({ ...fence, remoteJobId: "remote" })).toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
new file mode 100644
index 000000000..c15c16203
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
@@ -0,0 +1,328 @@
+import type { VideoEditSpec } from "@cap/database/types";
+import { Effect, Option } from "effect";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ db: vi.fn(),
+ access: vi.fn(),
+ head: vi.fn(),
+ post: vi.fn(),
+ retire: vi.fn(),
+ env: vi.fn(),
+ fetch: vi.fn(),
+ cloudfront: vi.fn(),
+ auth: vi.fn(),
+}));
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/database/auth/session", () => ({ getCurrentUser: mocks.auth }));
+vi.mock("@cap/database/schema", () => ({
+ videos: { table: "videos", id: "id" },
+ videoUploads: {
+ table: "uploads",
+ videoId: "videoId",
+ phase: "phase",
+ rawFileKey: "rawFileKey",
+ },
+ videoEdits: { table: "edits" },
+ comments: { table: "comments" },
+}));
+vi.mock("drizzle-orm", () => ({ and: vi.fn(), eq: vi.fn() }));
+vi.mock("@cap/env", () => ({ serverEnv: mocks.env }));
+vi.mock("@cap/web-backend", () => ({
+ Storage: { getAccessForVideo: mocks.access },
+ AwsCredentials: {},
+}));
+vi.mock("@cap/web-backend/src/Storage/index", () => ({
+ Storage: { getAccessForVideo: mocks.access },
+}));
+vi.mock("@cap/web-backend/src/Aws", () => ({ AwsCredentials: {} }));
+vi.mock("workflow", () => ({
+ FatalError: class FatalError extends Error {},
+ sleep: vi.fn(),
+}));
+vi.mock("@aws-sdk/client-cloudfront", () => ({
+ CloudFrontClient: class {
+ send = mocks.cloudfront;
+ },
+ CreateInvalidationCommand: class {
+ constructor(readonly input: unknown) {}
+ },
+}));
+vi.mock("@/lib/desktop-recording-jobs", () => ({
+ retireDesktopRecordingJobForOutputReplacement: mocks.retire,
+}));
+vi.mock("@/lib/messenger/constants", () => ({
+ MESSENGER_ADMIN_EMAIL: "[email protected]",
+}));
+vi.mock("@/lib/server", async () => ({
+ runPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/workflow-runtime", async () => ({
+ runWorkflowPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: (video: unknown) => video,
+}));
+vi.mock("@/lib/edit-transcript-storage", () => ({
+ decryptEditTranscriptObject: () => null,
+}));
+vi.mock("@/lib/generate-ai", () => ({ startAiGeneration: vi.fn() }));
+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: vi.fn() }));
+
+import {
+ getVideoReplaceUploadUrl,
+ invalidateVideoCache,
+} from "@/actions/admin/replace-video";
+import { saveMetadataAndComplete } from "@/workflows/admin-reprocess-video";
+import {
+ saveEditResultAndComplete,
+ verifyRenderedEditOutput,
+} from "@/workflows/edit-video";
+
+let video: {
+ id: string;
+ ownerId: string;
+ bucket: string | null;
+ storageIntegrationId: string | null;
+ source: {
+ type: string;
+ outputKey?: string;
+ thumbnailKey?: string;
+ previewKey?: string;
+ };
+ metadata: Record<string, unknown>;
+};
+let events: string[];
+let updates: Record<string, unknown>[];
+const metadata = { duration: 5, width: 320, height: 180, fps: 30 };
+const editSpec: VideoEditSpec = {
+ version: 1,
+ sourceDuration: 10,
+ keepRanges: [{ start: 0, end: 5 }],
+};
+
+function createClient() {
+ const client = {
+ select() {
+ return {
+ from: (table: { table: string }) => ({
+ where: () => {
+ const rows = table.table === "comments" ? [] : [video];
+ return Object.assign(Promise.resolve(rows), {
+ for: async () => {
+ events.push("lock-video");
+ return rows;
+ },
+ });
+ },
+ }),
+ };
+ },
+ update(table: { table: string }) {
+ return {
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ events.push(`update-${table.table}`);
+ if (table.table === "videos") {
+ updates.push(values);
+ Object.assign(video, values);
+ }
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ };
+ },
+ insert() {
+ return {
+ values: () => ({
+ onDuplicateKeyUpdate: async () => [{ affectedRows: 1 }],
+ }),
+ };
+ },
+ delete(table: { table: string }) {
+ return {
+ where: async () => {
+ events.push(`delete-${table.table}`);
+ return [{ affectedRows: 1 }];
+ },
+ };
+ },
+ };
+ return {
+ ...client,
+ transaction: async (callback: (tx: typeof client) => Promise<unknown>) => {
+ events.push("transaction");
+ return callback(client);
+ },
+ };
+}
+
+beforeEach(() => {
+ video = {
+ id: "video",
+ ownerId: "user",
+ bucket: null,
+ storageIntegrationId: null,
+ source: {
+ type: "desktopMP4",
+ outputKey: "user/video/.recording/outputs/generation/attempt.mp4",
+ thumbnailKey: "old-thumbnail",
+ previewKey: "old-preview",
+ },
+ metadata: {
+ desktopRecordingUpload: { fullDecode: true },
+ customCreatedAt: "2020-01-01T00:00:00Z",
+ summary: "old summary",
+ },
+ };
+ events = [];
+ updates = [];
+ mocks.db.mockReturnValue(createClient());
+ mocks.head.mockImplementation(() => {
+ events.push("head-canonical");
+ return Effect.succeed({ ETag: '"new-output"', ContentLength: 1000 });
+ });
+ mocks.post.mockReturnValue(
+ Effect.succeed({
+ url: "https://storage.test/upload",
+ fields: { key: "user/video/result.mp4" },
+ }),
+ );
+ mocks.access.mockImplementation(
+ (_video, options?: { resolvePublishedOutput?: boolean }) =>
+ Effect.succeed([
+ {
+ headObject: mocks.head,
+ getPresignedPostUrl: mocks.post,
+ getInternalSignedObjectUrl: (key: string) =>
+ Effect.succeed(
+ `https://storage.test/${options?.resolvePublishedOutput === false ? "canonical" : "published"}/${key}`,
+ ),
+ getObject: () => Effect.succeed(Option.none()),
+ listObjects: () => Effect.succeed({ Contents: [] }),
+ },
+ ]),
+ );
+ mocks.retire.mockImplementation(async () => {
+ events.push("retire-job");
+ });
+ mocks.env.mockReturnValue({
+ MEDIA_SERVER_URL: "https://media.test",
+ MEDIA_SERVER_WEBHOOK_SECRET: "secret",
+ WEB_URL: "https://cap.test",
+ });
+ mocks.auth.mockResolvedValue({ id: "admin", email: "[email protected]" });
+ mocks.fetch.mockResolvedValue(Response.json({ metadata }));
+ vi.stubGlobal("fetch", mocks.fetch);
+});
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("edited recording publication", () => {
+ it("verifies the newly rendered canonical output instead of the old published immutable recording", async () => {
+ await verifyRenderedEditOutput("video", "user", editSpec, metadata);
+ expect(mocks.access).toHaveBeenCalledWith(video, {
+ resolvePublishedOutput: false,
+ });
+ expect(mocks.fetch).toHaveBeenCalledWith(
+ "https://media.test/video/probe",
+ expect.objectContaining({
+ body: JSON.stringify({
+ videoUrl: "https://storage.test/canonical/user/video/result.mp4",
+ }),
+ }),
+ );
+ });
+
+ it("switches a completed edit to canonical output and retires old upload proof atomically", async () => {
+ await saveEditResultAndComplete(
+ "video",
+ "user/video/edit-original.mp4",
+ editSpec,
+ editSpec,
+ metadata,
+ );
+ expect(video.source).toEqual({ type: "desktopMP4" });
+ expect(video.metadata).not.toHaveProperty("desktopRecordingUpload");
+ expect(video.metadata.customCreatedAt).toBe("2020-01-01T00:00:00Z");
+ expect(events.indexOf("retire-job")).toBeLessThan(
+ events.indexOf("lock-video"),
+ );
+ expect(events.indexOf("lock-video")).toBeLessThan(
+ events.indexOf("update-videos"),
+ );
+ });
+
+ it("checks a reprocessed canonical object before clearing its previous immutable publication", async () => {
+ await saveMetadataAndComplete("video", metadata);
+ expect(mocks.access).toHaveBeenCalledWith(expect.any(Object), {
+ resolvePublishedOutput: false,
+ });
+ expect(events.indexOf("head-canonical")).toBeLessThan(
+ events.indexOf("retire-job"),
+ );
+ expect(video.source).toEqual({ type: "desktopMP4" });
+ expect(video.metadata).not.toHaveProperty("desktopRecordingUpload");
+ });
+
+ it("retains the published recording when reprocessing did not produce a usable object", async () => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({ ETag: '"empty"', ContentLength: 0 }),
+ );
+ await expect(saveMetadataAndComplete("video", metadata)).rejects.toThrow(
+ "missing or empty",
+ );
+ expect(updates).toEqual([]);
+ expect(mocks.retire).not.toHaveBeenCalled();
+ expect(video.source.outputKey).toBeDefined();
+ });
+});
+
+describe("intentional administrator replacements", () => {
+ it("publishes the replacement even when CloudFront is not configured", async () => {
+ await invalidateVideoCache("video");
+ expect(video.source).toEqual({ type: "desktopMP4" });
+ expect(video.metadata).not.toHaveProperty("desktopRecordingUpload");
+ expect(events).toContain("delete-uploads");
+ expect(mocks.cloudfront).not.toHaveBeenCalled();
+ });
+
+ it("publishes replacements in custom storage before the cache bypass return", async () => {
+ video.bucket = "custom-bucket";
+ mocks.env.mockReturnValue({
+ CAP_CLOUDFRONT_DISTRIBUTION_ID: "distribution",
+ });
+ await invalidateVideoCache("video");
+ expect(video.source).toEqual({ type: "desktopMP4" });
+ expect(mocks.retire).toHaveBeenCalledOnce();
+ expect(mocks.cloudfront).not.toHaveBeenCalled();
+ });
+
+ it("leaves the published recording and receipt untouched if the replacement has not uploaded", async () => {
+ mocks.head.mockReturnValue(Effect.succeed({ ContentLength: 0 }));
+ await expect(invalidateVideoCache("video")).rejects.toThrow(
+ "not finished uploading",
+ );
+ expect(updates).toEqual([]);
+ expect(mocks.retire).not.toHaveBeenCalled();
+ expect(video.metadata).toHaveProperty("desktopRecordingUpload");
+ });
+
+ it("moves an explicitly replaced segmented recording to its real MP4 output", async () => {
+ video.source = { type: "desktopSegments" };
+ await invalidateVideoCache("video");
+ expect(video.source).toEqual({ type: "desktopMP4" });
+ });
+
+ it("prepares replacement writes against the recording storage without retiring the current publication early", async () => {
+ await getVideoReplaceUploadUrl("video");
+ expect(mocks.access).toHaveBeenCalledWith(video, {
+ resolvePublishedOutput: false,
+ });
+ expect(mocks.post).toHaveBeenCalledWith(
+ "user/video/result.mp4",
+ expect.any(Object),
+ );
+ expect(mocks.retire).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-recording-publication.test.ts b/apps/web/__tests__/unit/desktop-recording-publication.test.ts
new file mode 100644
index 000000000..9251789e4
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-recording-publication.test.ts
@@ -0,0 +1,664 @@
+import { Effect } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DesktopRecordingJob } from "@/lib/desktop-recording-jobs";
+
+const mocks = vi.hoisted(() => ({
+ db: vi.fn(),
+ getState: vi.fn(),
+ retry: vi.fn(),
+ blocked: vi.fn(),
+ head: vi.fn(),
+ storage: vi.fn(),
+ invalidateQuota: vi.fn(),
+ tables: {
+ videos: {
+ id: "videos.id",
+ ownerId: "videos.ownerId",
+ metadata: "videos.metadata",
+ },
+ jobs: { videoId: "jobs.videoId" },
+ uploads: { videoId: "uploads.videoId", rawFileKey: "uploads.rawFileKey" },
+ },
+}));
+
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/database/schema", () => ({
+ videos: mocks.tables.videos,
+ videoProcessingJobs: mocks.tables.jobs,
+ videoUploads: mocks.tables.uploads,
+}));
+vi.mock("@cap/web-backend", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@cap/web-backend/src/Storage/index", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@/lib/desktop-recording-jobs", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@/lib/desktop-recording-jobs")>();
+ return {
+ ...actual,
+ getProcessingState: mocks.getState,
+ scheduleRetry: mocks.retry,
+ markSourceBlocked: mocks.blocked,
+ };
+});
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ return { runPromise: Effect.runPromise };
+});
+vi.mock("@/lib/workflow-runtime", async () => {
+ const { Effect } = await import("effect");
+ return { runWorkflowPromise: Effect.runPromise };
+});
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: (video: unknown) => video,
+}));
+vi.mock("@/lib/google-drive-storage-quota-cache", () => ({
+ invalidateGoogleDriveStorageQuotaCache: mocks.invalidateQuota,
+}));
+
+import { parseDesktopRecordingJob } from "@/lib/desktop-recording-jobs";
+import {
+ applyDesktopRecordingProgress,
+ isCurrentDesktopRecordingAttempt,
+ validateDesktopRecordingCompletion,
+} from "@/lib/desktop-recording-publication";
+import { getDesktopRecordingOutputKey } from "@/lib/desktop-recording-source";
+
+type StoredJob = Parameters<typeof parseDesktopRecordingJob>[0];
+type Mutation = {
+ operation: "update" | "delete";
+ table: unknown;
+ values?: Record<string, unknown>;
+};
+
+const generation = "c9699f1a-fe24-44f9-ac89-63d5744a058c";
+const attemptId = "cf9f55f8-4d6d-44b4-a670-30c2f7e51d9b";
+const snapshotId = "5ec501d7-7a24-4efb-95ea-b3537350d870";
+const manifestSha256 = "a".repeat(64);
+const inventorySha256 = "b".repeat(64);
+const outputSha256 = "c".repeat(64);
+const ownerId = "owned-user" as DesktopRecordingJob["ownerId"];
+const videoId = "owned-video" as DesktopRecordingJob["videoId"];
+const outputKey = getDesktopRecordingOutputKey(
+ ownerId,
+ videoId,
+ generation,
+ attemptId,
+);
+const metadata = {
+ fileSize: 4096,
+ duration: 5,
+ width: 320,
+ height: 180,
+ fps: 30,
+ videoCodec: "h264",
+ audioCodec: "aac",
+};
+
+function segmentedFixture() {
+ const source = {
+ version: 1 as const,
+ kind: "segments" as const,
+ manifestSha256,
+ inventorySha256,
+ inventoryKey: `${ownerId}/${videoId}/.recording/sources/${generation}/${snapshotId}/inventory.json`,
+ requiredAudio: true,
+ };
+ const verification = {
+ version: 1 as const,
+ artifact: { kind: "segments" as const, manifestSha256 },
+ requiredAudio: true,
+ };
+ const now = new Date();
+ const job: DesktopRecordingJob = {
+ videoId,
+ ownerId,
+ generation,
+ manifestSha256,
+ state: "processing",
+ attemptId,
+ attemptCount: 1,
+ leaseExpiresAt: new Date(now.getTime() + 60_000),
+ nextRetryAt: now,
+ workflowRunId: "workflow-1",
+ remoteJobId: "remote-1",
+ source,
+ verification,
+ output: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const payload = {
+ jobId: "remote-1",
+ videoId,
+ generation,
+ attemptId,
+ phase: "complete" as const,
+ progress: 100,
+ metadata: { ...metadata },
+ recordingVerification: {
+ request: verification,
+ fullDecode: true as const,
+ objectIdentity: '"verified-output"',
+ outputKey,
+ outputSha256,
+ sourceProof: {
+ version: 1 as const,
+ manifestSha256,
+ inventorySha256,
+ sourcePreserved: true as const,
+ videoDuration: metadata.duration,
+ hasAudio: true,
+ audioVerified: true,
+ },
+ },
+ };
+ return { job, payload, source, verification };
+}
+
+function mp4Fixture(requiredAudio = false) {
+ const base = segmentedFixture();
+ const source = {
+ version: 1 as const,
+ kind: "mp4" as const,
+ inventorySha256,
+ inventoryKey: base.source.inventoryKey,
+ requiredAudio,
+ mp4: {
+ fileSize: metadata.fileSize,
+ duration: metadata.duration,
+ objectIdentity: '"original-upload"',
+ },
+ };
+ const verification = {
+ version: 1 as const,
+ artifact: { kind: "mp4" as const, ...source.mp4 },
+ requiredAudio,
+ };
+ const job: DesktopRecordingJob = {
+ ...base.job,
+ manifestSha256: null,
+ source,
+ verification,
+ };
+ const payload = {
+ ...base.payload,
+ recordingVerification: {
+ request: verification,
+ fullDecode: true as const,
+ objectIdentity: '"copied-mp4"',
+ outputKey: source.inventoryKey.replace("inventory.json", "mp4/0.mp4"),
+ outputSha256,
+ },
+ };
+ return { job, payload, source, verification };
+}
+
+function databaseFixture(initial: DesktopRecordingJob) {
+ let current: StoredJob | null = structuredClone(initial);
+ let video: Record<string, unknown> | null = {
+ id: videoId,
+ ownerId,
+ source: {
+ type: initial.source?.kind === "mp4" ? "desktopMP4" : "desktopSegments",
+ },
+ metadata: {},
+ storageIntegrationId: null,
+ };
+ let beforeTransaction: (() => void) | undefined;
+ const mutations: Mutation[] = [];
+ const rows = (table: unknown) => {
+ if (table === mocks.tables.jobs)
+ return current ? [structuredClone(current)] : [];
+ if (table === mocks.tables.videos)
+ return video ? [structuredClone(video)] : [];
+ if (table === mocks.tables.uploads) return [{ rawFileKey: null }];
+ throw new Error("Unexpected table");
+ };
+ const transaction = vi.fn(
+ async (
+ operation: (tx: ReturnType<typeof transactionHandle>) => Promise<unknown>,
+ ) => {
+ beforeTransaction?.();
+ const pending: Mutation[] = [];
+ const result = await operation(transactionHandle(pending));
+ for (const mutation of pending) {
+ mutations.push(mutation);
+ if (mutation.operation !== "update") continue;
+ if (mutation.table === mocks.tables.jobs && current) {
+ Object.assign(current, mutation.values);
+ } else if (mutation.table === mocks.tables.videos && video) {
+ Object.assign(video, mutation.values);
+ }
+ }
+ return result;
+ },
+ );
+ function transactionHandle(pending: Mutation[]) {
+ return {
+ select: () => ({
+ from: (table: unknown) => ({
+ where: () => ({ for: async () => rows(table) }),
+ }),
+ }),
+ update: (table: unknown) => ({
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ pending.push({ operation: "update", table, values });
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ }),
+ delete: (table: unknown) => ({
+ where: async () => {
+ pending.push({ operation: "delete", table });
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ };
+ }
+ mocks.db.mockReturnValue({
+ select: () => ({
+ from: (table: unknown) => ({ where: async () => rows(table) }),
+ }),
+ transaction,
+ });
+ mocks.getState.mockImplementation(
+ async () => current && parseDesktopRecordingJob(structuredClone(current)),
+ );
+ return {
+ mutations,
+ transaction,
+ setCurrent: (next: StoredJob | null) => {
+ current = next;
+ },
+ getVideo: () => video,
+ setVideo: (next: Record<string, unknown> | null) => {
+ video = next;
+ },
+ beforeTransaction: (callback: () => void) => {
+ beforeTransaction = callback;
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.storage.mockReturnValue(Effect.succeed([{ headObject: mocks.head }]));
+ mocks.head.mockImplementation((key: string) =>
+ key.endsWith(".mp4")
+ ? Effect.succeed({
+ ContentLength: metadata.fileSize,
+ ETag: '"verified-output"',
+ })
+ : Effect.fail(new Error("Asset absent")),
+ );
+ mocks.invalidateQuota.mockResolvedValue(undefined);
+ mocks.retry.mockResolvedValue(true);
+ mocks.blocked.mockResolvedValue(true);
+});
+
+describe("recording publication attempt fence", () => {
+ it("accepts only the current live processing attempt", () => {
+ const { job, payload } = segmentedFixture();
+ const now = new Date();
+ expect(isCurrentDesktopRecordingAttempt(job, payload, now)).toBe(true);
+ for (const change of [
+ { generation: "old-generation" },
+ { attemptId: "old-attempt" },
+ { remoteJobId: "different-worker" },
+ { state: "verified" as const },
+ { state: "retry" as const },
+ { leaseExpiresAt: null },
+ { leaseExpiresAt: now },
+ { leaseExpiresAt: new Date(now.getTime() - 1) },
+ ]) {
+ expect(
+ isCurrentDesktopRecordingAttempt({ ...job, ...change }, payload, now),
+ ).toBe(false);
+ }
+ });
+
+ it("allows a matching attempt callback before the remote job id is persisted", () => {
+ const { job, payload } = segmentedFixture();
+ expect(
+ isCurrentDesktopRecordingAttempt({ ...job, remoteJobId: null }, payload),
+ ).toBe(true);
+ });
+
+ it.each(["generation", "attempt", "remote", "expired", "verified"])(
+ "does not inspect or mutate output for a %s stale completion",
+ async (reason) => {
+ const { job, payload } = segmentedFixture();
+ if (reason === "generation") job.generation = "new-generation";
+ else if (reason === "attempt") job.attemptId = "new-attempt";
+ else if (reason === "remote") job.remoteJobId = "new-worker";
+ else if (reason === "expired")
+ job.leaseExpiresAt = new Date(Date.now() - 1);
+ else job.state = "verified";
+ const database = databaseFixture(job);
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 200,
+ });
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(database.mutations).toEqual([]);
+ expect(database.transaction).not.toHaveBeenCalled();
+ },
+ );
+});
+
+describe("recording completion source binding", () => {
+ it("binds the exact committed manifest, inventory and attempt output", () => {
+ const { job, payload } = segmentedFixture();
+ const result = validateDesktopRecordingCompletion(job, payload);
+ expect(result.request).toEqual(job.verification);
+ expect(result.options).toEqual({
+ outputKey,
+ outputSha256,
+ sourceProof: payload.recordingVerification.sourceProof,
+ });
+ });
+
+ it.each(["manifest", "inventory", "output-key", "audio"])(
+ "refuses mismatched segmented %s evidence",
+ (reason) => {
+ const { job, payload } = segmentedFixture();
+ if (reason === "manifest")
+ payload.recordingVerification.sourceProof.manifestSha256 = "d".repeat(
+ 64,
+ );
+ else if (reason === "inventory")
+ payload.recordingVerification.sourceProof.inventorySha256 = "d".repeat(
+ 64,
+ );
+ else if (reason === "output-key")
+ payload.recordingVerification.outputKey = `${ownerId}/${videoId}/result.mp4`;
+ else payload.recordingVerification.sourceProof.audioVerified = false;
+ expect(() => validateDesktopRecordingCompletion(job, payload)).toThrow();
+ },
+ );
+
+ it("refuses a different requested artifact even if the output proof is internally consistent", () => {
+ const { job, payload } = segmentedFixture();
+ job.verification = {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256: "d".repeat(64) },
+ requiredAudio: true,
+ };
+ expect(() => validateDesktopRecordingCompletion(job, payload)).toThrow();
+ });
+
+ it("binds an MP4 snapshot to the original identity despite a different copied ETag", () => {
+ const { job, payload, source } = mp4Fixture();
+ const result = validateDesktopRecordingCompletion(job, payload);
+ expect(result.options.sourceObjectIdentity).toBe(source.mp4.objectIdentity);
+ expect(result.options.outputKey).toBe(
+ payload.recordingVerification.outputKey,
+ );
+ expect(result.proof.objectIdentity).not.toBe(source.mp4.objectIdentity);
+ });
+
+ it("does not upgrade an optional-audio MP4 worker proof after a stronger request arrives", () => {
+ const { job, payload, verification } = mp4Fixture(false);
+ job.verification = { ...verification, requiredAudio: true };
+ expect(payload.metadata.audioCodec).toBe("aac");
+ expect(() => validateDesktopRecordingCompletion(job, payload)).toThrow();
+ });
+
+ it.each(["identity", "size", "duration", "key"])(
+ "rejects MP4 %s substitutions",
+ (reason) => {
+ const { job, payload, source } = mp4Fixture();
+ if (reason === "identity") source.mp4.objectIdentity = '"other-original"';
+ else if (reason === "size") source.mp4.fileSize += 1;
+ else if (reason === "duration") source.mp4.duration += 1;
+ else payload.recordingVerification.outputKey = outputKey;
+ expect(() => validateDesktopRecordingCompletion(job, payload)).toThrow();
+ },
+ );
+
+ it.each([
+ "byte-hash",
+ "full-decode",
+ "source-preservation",
+ "object-identity",
+ ])(
+ "refuses malformed %s evidence before any publication writes",
+ async (reason) => {
+ const { job, payload } = segmentedFixture();
+ const database = databaseFixture(job);
+ const proof = {
+ ...payload.recordingVerification,
+ ...(reason === "byte-hash" ? { outputSha256: "not-a-sha256" } : {}),
+ ...(reason === "full-decode" ? { fullDecode: false } : {}),
+ ...(reason === "source-preservation"
+ ? {
+ sourceProof: {
+ ...payload.recordingVerification.sourceProof,
+ sourcePreserved: false,
+ },
+ }
+ : {}),
+ ...(reason === "object-identity" ? { objectIdentity: 'W/"weak"' } : {}),
+ };
+ expect(
+ await applyDesktopRecordingProgress({
+ ...payload,
+ recordingVerification: proof,
+ }),
+ ).toEqual({ handled: true, status: 400 });
+ expect(database.mutations).toEqual([]);
+ expect(mocks.head).not.toHaveBeenCalled();
+ },
+ );
+});
+
+describe("atomic publication revalidation", () => {
+ it("publishes verified metadata, saves the matching receipt, and ignores duplicate completion", async () => {
+ const { job, payload } = segmentedFixture();
+ const database = databaseFixture(job);
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 200,
+ published: true,
+ });
+ expect(
+ database.mutations.find(
+ (mutation) => mutation.table === mocks.tables.videos,
+ )?.values,
+ ).toMatchObject({
+ source: { type: "desktopMP4", outputKey },
+ duration: metadata.duration,
+ });
+ expect(
+ database.mutations.find(
+ (mutation) => mutation.table === mocks.tables.jobs,
+ )?.values,
+ ).toMatchObject({
+ state: "verified",
+ leaseExpiresAt: null,
+ output: {
+ outputKey,
+ outputSha256,
+ sourceProof: payload.recordingVerification.sourceProof,
+ },
+ });
+ expect(
+ database.mutations.filter((mutation) => mutation.operation === "delete"),
+ ).toEqual([{ operation: "delete", table: mocks.tables.uploads }]);
+ const count = database.mutations.length;
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 200,
+ });
+ expect(database.mutations).toHaveLength(count);
+ });
+
+ it("publishes a verified MP4 copy without substituting its original upload identity", async () => {
+ const { job, payload, source } = mp4Fixture(true);
+ const database = databaseFixture(job);
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: metadata.fileSize,
+ ETag: '"copied-mp4"',
+ }),
+ );
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 200,
+ published: true,
+ });
+ expect(
+ database.mutations.find(
+ (mutation) => mutation.table === mocks.tables.jobs,
+ )?.values,
+ ).toMatchObject({
+ state: "verified",
+ output: {
+ artifact: payload.recordingVerification.request.artifact,
+ objectIdentity: '"copied-mp4"',
+ sourceObjectIdentity: source.mp4.objectIdentity,
+ requiredAudioVerified: true,
+ },
+ });
+ });
+
+ it("accepts semantically unchanged persisted JSON regardless of key order", async () => {
+ const { job, payload, source, verification } = segmentedFixture();
+ const database = databaseFixture(job);
+ database.beforeTransaction(() =>
+ database.setCurrent({
+ ...job,
+ source: Object.fromEntries(Object.entries(source).reverse()),
+ verification: {
+ requiredAudio: verification.requiredAudio,
+ artifact: { manifestSha256, kind: "segments" },
+ version: 1,
+ },
+ }),
+ );
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 200,
+ published: true,
+ });
+ });
+
+ it.each([
+ "generation",
+ "attempt",
+ "lease",
+ "source",
+ "verification",
+ "worker",
+ ])(
+ "does not publish after %s changes during output verification",
+ async (reason) => {
+ const { job, payload, source, verification } = segmentedFixture();
+ const database = databaseFixture(job);
+ database.beforeTransaction(() => {
+ const current = { ...job };
+ if (reason === "generation") current.generation = "new-generation";
+ else if (reason === "attempt") current.attemptId = "new-attempt";
+ else if (reason === "lease")
+ current.leaseExpiresAt = new Date(Date.now() - 1);
+ else if (reason === "source")
+ current.source = { ...source, inventorySha256: "d".repeat(64) };
+ else if (reason === "verification")
+ current.verification = { ...verification, requiredAudio: false };
+ else current.remoteJobId = "new-worker";
+ database.setCurrent(current);
+ });
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 503,
+ });
+ expect(database.mutations).toEqual([]);
+ },
+ );
+
+ it("does not publish a weak MP4 receipt after audio requirements strengthen during its HEAD check", async () => {
+ const { job, payload, verification } = mp4Fixture(false);
+ const database = databaseFixture(job);
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: metadata.fileSize,
+ ETag: '"copied-mp4"',
+ }),
+ );
+ database.beforeTransaction(() =>
+ database.setCurrent({
+ ...job,
+ verification: { ...verification, requiredAudio: true },
+ }),
+ );
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 503,
+ });
+ expect(database.mutations).toEqual([]);
+ });
+
+ it.each(["deleted", "owner", "source", "bucket", "storage-integration"])(
+ "does not publish when the video is concurrently changed: %s",
+ async (reason) => {
+ const { job, payload } = segmentedFixture();
+ const database = databaseFixture(job);
+ database.beforeTransaction(() => {
+ if (reason === "deleted") {
+ database.setVideo(null);
+ return;
+ }
+ const current = { ...database.getVideo() };
+ if (reason === "owner") current.ownerId = "different-owner";
+ else if (reason === "source")
+ current.source = { type: "desktopMP4", outputKey: "new-upload" };
+ else if (reason === "bucket") current.bucket = "different-bucket";
+ else current.storageIntegrationId = "different-integration";
+ database.setVideo(current);
+ });
+ expect(await applyDesktopRecordingProgress(payload)).toEqual({
+ handled: true,
+ status: 503,
+ });
+ expect(database.mutations).toEqual([]);
+ },
+ );
+
+ it("does not let an unfenced legacy completion overwrite a managed recording", async () => {
+ const { job, payload } = segmentedFixture();
+ const database = databaseFixture(job);
+ expect(
+ await applyDesktopRecordingProgress({
+ videoId,
+ jobId: "old-worker",
+ phase: "complete",
+ progress: 100,
+ metadata,
+ recordingVerification: payload.recordingVerification,
+ }),
+ ).toEqual({ handled: true, status: 200 });
+ expect(database.mutations).toEqual([]);
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+
+ it("does not publish after the verified output object was replaced", async () => {
+ const { job, payload } = segmentedFixture();
+ const database = databaseFixture(job);
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: metadata.fileSize,
+ ETag: '"replaced-output"',
+ }),
+ );
+ await expect(applyDesktopRecordingProgress(payload)).rejects.toThrow(
+ "changed",
+ );
+ expect(database.mutations).toEqual([]);
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-recording-source.test.ts b/apps/web/__tests__/unit/desktop-recording-source.test.ts
new file mode 100644
index 000000000..e124b08e7
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-recording-source.test.ts
@@ -0,0 +1,1371 @@
+import { createHash } from "node:crypto";
+import { GoogleDriveRequestError } from "@cap/web-backend/src/Storage/GoogleDrive";
+import { Storage as StorageDomain } from "@cap/web-domain";
+import { Effect, Option } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { z } from "zod";
+import type { DesktopRecordingSourceCheckpoint } from "@/lib/desktop-recording-source-checkpoint";
+import type { RecordingVerification } from "@/lib/desktop-recording-verification";
+
+const mocks = vi.hoisted(() => ({ storage: vi.fn() }));
+
+vi.mock("@cap/web-backend/src/Storage/index", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@/lib/workflow-runtime", async () => {
+ const { Effect } = await import("effect");
+ return { runWorkflowPromise: Effect.runPromise };
+});
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: (video: unknown) => video,
+}));
+
+import {
+ advanceDesktopRecordingSourceCommit,
+ buildDesktopRecordingSourceUrls,
+ commitDesktopRecordingSource,
+ DesktopRecordingSourceError,
+ getDesktopRecordingOutputKey,
+} from "@/lib/desktop-recording-source";
+
+type VideoRow = Parameters<typeof commitDesktopRecordingSource>[0];
+type StoredObject = {
+ identity: string;
+ size: number;
+ body?: string;
+ metadata?: Record<string, string>;
+};
+type CopyOptions = {
+ CopySourceIfMatch?: string;
+ IfNoneMatch?: string;
+ Metadata?: Record<string, string>;
+};
+type CopyPartOptions = CopyOptions & {
+ CopySource: string;
+ CopySourceRange: string;
+};
+type CopiedPart = {
+ number: number;
+ start: number;
+ end: number;
+ identity: string;
+ sourceKey: string;
+};
+
+const prefix = "owned-user/owned-video";
+const manifestKey = `${prefix}/segments/manifest.json`;
+const videoInitKey = `${prefix}/segments/video/init.mp4`;
+const audioInitKey = `${prefix}/segments/audio/init.mp4`;
+const generation = "a4241ba5-b520-483f-ad97-b8e5ce0950e3";
+const attempt = "4d7653bb-9cdd-47e2-be3b-d1df01838f79";
+const inventorySchema = z
+ .object({
+ objects: z.array(
+ z
+ .object({
+ key: z.string(),
+ originalKey: z.string(),
+ originalIdentity: z.string(),
+ objectIdentity: z.string(),
+ size: z.number(),
+ })
+ .passthrough(),
+ ),
+ })
+ .passthrough();
+
+function hash(content: string) {
+ return createHash("sha256").update(content).digest("hex");
+}
+
+function checked<T>(operation: () => T): Effect.Effect<T, Error> {
+ return Effect.try({
+ try: operation,
+ catch: (error) =>
+ error instanceof Error ? error : new Error(String(error)),
+ });
+}
+
+function deferred() {
+ let resolve: () => void = () => undefined;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+function recording(source: VideoRow["source"] = { type: "desktopSegments" }) {
+ return { id: "owned-video", ownerId: "owned-user", source } as VideoRow;
+}
+
+function storageFixture(provider = "s3") {
+ const objects = new Map<string, StoredObject>();
+ const uploads = new Map<
+ string,
+ { key: string; parts: CopiedPart[]; metadata?: Record<string, string> }
+ >();
+ let identity = 0;
+ const object = (key: string) => {
+ const value = objects.get(key);
+ if (!value)
+ throw Object.assign(new Error(`Object missing: ${key}`), {
+ name: "NoSuchKey",
+ });
+ return value;
+ };
+ const copiedSource = (source: string, options: CopyOptions) => {
+ if (!source.startsWith("recordings/")) throw new Error("Wrong bucket");
+ const key = source.slice("recordings/".length);
+ const value = object(key);
+ if (
+ options.CopySourceIfMatch !== undefined &&
+ options.CopySourceIfMatch !== value.identity
+ ) {
+ throw new Error("Copy source precondition failed");
+ }
+ return { key, value };
+ };
+ const seed = (key: string, body: string) => {
+ objects.set(key, {
+ body,
+ size: Buffer.byteLength(body),
+ identity: `"original-${++identity}"`,
+ });
+ };
+ const bucket = {
+ bucketName: "recordings",
+ provider,
+ getObject: vi.fn((key: string) =>
+ checked(() => Option.fromNullable(objects.get(key)?.body)),
+ ),
+ headObject: vi.fn((key: string) =>
+ checked(() => {
+ const value = object(key);
+ return {
+ ContentLength: value.size,
+ ETag: value.identity,
+ Metadata: value.metadata,
+ };
+ }),
+ ),
+ putObject: vi.fn((key: string, body: string) =>
+ checked(() => {
+ seed(key, body);
+ }),
+ ),
+ copyObject: vi.fn((source: string, target: string, options: CopyOptions) =>
+ checked(() => {
+ const { value } = copiedSource(source, options);
+ if (
+ provider === "s3" &&
+ options.IfNoneMatch === "*" &&
+ objects.has(target)
+ ) {
+ throw new Error("Copy destination already exists");
+ }
+ const copied = {
+ ...value,
+ identity: `"snapshot-${++identity}"`,
+ metadata: provider === "s3" ? options.Metadata : undefined,
+ };
+ objects.set(target, copied);
+ return { CopyObjectResult: { ETag: copied.identity } };
+ }),
+ ),
+ listObjects: vi.fn(
+ ({
+ prefix: filter,
+ maxKeys = 32,
+ continuationToken,
+ }: {
+ prefix?: string;
+ maxKeys?: number;
+ continuationToken?: string;
+ }) =>
+ checked(() => {
+ const keys = [...objects.keys()]
+ .filter((key) => !filter || key.startsWith(filter))
+ .sort();
+ const start = continuationToken ? Number(continuationToken) : 0;
+ return {
+ Contents: keys
+ .slice(start, start + maxKeys)
+ .map((Key) => ({ Key })),
+ IsTruncated: start + maxKeys < keys.length,
+ NextContinuationToken:
+ start + maxKeys < keys.length
+ ? String(start + maxKeys)
+ : undefined,
+ };
+ }),
+ ),
+ getInternalSignedObjectUrl: vi.fn((key: string) =>
+ checked(() => `https://storage.example/${key}?signed=1`),
+ ),
+ multipart: {
+ create: vi.fn(
+ (key: string, options?: { Metadata?: Record<string, string> }) =>
+ checked(() => {
+ const uploadId = `upload-${++identity}`;
+ uploads.set(uploadId, {
+ key,
+ parts: [],
+ metadata: options?.Metadata,
+ });
+ return { UploadId: uploadId };
+ }),
+ ),
+ copyPart: vi.fn(
+ (
+ key: string,
+ uploadId: string,
+ partNumber: number,
+ options: CopyPartOptions,
+ ) =>
+ checked(() => {
+ const upload = uploads.get(uploadId);
+ if (!upload || upload.key !== key)
+ throw Object.assign(new Error("Unknown upload"), {
+ name: "NoSuchUpload",
+ });
+ const source = copiedSource(options.CopySource, options);
+ const range = /^bytes=(\d+)-(\d+)$/.exec(options.CopySourceRange);
+ if (!range) throw new Error("Invalid copy range");
+ const start = Number(range[1]);
+ const end = Number(range[2]);
+ if (start > end || end >= source.value.size) {
+ throw new Error("Copy range exceeds source");
+ }
+ const partIdentity = `"part-${partNumber}"`;
+ upload.parts = upload.parts.filter(
+ (part) => part.number !== partNumber,
+ );
+ upload.parts.push({
+ number: partNumber,
+ start,
+ end,
+ identity: partIdentity,
+ sourceKey: source.key,
+ });
+ return { CopyPartResult: { ETag: partIdentity } };
+ }),
+ ),
+ complete: vi.fn(
+ (
+ key: string,
+ uploadId: string,
+ options: {
+ IfNoneMatch?: string;
+ MultipartUpload: { Parts: { ETag: string; PartNumber: number }[] };
+ },
+ ) =>
+ checked(() => {
+ const upload = uploads.get(uploadId);
+ if (!upload || upload.key !== key)
+ throw Object.assign(new Error("Unknown upload"), {
+ name: "NoSuchUpload",
+ });
+ if (options.IfNoneMatch === "*" && objects.has(key)) {
+ throw new Error("Copy destination already exists");
+ }
+ let next = 0;
+ for (const [index, part] of upload.parts
+ .sort((left, right) => left.number - right.number)
+ .entries()) {
+ const requested = options.MultipartUpload.Parts[index];
+ if (
+ part.start !== next ||
+ requested?.ETag !== part.identity ||
+ requested.PartNumber !== part.number
+ ) {
+ throw new Error("Incomplete multipart copy");
+ }
+ next = part.end + 1;
+ }
+ const first = upload.parts[0];
+ if (!first) throw new Error("Empty multipart copy");
+ const source = object(first.sourceKey);
+ if (next !== source.size)
+ throw new Error("Source tail was omitted");
+ const copied = {
+ ...source,
+ identity: `"snapshot-${++identity}"`,
+ metadata: upload.metadata,
+ };
+ objects.set(key, copied);
+ uploads.delete(uploadId);
+ return { ETag: copied.identity };
+ }),
+ ),
+ abort: vi.fn((key: string, uploadId: string) =>
+ checked(() => {
+ if (uploads.get(uploadId)?.key !== key)
+ throw new Error("Wrong abort");
+ uploads.delete(uploadId);
+ }),
+ ),
+ },
+ };
+ mocks.storage.mockReturnValue(Effect.succeed([bucket]));
+ return { bucket, objects, uploads, seed, object };
+}
+
+function snapshotCheckpoint(): DesktopRecordingSourceCheckpoint {
+ return {
+ kind: "desktop-recording-source-commit",
+ version: 1,
+ generation,
+ snapshotId: "snapshot",
+ revision: 0,
+ phase: "plan",
+ cursor: 0,
+ planRoots: [],
+ receiptRoots: [],
+ };
+}
+
+async function advanceToPhase(
+ video: VideoRow,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+ phase: DesktopRecordingSourceCheckpoint["phase"],
+) {
+ while (checkpoint.phase !== phase) {
+ const result = await advanceDesktopRecordingSourceCommit(video, checkpoint);
+ if ("source" in result) throw new Error("Unexpected source completion");
+ checkpoint = result.checkpoint;
+ }
+ return checkpoint;
+}
+
+async function finishSnapshot(
+ video: VideoRow,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+) {
+ for (;;) {
+ const result = await advanceDesktopRecordingSourceCommit(video, checkpoint);
+ if ("source" in result) return result.source;
+ checkpoint = result.checkpoint;
+ }
+}
+
+function readInventory(
+ storage: ReturnType<typeof storageFixture>,
+ inventoryKey: string,
+) {
+ const raw = JSON.parse(storage.object(inventoryKey).body ?? "");
+ if (raw.version === 1) return inventorySchema.parse(raw);
+ const node = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("leaf"), entries: z.array(z.unknown()) }),
+ z.object({
+ type: z.literal("branch"),
+ children: z.array(z.object({ key: z.string() })),
+ }),
+ ]);
+ const entries = (key: string): unknown[] => {
+ const page = node.parse(JSON.parse(storage.object(key).body ?? ""));
+ return page.type === "leaf"
+ ? page.entries
+ : page.children.flatMap((child) => entries(child.key));
+ };
+ const roots = z
+ .object({ roots: z.array(z.object({ key: z.string() })) })
+ .parse(raw).roots;
+ return inventorySchema.parse({
+ ...raw,
+ version: 1,
+ objects: roots.flatMap((root) => entries(root.key)),
+ });
+}
+
+function seedSegments(
+ storage: ReturnType<typeof storageFixture>,
+ entries: (number | { index: number; duration: number })[] = [1, 2],
+ hasAudio = true,
+) {
+ const manifest = {
+ version: 2,
+ video_init_uploaded: true,
+ audio_init_uploaded: hasAudio,
+ video_segments: entries,
+ audio_segments: hasAudio ? [1] : [],
+ is_complete: true,
+ };
+ const json = `${JSON.stringify(manifest, null, 2)}\n`;
+ storage.seed(manifestKey, json);
+ storage.seed(videoInitKey, "video-init");
+ for (const entry of entries) {
+ const index = typeof entry === "number" ? entry : entry.index;
+ storage.seed(
+ `${prefix}/segments/video/segment_${String(index).padStart(3, "0")}.m4s`,
+ `video-fragment-${index}`,
+ );
+ }
+ if (hasAudio) {
+ storage.seed(audioInitKey, "audio-init");
+ storage.seed(
+ `${prefix}/segments/audio/segment_001.m4s`,
+ "audio-fragment-1",
+ );
+ }
+ const verification: RecordingVerification = {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256: hash(json) },
+ requiredAudio: false,
+ };
+ return { json, manifest, verification };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("durable desktop recording source commit", () => {
+ it.each([
+ { status: 404, code: "source-missing" },
+ { status: 412, code: "source-changed" },
+ ])(
+ "classifies a real wrapped Drive $status during source commitment",
+ async ({ status, code }) => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage);
+ const checkpoint = await advanceToPhase(
+ recording(),
+ snapshotCheckpoint(),
+ "enumerate",
+ );
+ storage.bucket.headObject.mockImplementationOnce(() =>
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(
+ status,
+ "Source metadata unavailable",
+ ),
+ }),
+ ),
+ );
+ await expect(
+ advanceDesktopRecordingSourceCommit(recording(), checkpoint),
+ ).rejects.toMatchObject({ code });
+ expect(storage.bucket.copyObject).not.toHaveBeenCalled();
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it.each([403, 429, 500, 503, null])(
+ "keeps wrapped Drive status %s retryable without replacing its checkpoint",
+ async (status) => {
+ const storage = storageFixture("googleDrive");
+ seedSegments(storage);
+ const video = recording();
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const savedCheckpoint = structuredClone(checkpoint);
+ const cause =
+ status === null
+ ? new TypeError("Network connection closed")
+ : new GoogleDriveRequestError(status, "Temporarily unavailable");
+ storage.bucket.headObject.mockImplementationOnce(() =>
+ Effect.fail(new StorageDomain.StorageError({ cause })),
+ );
+ await expect(
+ advanceDesktopRecordingSourceCommit(video, checkpoint),
+ ).rejects.not.toBeInstanceOf(DesktopRecordingSourceError);
+ expect(checkpoint).toEqual(savedCheckpoint);
+ const source = await finishSnapshot(video, checkpoint);
+ expect(
+ (await buildDesktopRecordingSourceUrls(video, source)).sourceObjects,
+ ).toHaveLength(5);
+ },
+ );
+
+ it.each([
+ { status: 404, code: "source-missing" },
+ { status: 412, code: "source-changed" },
+ ])(
+ "classifies wrapped provider status $status without acknowledging a source",
+ async ({ status, code }) => {
+ const storage = storageFixture();
+ const fixture = seedSegments(storage);
+ storage.bucket.headObject.mockImplementationOnce(() =>
+ Effect.fail(
+ new Error("Storage request failed", {
+ cause: { $metadata: { httpStatusCode: status } },
+ }),
+ ),
+ );
+ await expect(
+ commitDesktopRecordingSource(
+ recording(),
+ generation,
+ fixture.verification,
+ ),
+ ).rejects.toMatchObject({ code });
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it.each([
+ { name: "numeric legacy", entries: [1, 2] },
+ {
+ name: "estimated durations",
+ entries: [
+ { index: 1, duration: 40 },
+ { index: 2, duration: 44.849652863 },
+ ],
+ },
+ { name: "mixed legacy", entries: [1, { index: 2, duration: 3 }] },
+ ])(
+ "commits every intended fragment from $name manifests",
+ async ({ entries }) => {
+ const storage = storageFixture();
+ const fixture = seedSegments(storage, entries);
+ const source = await commitDesktopRecordingSource(
+ recording(),
+ generation,
+ fixture.verification,
+ );
+ expect(source.requiredAudio).toBe(true);
+ expect(source.manifestSha256).toBe(hash(fixture.json));
+ const inventoryJson = storage.object(source.inventoryKey).body;
+ expect(inventoryJson).toBeDefined();
+ const inventory = readInventory(storage, source.inventoryKey);
+ expect(source.inventorySha256).toBe(hash(inventoryJson ?? ""));
+ expect(inventory.objects).toHaveLength(5);
+ for (const copied of inventory.objects) {
+ const original = storage.object(copied.originalKey);
+ const snapshot = storage.object(copied.key);
+ expect(snapshot.body).toBe(original.body);
+ expect(copied.size).toBe(original.size);
+ expect(copied.originalIdentity).toBe(original.identity);
+ expect(copied.objectIdentity).toBe(snapshot.identity);
+ expect(copied.objectIdentity).not.toBe(copied.originalIdentity);
+ }
+ const snapshotManifest = source.inventoryKey.replace(
+ "inventory.json",
+ "manifest.json",
+ );
+ expect(storage.object(snapshotManifest).body).toBe(fixture.json);
+ },
+ );
+
+ it("does not acknowledge before both copies and inventory readback finish", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const copyGate = deferred();
+ const readbackGate = deferred();
+ const copy = storage.bucket.copyObject.getMockImplementation();
+ const get = storage.bucket.getObject.getMockImplementation();
+ if (!copy || !get) throw new Error("Missing fixture operation");
+ storage.bucket.copyObject.mockImplementation((...args) =>
+ Effect.promise(async () => {
+ await copyGate.promise;
+ return Effect.runPromise(copy(...args));
+ }),
+ );
+ storage.bucket.getObject.mockImplementation((key) =>
+ Effect.promise(async () => {
+ if (key.endsWith("/inventory.json")) await readbackGate.promise;
+ return Effect.runPromise(get(key));
+ }),
+ );
+ let acknowledged = false;
+ const pending = commitDesktopRecordingSource(recording(), generation).then(
+ (source) => {
+ acknowledged = true;
+ return source;
+ },
+ );
+ try {
+ await vi.waitFor(() =>
+ expect(storage.bucket.copyObject).toHaveBeenCalled(),
+ );
+ expect(acknowledged).toBe(false);
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ copyGate.resolve();
+ await vi.waitFor(() =>
+ expect(
+ storage.bucket.getObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(true),
+ );
+ expect(acknowledged).toBe(false);
+ readbackGate.resolve();
+ await pending;
+ expect(acknowledged).toBe(true);
+ } finally {
+ copyGate.resolve();
+ readbackGate.resolve();
+ }
+ });
+
+ it("keeps video-only recordings independent of absent audio", async () => {
+ const storage = storageFixture();
+ const fixture = seedSegments(storage, [1, 2], false);
+ const source = await commitDesktopRecordingSource(recording(), generation);
+ expect(source.requiredAudio).toBe(false);
+ const urls = await buildDesktopRecordingSourceUrls(recording(), source);
+ expect(urls.videoSegmentUrls).toHaveLength(2);
+ expect(urls.audioInitUrl).toBeUndefined();
+ expect(urls.audioSegmentUrls).toEqual([]);
+ await expect(
+ commitDesktopRecordingSource(recording(), generation, {
+ ...fixture.verification,
+ requiredAudio: true,
+ }),
+ ).rejects.toThrow("does not match");
+ });
+
+ it.each([
+ "missing",
+ "empty",
+ "negative-size",
+ "weak-identity",
+ "unquoted-identity",
+ ])("never commits a %s source object", async (failure) => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = storage.object(videoInitKey);
+ if (failure === "missing") storage.objects.delete(videoInitKey);
+ else if (failure === "empty") source.size = 0;
+ else if (failure === "negative-size") source.size = -1;
+ else if (failure === "weak-identity") source.identity = 'W/"weak"';
+ else source.identity = "unquoted";
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow();
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ });
+
+ it("rejects a changed source identity while saving the snapshot", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const copy = storage.bucket.copyObject.getMockImplementation();
+ if (!copy) throw new Error("Missing fixture operation");
+ storage.bucket.copyObject.mockImplementation((...args) =>
+ Effect.flatMap(copy(...args), (result) => {
+ storage.object(videoInitKey).identity = '"new-original"';
+ return Effect.succeed(result);
+ }),
+ );
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow();
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ });
+
+ it("requires the exact completion manifest, including its original bytes", async () => {
+ const storage = storageFixture();
+ const fixture = seedSegments(storage);
+ storage.seed(manifestKey, JSON.stringify(fixture.manifest));
+ await expect(
+ commitDesktopRecordingSource(
+ recording(),
+ generation,
+ fixture.verification,
+ ),
+ ).rejects.toThrow("does not match");
+ expect(storage.bucket.copyObject).not.toHaveBeenCalled();
+ });
+
+ it("never treats an uncommitted manifest as a complete source", async () => {
+ const storage = storageFixture();
+ const fixture = seedSegments(storage);
+ storage.seed(
+ manifestKey,
+ JSON.stringify({ ...fixture.manifest, is_complete: false }),
+ );
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow("incomplete");
+ expect(storage.bucket.copyObject).not.toHaveBeenCalled();
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ });
+
+ it("does not commit if the manifest changes while fragments are copied", async () => {
+ const storage = storageFixture();
+ const fixture = seedSegments(storage);
+ const copy = storage.bucket.copyObject.getMockImplementation();
+ if (!copy) throw new Error("Missing fixture operation");
+ storage.bucket.copyObject.mockImplementation((...args) =>
+ Effect.flatMap(copy(...args), (result) => {
+ storage.seed(manifestKey, `${fixture.json} `);
+ return Effect.succeed(result);
+ }),
+ );
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow("manifest changed");
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ });
+
+ it("renews a slow copy lease and refuses completion after the lease is lost", async () => {
+ vi.useFakeTimers();
+ const gate = deferred();
+ try {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const copy = storage.bucket.copyObject.getMockImplementation();
+ if (!copy) throw new Error("Missing fixture operation");
+ storage.bucket.copyObject.mockImplementation((...args) =>
+ Effect.promise(async () => {
+ await gate.promise;
+ return Effect.runPromise(copy(...args));
+ }),
+ );
+ const progress = vi
+ .fn<() => Promise<void>>()
+ .mockResolvedValue(undefined);
+ const pending = expect(
+ commitDesktopRecordingSource(
+ recording(),
+ generation,
+ undefined,
+ progress,
+ ),
+ ).rejects.toThrow("lease lost");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(storage.bucket.copyObject).toHaveBeenCalled();
+ const previousCalls = progress.mock.calls.length;
+ progress.mockRejectedValue(new Error("Recording lease lost"));
+ await vi.advanceTimersByTimeAsync(30_001);
+ expect(progress.mock.calls.length).toBeGreaterThan(previousCalls);
+ gate.resolve();
+ await pending;
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ } finally {
+ gate.resolve();
+ vi.useRealTimers();
+ }
+ });
+
+ it.each(["manifest.json", "inventory.json"])(
+ "does not commit corrupt durable %s readback",
+ async (name) => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const put = storage.bucket.putObject.getMockImplementation();
+ if (!put) throw new Error("Missing fixture operation");
+ storage.bucket.putObject.mockImplementation((key, body) =>
+ put(key, key.endsWith(`/${name}`) ? `${body}\ncorrupt` : body),
+ );
+ await expect(
+ commitDesktopRecordingSource(recording(), generation),
+ ).rejects.toThrow();
+ },
+ );
+});
+
+describe("large desktop recording snapshots", () => {
+ it("bounds an individual stalled storage copy without advancing the checkpoint", async () => {
+ const storage = storageFixture();
+ storage.seed(`${prefix}/result.mp4`, "uploaded-mp4");
+ const video = recording({ type: "desktopMP4" });
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ vi.useFakeTimers();
+ try {
+ storage.bucket.copyObject.mockImplementationOnce(() => Effect.never);
+ const pending = expect(
+ advanceDesktopRecordingSourceCommit(video, checkpoint),
+ ).rejects.toThrow(/timed out|Timeout/i);
+ await vi.advanceTimersByTimeAsync(60_001);
+ await pending;
+ expect(checkpoint.cursor).toBe(0);
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ const source = await finishSnapshot(video, checkpoint);
+ expect(source.kind).toBe("mp4");
+ });
+
+ it.each(["NoSuchUpload", "bare 404"])(
+ "restarts an expired multipart upload reported as %s while retaining its immutable source plan",
+ async (failure) => {
+ const storage = storageFixture();
+ storage.objects.set(`${prefix}/result.mp4`, {
+ size: 8 * 1024 ** 3,
+ identity: '"large-original"',
+ });
+ const video = recording({ type: "desktopMP4" });
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const created = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ );
+ if (!("checkpoint" in created) || !created.checkpoint.multipart)
+ throw new Error("Missing multipart checkpoint");
+ storage.uploads.delete(created.checkpoint.multipart.uploadId);
+ if (failure === "bare 404") {
+ storage.bucket.multipart.copyPart.mockImplementationOnce(() =>
+ Effect.fail(
+ Object.assign(new Error("Not found"), {
+ $metadata: { httpStatusCode: 404 },
+ }),
+ ),
+ );
+ }
+ const expired = await advanceDesktopRecordingSourceCommit(
+ video,
+ created.checkpoint,
+ );
+ if (!("checkpoint" in expired)) throw new Error("Unexpected completion");
+ expect(expired.checkpoint).toMatchObject({
+ phase: "copy",
+ cursor: 0,
+ plan: checkpoint.plan,
+ planRoots: checkpoint.planRoots,
+ });
+ expect(expired.checkpoint.multipart).toBeUndefined();
+ const source = await finishSnapshot(video, expired.checkpoint);
+ expect(storage.bucket.multipart.create).toHaveBeenCalledTimes(2);
+ expect(source.mp4?.fileSize).toBe(8 * 1024 ** 3);
+ },
+ );
+
+ it("does not treat a missing original as an expired multipart session", async () => {
+ const storage = storageFixture();
+ const key = `${prefix}/result.mp4`;
+ storage.objects.set(key, {
+ size: 8 * 1024 ** 3,
+ identity: '"large-original"',
+ });
+ const video = recording({ type: "desktopMP4" });
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const result = await advanceDesktopRecordingSourceCommit(video, checkpoint);
+ if (!("checkpoint" in result))
+ throw new Error("Missing multipart checkpoint");
+ storage.objects.delete(key);
+ await expect(
+ advanceDesktopRecordingSourceCommit(video, result.checkpoint),
+ ).rejects.toMatchObject({ code: "source-missing" });
+ expect(storage.bucket.multipart.create).toHaveBeenCalledOnce();
+ });
+
+ it("reuses a completed multipart object when completion response checkpointing was interrupted", async () => {
+ const storage = storageFixture();
+ storage.objects.set(`${prefix}/result.mp4`, {
+ size: 8 * 1024 ** 3,
+ identity: '"large-original"',
+ });
+ const video = recording({ type: "desktopMP4" });
+ let checkpoint = await advanceToPhase(video, snapshotCheckpoint(), "copy");
+ while ((checkpoint.multipart?.nextPartNumber ?? 0) <= 64) {
+ const result = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ );
+ if (!("checkpoint" in result)) throw new Error("Unexpected completion");
+ checkpoint = result.checkpoint;
+ }
+ await advanceDesktopRecordingSourceCommit(video, checkpoint);
+ const source = await finishSnapshot(video, checkpoint);
+ expect(storage.bucket.multipart.complete).toHaveBeenCalledOnce();
+ expect(
+ (await buildDesktopRecordingSourceUrls(video, source)).sourceFileSize,
+ ).toBe(8 * 1024 ** 3);
+ });
+
+ it.each(["s3", "googleDrive"])(
+ "resumes a completed %s copy when the database checkpoint write was lost",
+ async (provider) => {
+ const storage = storageFixture(provider);
+ seedSegments(
+ storage,
+ Array.from({ length: 33 }, (_, index) => index + 1),
+ false,
+ );
+ const video = recording();
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const copied = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ );
+ if (!("checkpoint" in copied)) throw new Error("Unexpected completion");
+ expect(copied.checkpoint.cursor).toBe(16);
+ expect(storage.bucket.copyObject).toHaveBeenCalledTimes(16);
+ const replay = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ );
+ if (!("checkpoint" in replay)) throw new Error("Unexpected completion");
+ expect(storage.bucket.copyObject).toHaveBeenCalledTimes(16);
+ expect(replay.checkpoint.snapshotId).toBe(checkpoint.snapshotId);
+ const source = await finishSnapshot(video, replay.checkpoint);
+ const urls = await buildDesktopRecordingSourceUrls(video, source);
+ expect(urls.sourceObjects).toHaveLength(34);
+ expect(storage.bucket.copyObject).toHaveBeenCalledTimes(34);
+ expect(JSON.stringify(replay.checkpoint).length).toBeLessThan(5_000);
+ },
+ );
+
+ it("reuses a metadata-verified S3 copy even when its receipt write was interrupted", async () => {
+ const storage = storageFixture();
+ storage.seed(`${prefix}/result.mp4`, "uploaded-mp4");
+ const video = recording({ type: "desktopMP4" });
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const put = storage.bucket.putObject.getMockImplementation();
+ if (!put) throw new Error("Missing fixture operation");
+ storage.bucket.putObject.mockImplementationOnce(() =>
+ Effect.fail(new Error("Receipt storage unavailable")),
+ );
+ await expect(
+ advanceDesktopRecordingSourceCommit(video, checkpoint),
+ ).rejects.toThrow("Receipt storage unavailable");
+ const source = await finishSnapshot(video, checkpoint);
+ expect(storage.bucket.copyObject).toHaveBeenCalledOnce();
+ expect(source.inventoryKey.replace(/inventory\.json$/, "mp4/0.mp4")).toBe(
+ (await buildDesktopRecordingSourceUrls(video, source)).outputKey,
+ );
+ });
+
+ it("keeps a late Drive copy isolated from the receipt selected by a retry", async () => {
+ const storage = storageFixture("googleDrive");
+ storage.seed(`${prefix}/result.mp4`, "uploaded-mp4");
+ const video = recording({ type: "desktopMP4" });
+ const checkpoint = await advanceToPhase(
+ video,
+ snapshotCheckpoint(),
+ "copy",
+ );
+ const copy = storage.bucket.copyObject.getMockImplementation();
+ if (!copy) throw new Error("Missing fixture operation");
+ const gate = deferred();
+ storage.bucket.copyObject.mockImplementationOnce((...args) =>
+ Effect.promise(async () => {
+ await gate.promise;
+ return Effect.runPromise(copy(...args));
+ }),
+ );
+ const stale = advanceDesktopRecordingSourceCommit(video, checkpoint);
+ try {
+ await vi.waitFor(() =>
+ expect(storage.bucket.copyObject).toHaveBeenCalledOnce(),
+ );
+ const source = await finishSnapshot(video, checkpoint);
+ const before = await buildDesktopRecordingSourceUrls(video, source);
+ gate.resolve();
+ await stale;
+ const after = await buildDesktopRecordingSourceUrls(video, source);
+ expect(after.sourceObjects).toEqual(before.sourceObjects);
+ expect(storage.bucket.copyObject.mock.calls[0]?.[1]).not.toBe(
+ storage.bucket.copyObject.mock.calls[1]?.[1],
+ );
+ } finally {
+ gate.resolve();
+ }
+ });
+
+ it("resumes checkpointed multipart ranges after interruption without copying previous ranges again", async () => {
+ const storage = storageFixture();
+ storage.objects.set(`${prefix}/result.mp4`, {
+ size: 8 * 1024 ** 3,
+ identity: '"large-original"',
+ });
+ const video = recording({ type: "desktopMP4" });
+ let checkpoint = await advanceToPhase(video, snapshotCheckpoint(), "copy");
+ for (let step = 0; step < 3; step++) {
+ const result = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ );
+ if (!("checkpoint" in result)) throw new Error("Unexpected completion");
+ checkpoint = result.checkpoint;
+ }
+ expect(checkpoint.multipart?.nextPartNumber).toBe(9);
+ storage.bucket.multipart.copyPart.mockImplementationOnce(() =>
+ Effect.fail(new Error("Worker stopped")),
+ );
+ await expect(
+ advanceDesktopRecordingSourceCommit(video, checkpoint),
+ ).rejects.toThrow("Worker stopped");
+ const source = await finishSnapshot(video, checkpoint);
+ expect(storage.bucket.multipart.create).toHaveBeenCalledOnce();
+ expect(storage.bucket.multipart.abort).not.toHaveBeenCalled();
+ for (let part = 1; part <= 8; part++) {
+ expect(
+ storage.bucket.multipart.copyPart.mock.calls.filter(
+ ([, , number]) => number === part,
+ ),
+ ).toHaveLength(1);
+ }
+ expect(
+ (await buildDesktopRecordingSourceUrls(video, source)).sourceFileSize,
+ ).toBe(8 * 1024 ** 3);
+ expect(JSON.stringify(checkpoint).length).toBeLessThan(10_000);
+ });
+
+ it("rejects a fragment replaced after the identity plan was checkpointed", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const checkpoint = await advanceToPhase(
+ recording(),
+ snapshotCheckpoint(),
+ "copy",
+ );
+ storage.seed(videoInitKey, "new-original");
+ await expect(
+ advanceDesktopRecordingSourceCommit(recording(), checkpoint),
+ ).rejects.toMatchObject({ code: "source-changed" });
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ });
+
+ it("snapshots a new explicit MP4 upload instead of the previously published output", async () => {
+ const storage = storageFixture();
+ const rawKey = `${prefix}/result.mp4`;
+ const publishedKey = `${prefix}/.recording/outputs/${generation}/previous.mp4`;
+ storage.seed(rawKey, "newly-uploaded-recording");
+ storage.seed(publishedKey, "previously-published-recording");
+ const uploaded = storage.object(rawKey);
+ const video = recording({ type: "desktopMP4", outputKey: publishedKey });
+ const verification: RecordingVerification = {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: uploaded.size,
+ duration: 5,
+ objectIdentity: uploaded.identity,
+ },
+ requiredAudio: false,
+ };
+ const source = await commitDesktopRecordingSource(
+ video,
+ generation,
+ verification,
+ );
+ expect(source.mp4).toMatchObject({
+ fileSize: uploaded.size,
+ objectIdentity: uploaded.identity,
+ });
+ const urls = await buildDesktopRecordingSourceUrls(video, source);
+ if (!urls.sourceOutputKey)
+ throw new Error("Missing committed MP4 snapshot");
+ expect(storage.object(urls.sourceOutputKey).body).toBe(uploaded.body);
+ expect(storage.object(publishedKey).body).toBe(
+ "previously-published-recording",
+ );
+ expect(mocks.storage).toHaveBeenNthCalledWith(1, video, {
+ resolvePublishedOutput: false,
+ });
+ });
+
+ it("copies an 8 GiB source in complete, conditional multipart ranges", async () => {
+ const storage = storageFixture();
+ const size = 8 * 1024 ** 3;
+ const key = `${prefix}/result.mp4`;
+ storage.objects.set(key, { size, identity: '"large-original"' });
+ const source = await commitDesktopRecordingSource(
+ recording({ type: "desktopMP4" }),
+ generation,
+ );
+ expect(source.mp4).toMatchObject({
+ fileSize: size,
+ objectIdentity: '"large-original"',
+ });
+ expect(storage.bucket.copyObject).not.toHaveBeenCalled();
+ expect(storage.bucket.multipart.copyPart.mock.calls.length).toBeGreaterThan(
+ 1,
+ );
+ let next = 0;
+ for (const [, , , options] of storage.bucket.multipart.copyPart.mock
+ .calls) {
+ const range = /^bytes=(\d+)-(\d+)$/.exec(options.CopySourceRange);
+ if (!range) throw new Error("Missing multipart source range");
+ expect(Number(range[1])).toBe(next);
+ expect(Number(range[2])).toBeLessThan(size);
+ expect(options.CopySourceIfMatch).toBe('"large-original"');
+ next = Number(range[2]) + 1;
+ }
+ expect(next).toBe(size);
+ expect(storage.uploads.size).toBe(0);
+ for (const [, body] of storage.bucket.putObject.mock.calls) {
+ expect(Buffer.byteLength(body)).toBeLessThan(1024 ** 2);
+ }
+ const urls = await buildDesktopRecordingSourceUrls(recording(), source);
+ expect(urls.sourceFileSize).toBe(size);
+ expect(urls.sourceObjectIdentity).not.toBe('"large-original"');
+ });
+
+ it("retains an interrupted multipart copy without publishing an inventory", async () => {
+ const storage = storageFixture();
+ storage.objects.set(`${prefix}/result.mp4`, {
+ size: 8 * 1024 ** 3,
+ identity: '"large-original"',
+ });
+ storage.bucket.multipart.copyPart.mockImplementation(() =>
+ Effect.fail(new Error("Part copy failed")),
+ );
+ await expect(
+ commitDesktopRecordingSource(
+ recording({ type: "desktopMP4" }),
+ generation,
+ ),
+ ).rejects.toThrow("Part copy failed");
+ expect(storage.bucket.multipart.abort).not.toHaveBeenCalled();
+ expect(storage.bucket.multipart.complete).not.toHaveBeenCalled();
+ expect(
+ storage.bucket.putObject.mock.calls.some(([key]) =>
+ key.endsWith("/inventory.json"),
+ ),
+ ).toBe(false);
+ expect(storage.uploads.size).toBe(1);
+ });
+});
+
+describe("committed source access", () => {
+ it("classifies malformed committed inventory JSON as a permanent source error", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = await commitDesktopRecordingSource(recording(), generation);
+ const content = "{not-json";
+ storage.seed(source.inventoryKey, content);
+ await expect(
+ buildDesktopRecordingSourceUrls(recording(), {
+ ...source,
+ inventorySha256: hash(content),
+ }),
+ ).rejects.toMatchObject({ code: "source-invalid" });
+ });
+
+ it("classifies a missing committed inventory page without retrying it as a worker failure", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = await commitDesktopRecordingSource(recording(), generation);
+ const inventory = z
+ .object({ roots: z.array(z.object({ key: z.string() })) })
+ .parse(JSON.parse(storage.object(source.inventoryKey).body ?? ""));
+ const first = inventory.roots[0];
+ if (!first) throw new Error("Missing inventory page");
+ storage.objects.delete(first.key);
+ await expect(
+ buildDesktopRecordingSourceUrls(recording(), source),
+ ).rejects.toMatchObject({ code: "source-missing" });
+ });
+
+ it("rejects malformed source entries even when their page and index digests match", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = await commitDesktopRecordingSource(recording(), generation);
+ const inventory = z
+ .object({
+ roots: z.array(
+ z.object({ key: z.string(), sha256: z.string() }).passthrough(),
+ ),
+ })
+ .passthrough()
+ .parse(JSON.parse(storage.object(source.inventoryKey).body ?? ""));
+ const first = inventory.roots[0];
+ if (!first) throw new Error("Missing inventory page");
+ const page = z
+ .object({ entries: z.array(z.record(z.unknown())) })
+ .passthrough()
+ .parse(JSON.parse(storage.object(first.key).body ?? ""));
+ page.entries[0] = { ...page.entries[0], size: -1 };
+ const pageContent = JSON.stringify(page);
+ storage.seed(first.key, pageContent);
+ first.sha256 = hash(pageContent);
+ const content = JSON.stringify(inventory);
+ storage.seed(source.inventoryKey, content);
+ await expect(
+ buildDesktopRecordingSourceUrls(recording(), {
+ ...source,
+ inventorySha256: hash(content),
+ }),
+ ).rejects.toMatchObject({ code: "source-invalid" });
+ });
+
+ it.each([
+ "other-user/owned-video/result.mp4",
+ "owned-user/other-video/result.mp4",
+ `${prefix}/../other-video/result.mp4`,
+ `${prefix}/%2e%2e/other-video/result.mp4`,
+ ])(
+ "does not snapshot a foreign or traversing MP4 source %s",
+ async (outputKey) => {
+ const storage = storageFixture();
+ storage.seed(outputKey, "unrelated-recording");
+ await expect(
+ commitDesktopRecordingSource(
+ recording({ type: "desktopMP4", outputKey }),
+ generation,
+ ),
+ ).rejects.toThrow();
+ expect(storage.bucket.copyObject).not.toHaveBeenCalled();
+ },
+ );
+
+ it("returns immutable URLs paired with their exact copied identities and sizes", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = await commitDesktopRecordingSource(recording(), generation);
+ const urls = await buildDesktopRecordingSourceUrls(recording(), source);
+ expect(urls.sourceObjects).toHaveLength(5);
+ for (const entry of urls.sourceObjects) {
+ const key = new URL(entry.url).pathname.slice(1);
+ const copied = storage.object(key);
+ expect(entry.objectIdentity).toBe(copied.identity);
+ expect(entry.size).toBe(copied.size);
+ expect(
+ key.startsWith(`${prefix}/.recording/sources/${generation}/`),
+ ).toBe(true);
+ }
+ storage.object(source.inventoryKey).body += " ";
+ await expect(
+ buildDesktopRecordingSourceUrls(recording(), source),
+ ).rejects.toThrow("changed");
+ });
+
+ it.each([
+ "other-user/owned-video/.recording/sources/generation/inventory.json",
+ `${prefix}/.recording/sources/../outside/inventory.json`,
+ `${prefix}/.recording/sources/%2e%2e/outside/inventory.json`,
+ ])(
+ "refuses foreign or traversing committed inventory keys %s",
+ async (inventoryKey) => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = await commitDesktopRecordingSource(
+ recording(),
+ generation,
+ );
+ await expect(
+ buildDesktopRecordingSourceUrls(recording(), {
+ ...source,
+ inventoryKey,
+ }),
+ ).rejects.toThrow();
+ expect(storage.bucket.getInternalSignedObjectUrl).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not sign a foreign object hidden in an otherwise matching inventory", async () => {
+ const storage = storageFixture();
+ seedSegments(storage);
+ const source = await commitDesktopRecordingSource(recording(), generation);
+ const inventory = readInventory(storage, source.inventoryKey);
+ const firstObject = inventory.objects[0];
+ if (!firstObject) throw new Error("Missing source inventory object");
+ firstObject.key = "other-user/other-video/.recording/sources/video.mp4";
+ const content = JSON.stringify(inventory);
+ storage.seed(source.inventoryKey, content);
+ await expect(
+ buildDesktopRecordingSourceUrls(recording(), {
+ ...source,
+ inventorySha256: hash(content),
+ }),
+ ).rejects.toThrow();
+ expect(
+ storage.bucket.getInternalSignedObjectUrl.mock.calls.some(([key]) =>
+ key.startsWith("other-user/"),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps output generations separate and rejects path fragments as identifiers", () => {
+ expect(
+ getDesktopRecordingOutputKey(
+ "owned-user",
+ "owned-video",
+ generation,
+ attempt,
+ ),
+ ).toBe(`${prefix}/.recording/outputs/${generation}/${attempt}.mp4`);
+ for (const invalid of ["../other", "a/b", "a\\b", "%2e%2e", ""]) {
+ expect(() =>
+ getDesktopRecordingOutputKey(
+ invalid,
+ "owned-video",
+ generation,
+ attempt,
+ ),
+ ).toThrow();
+ expect(() =>
+ getDesktopRecordingOutputKey(
+ "owned-user",
+ invalid,
+ generation,
+ attempt,
+ ),
+ ).toThrow();
+ expect(() =>
+ getDesktopRecordingOutputKey(
+ "owned-user",
+ "owned-video",
+ invalid,
+ attempt,
+ ),
+ ).toThrow();
+ expect(() =>
+ getDesktopRecordingOutputKey(
+ "owned-user",
+ "owned-video",
+ generation,
+ invalid,
+ ),
+ ).toThrow();
+ }
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts b/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts
index 7cf57de38..8dc085301 100644
--- a/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-upload-status.test.ts
@@ -1,14 +1,19 @@
-import { Effect } from "effect";
+import { Effect, Option } from "effect";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import type { RecordingVerification } from "@/lib/desktop-recording-verification";
+import {
+ type RecordingSourceProof,
+ type RecordingVerification,
+ readCompletedRecordingManifest,
+} from "@/lib/desktop-recording-verification";
-const mocks = vi.hoisted(() => ({ head: vi.fn() }));
+const mocks = vi.hoisted(() => ({ head: vi.fn(), get: vi.fn() }));
vi.mock("@cap/web-backend", async () => {
const { Effect } = await import("effect");
return {
Storage: {
- getAccessForVideo: () => Effect.succeed([{ headObject: mocks.head }]),
+ getAccessForVideo: () =>
+ Effect.succeed([{ headObject: mocks.head, getObject: mocks.get }]),
},
};
});
@@ -20,6 +25,8 @@ vi.mock("@/lib/video-storage", () => ({ decodeStorageVideo: () => ({}) }));
import {
createVerifiedRecordingReceipt,
+ type RecordingReceiptOptions,
+ validateDesktopRecordingRequest,
verifyDesktopRecordingUpload,
} from "@/lib/desktop-recording-upload-status";
@@ -47,6 +54,8 @@ const output = {
videoCodec: "h264",
audioCodec: "aac",
};
+const immutableOutputKey =
+ "owned-user/owned-video/.recording/outputs/26b763e0-d731-473e-a1f0-c41b965f4c83/856a5a30-d6f5-4e35-8ab6-394fb5b1a90f.mp4";
function video(
receipt?: NonNullable<VideoRow["metadata"]>["desktopRecordingUpload"],
@@ -54,21 +63,76 @@ function video(
return {
id: "owned-video",
ownerId: "owned-user",
- source: { type: "desktopMP4" },
+ source: {
+ type: "desktopMP4",
+ ...(receipt?.sourceProof || receipt?.sourceObjectIdentity
+ ? { outputKey: receipt.outputKey }
+ : {}),
+ },
metadata: receipt ? { desktopRecordingUpload: receipt } : {},
} as VideoRow;
}
-describe("desktop recording audio verification strength", () => {
- beforeEach(() => {
- mocks.head.mockReturnValue(
- Effect.succeed({
- ContentLength: output.fileSize,
- ETag: '"same-uploaded-generation"',
- }),
- );
+function segmentedFixture(
+ videoSegments: (number | { index: number; duration: number })[] = [
+ { index: 1, duration: 40 },
+ { index: 2, duration: 44.849652863 },
+ ],
+ hasAudio = true,
+) {
+ const json = JSON.stringify({
+ version: 2,
+ video_init_uploaded: true,
+ audio_init_uploaded: hasAudio,
+ video_segments: videoSegments,
+ audio_segments: hasAudio ? [1] : [],
+ is_complete: true,
});
+ const manifest = readCompletedRecordingManifest(json);
+ const request: RecordingVerification = {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256: manifest.manifestSha256 },
+ requiredAudio: false,
+ };
+ const sourceProof: RecordingSourceProof = {
+ version: 1,
+ manifestSha256: manifest.manifestSha256,
+ inventorySha256: "b".repeat(64),
+ sourcePreserved: true,
+ videoDuration: 91.6680778,
+ hasAudio,
+ audioVerified: hasAudio,
+ };
+ const options: RecordingReceiptOptions = {
+ outputKey: immutableOutputKey,
+ outputSha256: "c".repeat(64),
+ sourceProof,
+ };
+ mocks.get.mockReturnValue(Effect.succeed(Option.some(json)));
+ return {
+ json,
+ request,
+ sourceProof,
+ options,
+ output: {
+ ...output,
+ duration: sourceProof.videoDuration,
+ audioCodec: hasAudio ? "aac" : null,
+ },
+ };
+}
+
+beforeEach(() => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: output.fileSize,
+ ETag: '"same-uploaded-generation"',
+ }),
+ );
+ mocks.get.mockReturnValue(Effect.succeed(Option.none()));
+});
+describe("desktop recording audio verification strength", () => {
it("cannot upgrade an optional-audio receipt to required coverage for the same object", async () => {
const receipt = await createVerifiedRecordingReceipt(
video(),
@@ -164,3 +228,275 @@ describe("desktop recording audio verification strength", () => {
).rejects.toThrow("does not match");
});
});
+
+describe("segmented recording preservation receipts", () => {
+ it.each([
+ {
+ name: "legacy object estimates",
+ segments: [
+ { index: 1, duration: 40 },
+ { index: 2, duration: 44.849652863 },
+ ],
+ },
+ { name: "numeric inventory", segments: [1, 2] },
+ { name: "mixed inventory", segments: [1, { index: 2, duration: 3 }] },
+ ])("uses preserved source timing for $name", async ({ segments }) => {
+ const fixture = segmentedFixture(segments);
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ fixture.options,
+ );
+ expect(receipt).toMatchObject({
+ duration: 91.6680778,
+ requiredAudioVerified: true,
+ outputKey: immutableOutputKey,
+ sourceProof: fixture.sourceProof,
+ });
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toEqual({
+ version: 1,
+ videoId: "owned-video",
+ artifact: fixture.request.artifact,
+ fileSize: output.fileSize,
+ duration: 91.6680778,
+ hasAudio: true,
+ fullDecode: true,
+ requiredAudioVerified: true,
+ });
+ expect(mocks.head).toHaveBeenLastCalledWith(immutableOutputKey);
+ });
+
+ it("keeps video-only recordings valid without inventing audio verification", async () => {
+ const fixture = segmentedFixture([1, 2], false);
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ fixture.options,
+ );
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toMatchObject({ hasAudio: false, requiredAudioVerified: false });
+ await expect(
+ createVerifiedRecordingReceipt(
+ video(),
+ { ...fixture.request, requiredAudio: true },
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ fixture.options,
+ ),
+ ).rejects.toThrow("not fully verified");
+ });
+
+ it("requires source proof, an explicit output key, and verified remote bytes", async () => {
+ const fixture = segmentedFixture();
+ for (const change of [
+ { sourceProof: undefined },
+ { outputKey: undefined },
+ { outputSha256: undefined },
+ { outputSha256: "invalid" },
+ {
+ sourceProof: { ...fixture.sourceProof, manifestSha256: "d".repeat(64) },
+ },
+ { sourceProof: { ...fixture.sourceProof, audioVerified: false } },
+ {
+ sourceProof: {
+ ...fixture.sourceProof,
+ hasAudio: false,
+ audioVerified: false,
+ },
+ },
+ ]) {
+ await expect(
+ createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ { ...fixture.options, ...change },
+ ),
+ ).rejects.toThrow();
+ }
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+
+ it("rejects output that differs from measured source timing or loses audio", async () => {
+ const fixture = segmentedFixture();
+ for (const change of [{ duration: 84.849652863 }, { audioCodec: null }]) {
+ await expect(
+ createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ { ...fixture.output, ...change },
+ true,
+ '"same-uploaded-generation"',
+ fixture.options,
+ ),
+ ).rejects.toThrow();
+ }
+ });
+
+ it.each([
+ "other-user/owned-video/result.mp4",
+ "owned-user/other-video/result.mp4",
+ "owned-user/owned-video/../other-video/result.mp4",
+ "owned-user/owned-video/%2e%2e/other-video/result.mp4",
+ "owned-user/owned-video/..\\other-video/result.mp4",
+ "owned-user/owned-video/./result.mp4",
+ "owned-user/owned-video//result.mp4",
+ "owned-user/owned-video/result\n.mp4",
+ ])("refuses an unsafe output key %s", async (outputKey) => {
+ const fixture = segmentedFixture();
+ await expect(
+ createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ { ...fixture.options, outputKey },
+ ),
+ ).rejects.toThrow();
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+
+ it("does not read back legacy, unpublished, or replaced output as verified", async () => {
+ const fixture = segmentedFixture();
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ fixture.options,
+ );
+ expect(
+ await verifyDesktopRecordingUpload(
+ video({ ...receipt, sourceProof: undefined }),
+ fixture.request,
+ ),
+ ).toBeNull();
+ const unpublished = video(receipt);
+ unpublished.source = { type: "desktopMP4" };
+ expect(
+ await verifyDesktopRecordingUpload(unpublished, fixture.request),
+ ).toBeNull();
+ const replaced = video(receipt);
+ replaced.source = {
+ type: "desktopMP4",
+ outputKey: `${immutableOutputKey}.replacement`,
+ };
+ expect(
+ await verifyDesktopRecordingUpload(replaced, fixture.request),
+ ).toBeNull();
+ mocks.head.mockReturnValue(
+ Effect.succeed({ ContentLength: output.fileSize, ETag: '"replaced"' }),
+ );
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toBeNull();
+ });
+
+ it("keeps committed proof valid after mutable originals change or disappear", async () => {
+ const fixture = segmentedFixture();
+ mocks.get.mockReturnValue(Effect.succeed(Option.none()));
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ fixture.request,
+ fixture.output,
+ true,
+ '"same-uploaded-generation"',
+ fixture.options,
+ );
+ for (const content of [Option.none(), Option.some(`${fixture.json}\n`)]) {
+ mocks.get.mockReturnValue(Effect.succeed(content));
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), fixture.request),
+ ).toMatchObject({ artifact: fixture.request.artifact, fullDecode: true });
+ }
+ expect(mocks.get).not.toHaveBeenCalled();
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), {
+ ...fixture.request,
+ artifact: { kind: "segments", manifestSha256: "d".repeat(64) },
+ }),
+ ).toBeNull();
+ });
+
+ it("still checks the exact current manifest before accepting a new upload request", async () => {
+ const fixture = segmentedFixture();
+ await expect(
+ validateDesktopRecordingRequest(video(), fixture.request),
+ ).resolves.toMatchObject({ expected: { requiredAudio: true } });
+ mocks.get.mockReturnValue(Effect.succeed(Option.some(`${fixture.json}\n`)));
+ await expect(
+ validateDesktopRecordingRequest(video(), fixture.request),
+ ).rejects.toThrow("manifest does not match");
+ });
+});
+
+describe("immutable MP4 snapshot receipts", () => {
+ it("binds the original upload identity while verifying the snapshot output", async () => {
+ mocks.head.mockReturnValue(
+ Effect.succeed({ ContentLength: output.fileSize, ETag: '"snapshot"' }),
+ );
+ const receipt = await createVerifiedRecordingReceipt(
+ video(),
+ strongRequest,
+ output,
+ true,
+ '"snapshot"',
+ {
+ outputKey: immutableOutputKey,
+ outputSha256: "c".repeat(64),
+ sourceObjectIdentity: '"same-uploaded-generation"',
+ },
+ );
+ expect(receipt.objectIdentity).toBe('"snapshot"');
+ expect(receipt.artifact).toEqual(strongRequest.artifact);
+ expect(
+ await verifyDesktopRecordingUpload(video(receipt), strongRequest),
+ ).toMatchObject({ artifact: strongRequest.artifact, fullDecode: true });
+ expect(mocks.head).toHaveBeenLastCalledWith(immutableOutputKey);
+ });
+
+ it("never substitutes an output identity without a bound verified snapshot", async () => {
+ for (const options of [
+ {},
+ {
+ outputKey: immutableOutputKey,
+ outputSha256: "c".repeat(64),
+ sourceObjectIdentity: '"wrong-original"',
+ },
+ {
+ outputKey: immutableOutputKey,
+ sourceObjectIdentity: '"same-uploaded-generation"',
+ },
+ {
+ outputSha256: "c".repeat(64),
+ sourceObjectIdentity: '"same-uploaded-generation"',
+ },
+ ]) {
+ await expect(
+ createVerifiedRecordingReceipt(
+ video(),
+ strongRequest,
+ output,
+ true,
+ '"snapshot"',
+ options,
+ ),
+ ).rejects.toThrow();
+ }
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-recording-verification.test.ts b/apps/web/__tests__/unit/desktop-recording-verification.test.ts
index 8281fa879..eb98ef64e 100644
--- a/apps/web/__tests__/unit/desktop-recording-verification.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-verification.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
assertRecordingObjectIdentity,
readCompletedRecordingManifest,
+ recordingSourceProofSchema,
recordingUploadReceiptSchema,
recordingVerificationSchema,
validateRecordingOutput,
@@ -38,16 +39,42 @@ describe("desktop recording verification", () => {
audio_segments: [],
}),
);
- expect(first).toMatchObject({ duration: 5, hasAudio: true });
+ expect(first).toMatchObject({
+ hasAudio: true,
+ videoSegments: [1, 2],
+ audioSegments: [1],
+ });
expect(first.manifestSha256).not.toBe(second.manifestSha256);
+ expect(first.manifestSha256).not.toBe(
+ readCompletedRecordingManifest(JSON.stringify(manifest, null, 2))
+ .manifestSha256,
+ );
});
+ it.each([
+ [1, 2],
+ [1, { index: 2, duration: 12 }],
+ [{ index: 1, duration: 0.1 }, 2],
+ ])(
+ "normalizes legacy and mixed fragment inventory %j",
+ (...videoSegments) => {
+ const result = readCompletedRecordingManifest(
+ JSON.stringify({ ...manifest, video_segments: videoSegments }),
+ );
+ expect(result.videoSegments).toEqual([1, 2]);
+ },
+ );
+
it.each([
{ is_complete: false },
{ video_init_uploaded: false },
{ video_segments: [] },
{ video_segments: [{ index: 2, duration: 3 }] },
{ video_segments: [{ index: 1, duration: 0 }] },
+ { video_segments: [1, 3] },
+ { video_segments: [1, { index: 1, duration: 3 }] },
+ { video_segments: [{ index: 2, duration: 3 }, 1] },
+ { video_segments: [1, 2.5] },
{
video_segments: [
{ index: 1, duration: 2 },
@@ -55,6 +82,7 @@ describe("desktop recording verification", () => {
],
},
{ audio_segments: [] },
+ { audio_segments: [1, { index: 3, duration: 3 }] },
{ audio_init_uploaded: false },
])("refuses incomplete or inconsistent manifest %j", (change) => {
expect(() =>
@@ -191,4 +219,81 @@ describe("desktop recording verification", () => {
}).success,
).toBe(false);
});
+
+ it("does not accept source preservation inferred from metadata alone", () => {
+ const sourceProof = {
+ version: 1,
+ manifestSha256: "a".repeat(64),
+ inventorySha256: "b".repeat(64),
+ sourcePreserved: true,
+ videoDuration: 5,
+ hasAudio: true,
+ audioVerified: true,
+ };
+ expect(recordingSourceProofSchema.safeParse(sourceProof).success).toBe(
+ true,
+ );
+ for (const change of [
+ { version: 2 },
+ { manifestSha256: "invalid" },
+ { inventorySha256: undefined },
+ { sourcePreserved: false },
+ { sourcePreserved: undefined },
+ { videoDuration: Number.NaN },
+ { videoDuration: 0 },
+ { hasAudio: false },
+ ]) {
+ expect(
+ recordingSourceProofSchema.safeParse({ ...sourceProof, ...change })
+ .success,
+ ).toBe(false);
+ }
+ });
+
+ it("binds segmented receipts to preserved source and verified output bytes", () => {
+ const receipt = {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256: "a".repeat(64) },
+ fileSize: 4096,
+ duration: 5,
+ hasAudio: true,
+ fullDecode: true,
+ requiredAudioVerified: true,
+ objectIdentity: '"generation"',
+ outputKey: "user/video/attempt/result.mp4",
+ outputSha256: "c".repeat(64),
+ sourceProof: {
+ version: 1,
+ manifestSha256: "a".repeat(64),
+ inventorySha256: "b".repeat(64),
+ sourcePreserved: true,
+ videoDuration: 5,
+ hasAudio: true,
+ audioVerified: true,
+ },
+ };
+ expect(recordingUploadReceiptSchema.safeParse(receipt).success).toBe(true);
+ for (const change of [
+ { sourceProof: undefined },
+ { outputKey: undefined },
+ { outputSha256: undefined },
+ { outputSha256: "invalid" },
+ { duration: 3 },
+ { hasAudio: false },
+ { requiredAudioVerified: false },
+ { objectIdentity: 'W/"weak"' },
+ {
+ sourceProof: {
+ ...receipt.sourceProof,
+ manifestSha256: "d".repeat(64),
+ },
+ },
+ { sourceProof: { ...receipt.sourceProof, audioVerified: false } },
+ ]) {
+ expect(
+ recordingUploadReceiptSchema.safeParse({ ...receipt, ...change })
+ .success,
+ ).toBe(false);
+ }
+ });
});
diff --git a/apps/web/__tests__/unit/desktop-segments-finalization.test.ts b/apps/web/__tests__/unit/desktop-segments-finalization.test.ts
new file mode 100644
index 000000000..dbfde3542
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-segments-finalization.test.ts
@@ -0,0 +1,161 @@
+import type { User, Video } from "@cap/web-domain";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ ensure: vi.fn(),
+ state: vi.fn(),
+ recoverable: vi.fn(),
+ start: vi.fn(),
+ attach: vi.fn(),
+ dispatchFailure: vi.fn(),
+ transcribe: vi.fn(),
+}));
+vi.mock("@cap/database", () => ({
+ db: () => ({ select: () => ({ from: () => ({ where: async () => [] }) }) }),
+}));
+vi.mock("@cap/database/schema", () => ({ users: {}, videos: {} }));
+vi.mock("drizzle-orm", () => ({ eq: vi.fn() }));
+vi.mock("workflow/api", () => ({ start: mocks.start }));
+vi.mock("@/lib/ai-generation-entitlement", () => ({
+ isAiGenerationEnabledForUser: () => false,
+}));
+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: mocks.transcribe }));
+vi.mock("@/workflows/finalize-desktop-recording", () => ({
+ finalizeDesktopRecordingWorkflow: vi.fn(),
+}));
+vi.mock("@/lib/desktop-recording-jobs", () => ({
+ ensureSegmentProcessingJob: mocks.ensure,
+ getProcessingState: mocks.state,
+ isDesktopRecordingJobRecoverable: mocks.recoverable,
+ attachWorkflowRun: mocks.attach,
+ recordWorkflowDispatchFailure: mocks.dispatchFailure,
+ SourceCommitPendingError: class SourceCommitPendingError extends Error {},
+ DesktopRecordingSourceBlockedError: class DesktopRecordingSourceBlockedError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ }
+ },
+}));
+
+import {
+ DesktopRecordingSourceBlockedError,
+ SourceCommitPendingError,
+} from "@/lib/desktop-recording-jobs";
+import { queueDesktopSegmentsFinalization } from "@/lib/desktop-segments-finalization";
+
+const input = {
+ videoId: "video" as Video.VideoId,
+ userId: "user" as User.UserId,
+};
+const job = {
+ videoId: input.videoId,
+ ownerId: input.userId,
+ generation: "generation",
+ state: "committing",
+ source: null,
+};
+const committed = { ...job, state: "processing", source: { kind: "segments" } };
+
+beforeEach(() => {
+ mocks.ensure.mockResolvedValue({ job, created: true });
+ mocks.state.mockResolvedValue(job);
+ mocks.recoverable.mockReturnValue(true);
+ mocks.start.mockResolvedValue({ runId: "run" });
+ mocks.attach.mockResolvedValue(undefined);
+ mocks.dispatchFailure.mockResolvedValue(undefined);
+ mocks.transcribe.mockResolvedValue({ success: true });
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+describe("durable finalization acknowledgement", () => {
+ it("persists intent before starting a workflow and does not acknowledge an uncommitted source", async () => {
+ await expect(
+ queueDesktopSegmentsFinalization(input),
+ ).rejects.toBeInstanceOf(SourceCommitPendingError);
+ expect(mocks.ensure.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.start.mock.invocationCallOrder[0] ?? 0,
+ );
+ expect(mocks.start).toHaveBeenCalledWith(expect.any(Function), [
+ { ...input, generation: job.generation },
+ ]);
+ expect(mocks.attach).toHaveBeenCalledWith({
+ videoId: input.videoId,
+ generation: job.generation,
+ workflowRunId: "run",
+ });
+ });
+
+ it("leaves an uncommitted job recoverable when workflow dispatch fails", async () => {
+ mocks.start.mockRejectedValueOnce(new Error("queue offline"));
+ await expect(
+ queueDesktopSegmentsFinalization(input),
+ ).rejects.toBeInstanceOf(SourceCommitPendingError);
+ expect(mocks.dispatchFailure).toHaveBeenCalledWith(
+ expect.objectContaining({
+ generation: job.generation,
+ errorMessage: "queue offline",
+ }),
+ );
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ });
+
+ it("acknowledges retained source independently from a temporary dispatch outage", async () => {
+ mocks.ensure.mockResolvedValue({ job: committed, created: false });
+ mocks.state.mockResolvedValue(committed);
+ mocks.start.mockRejectedValueOnce(new Error("queue offline"));
+ await expect(queueDesktopSegmentsFinalization(input)).resolves.toBe(
+ "already-processing",
+ );
+ expect(mocks.dispatchFailure).toHaveBeenCalledOnce();
+ });
+
+ it("does not launch another workflow while an attempt has a live lease", async () => {
+ mocks.ensure.mockResolvedValue({ job: committed, created: false });
+ mocks.state.mockResolvedValue(committed);
+ mocks.recoverable.mockReturnValue(false);
+ await expect(queueDesktopSegmentsFinalization(input)).resolves.toBe(
+ "already-processing",
+ );
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it("never acknowledges a source from a generation that was replaced during dispatch", async () => {
+ mocks.ensure.mockResolvedValue({ job: committed, created: false });
+ mocks.state.mockResolvedValue(null);
+ await expect(
+ queueDesktopSegmentsFinalization(input),
+ ).rejects.toBeInstanceOf(SourceCommitPendingError);
+ });
+
+ it("keeps incomplete source separate from transient worker failure", async () => {
+ mocks.ensure.mockResolvedValue({ job: committed, created: false });
+ mocks.recoverable.mockReturnValue(false);
+ mocks.state.mockResolvedValue({
+ ...committed,
+ state: "source-blocked",
+ errorCode: "source-incomplete",
+ errorMessage: "Audio fragment is missing",
+ });
+ await expect(
+ queueDesktopSegmentsFinalization(input),
+ ).rejects.toBeInstanceOf(DesktopRecordingSourceBlockedError);
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+
+ it("passes a late client proof into the existing durable intent", async () => {
+ const verification = {
+ version: 1 as const,
+ artifact: { kind: "segments" as const, manifestSha256: "a".repeat(64) },
+ requiredAudio: false,
+ };
+ mocks.ensure.mockResolvedValue({ job: committed, created: false });
+ mocks.state.mockResolvedValue(committed);
+ mocks.recoverable.mockReturnValue(false);
+ await queueDesktopSegmentsFinalization({ ...input, verification });
+ expect(mocks.ensure).toHaveBeenCalledWith({ ...input, verification });
+ expect(mocks.start).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-segments-recovery.test.ts b/apps/web/__tests__/unit/desktop-segments-recovery.test.ts
new file mode 100644
index 000000000..77027a7f7
--- /dev/null
+++ b/apps/web/__tests__/unit/desktop-segments-recovery.test.ts
@@ -0,0 +1,245 @@
+import type { User, Video } from "@cap/web-domain";
+import { Effect, Option } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ db: vi.fn(),
+ get: vi.fn(),
+ put: vi.fn(),
+ queue: vi.fn(),
+ recoverable: vi.fn(),
+}));
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/database/schema", () => ({
+ videos: { id: "video.id", ownerId: "video.ownerId", source: "video.source" },
+ videoUploads: {
+ videoId: "upload.videoId",
+ phase: "upload.phase",
+ updatedAt: "upload.updatedAt",
+ },
+ videoProcessingJobs: { videoId: "job.videoId" },
+}));
+vi.mock("drizzle-orm", () => ({
+ and: (...args: unknown[]) => args,
+ asc: (value: unknown) => value,
+ eq: (left: unknown, right: unknown) => ({ eq: [left, right] }),
+ inArray: (left: unknown, right: unknown) => ({ in: [left, right] }),
+ isNull: (value: unknown) => ({ null: value }),
+ lte: (left: unknown, right: unknown) => ({ lte: [left, right] }),
+ sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({
+ strings: [...strings],
+ values,
+ }),
+}));
+vi.mock("@cap/web-backend", async () => {
+ const { Effect } = await import("effect");
+ return {
+ Storage: {
+ getAccessForVideo: () =>
+ Effect.succeed([{ getObject: mocks.get, putObject: mocks.put }]),
+ },
+ };
+});
+vi.mock("@/lib/server", async () => ({
+ runPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/video-storage", () => ({ decodeStorageVideo: () => ({}) }));
+vi.mock("@/lib/desktop-segments-finalization", () => ({
+ queueDesktopSegmentsFinalization: mocks.queue,
+}));
+vi.mock("@/lib/desktop-recording-jobs", () => ({
+ listRecoverableSegmentJobs: mocks.recoverable,
+ SourceCommitPendingError: class SourceCommitPendingError extends Error {},
+ DesktopRecordingSourceBlockedError: class DesktopRecordingSourceBlockedError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ }
+ },
+}));
+
+import { SourceCommitPendingError } from "@/lib/desktop-recording-jobs";
+import {
+ completeDesktopSegmentsManifestAndQueue,
+ recoverStaleDesktopSegments,
+} from "@/lib/desktop-segments-recovery";
+
+const videoId = "video" as Video.VideoId;
+const userId = "user" as User.UserId;
+const video = {
+ id: videoId,
+ ownerId: userId,
+ source: { type: "desktopSegments" },
+};
+const manifest = {
+ version: 2,
+ video_init_uploaded: true,
+ audio_init_uploaded: false,
+ video_segments: [1, 2],
+ audio_segments: [],
+ is_complete: true,
+};
+
+function selectChain(result: unknown[]) {
+ const chain = {
+ select: vi.fn(),
+ from: vi.fn(),
+ innerJoin: vi.fn(),
+ leftJoin: vi.fn(),
+ where: vi.fn(),
+ orderBy: vi.fn(),
+ limit: vi.fn(),
+ };
+ chain.select.mockReturnValue(chain);
+ chain.from.mockReturnValue(chain);
+ chain.innerJoin.mockReturnValue(chain);
+ chain.leftJoin.mockReturnValue(chain);
+ chain.where.mockReturnValue(chain);
+ chain.orderBy.mockReturnValue(chain);
+ chain.limit.mockResolvedValue(result);
+ return chain;
+}
+
+beforeEach(() => {
+ mocks.db.mockReturnValue(selectChain([video]));
+ mocks.get.mockReturnValue(
+ Effect.succeed(Option.some(JSON.stringify(manifest))),
+ );
+ mocks.put.mockReturnValue(Effect.void);
+ mocks.queue.mockResolvedValue("queued");
+ mocks.recoverable.mockResolvedValue([]);
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+describe("committed source recovery", () => {
+ it("never marks an inactive but unfinished manifest complete", async () => {
+ const incomplete = { ...manifest, is_complete: false };
+ mocks.get.mockReturnValue(
+ Effect.succeed(Option.some(JSON.stringify(incomplete))),
+ );
+ expect(
+ await completeDesktopSegmentsManifestAndQueue({ videoId, userId }),
+ ).toEqual({ status: "source-incomplete" });
+ expect(mocks.put).not.toHaveBeenCalled();
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("queues an already completed numeric legacy inventory without rewriting it", async () => {
+ expect(
+ await completeDesktopSegmentsManifestAndQueue({ videoId, userId }),
+ ).toEqual({
+ status: "queued",
+ manifestCompleted: false,
+ videoSegments: 2,
+ audioSegments: 0,
+ });
+ expect(mocks.put).not.toHaveBeenCalled();
+ });
+
+ it("reports a pending durable snapshot without claiming processing has failed", async () => {
+ mocks.queue.mockRejectedValue(new SourceCommitPendingError());
+ expect(
+ await completeDesktopSegmentsManifestAndQueue({ videoId, userId }),
+ ).toEqual({ status: "source-committing" });
+ expect(mocks.put).not.toHaveBeenCalled();
+ });
+
+ it("does not recover a manifest that changed after the caller inspected it", async () => {
+ expect(
+ await completeDesktopSegmentsManifestAndQueue({
+ videoId,
+ userId,
+ expectedManifestSignature: "older-manifest",
+ }),
+ ).toEqual({ status: "manifest-changed" });
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+});
+
+describe("durable recovery scheduling", () => {
+ it("recovers old retry and expired processing jobs without a recording-age cutoff", async () => {
+ mocks.db.mockReturnValue(selectChain([]));
+ mocks.recoverable.mockResolvedValue([
+ {
+ videoId: "old-processing",
+ ownerId: userId,
+ verification: null,
+ state: "processing",
+ createdAt: new Date("2020-01-01"),
+ },
+ {
+ videoId: "old-retry",
+ ownerId: userId,
+ verification: null,
+ state: "retry",
+ createdAt: new Date("2020-01-01"),
+ },
+ ]);
+ const result = await recoverStaleDesktopSegments({ limit: 3 });
+ expect(result.checked).toBe(2);
+ expect(result.statuses).toEqual({ queued: 2 });
+ expect(mocks.recoverable).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 2 }),
+ );
+ expect(mocks.queue).toHaveBeenCalledWith({
+ videoId: "old-processing",
+ userId,
+ verification: undefined,
+ });
+ });
+
+ it("adopts stranded legacy processing rows without assuming their inventory is complete", async () => {
+ const chain = selectChain([{ videoId, ownerId: userId }]);
+ mocks.db.mockReturnValue(chain);
+ mocks.queue.mockRejectedValue(new SourceCommitPendingError());
+ const result = await recoverStaleDesktopSegments();
+ expect(result.statuses).toEqual({ "source-committing": 1 });
+ const query = JSON.stringify(chain.where.mock.calls);
+ expect(query).toContain('"processing"');
+ expect(query).not.toContain("28 HOUR");
+ expect(query).not.toContain("startedAt");
+ expect(mocks.put).not.toHaveBeenCalled();
+ });
+
+ it("continues the bounded recovery batch when one dispatch is unavailable", async () => {
+ mocks.db.mockReturnValue(selectChain([]));
+ mocks.recoverable.mockResolvedValue([
+ { videoId: "first", ownerId: userId, verification: null },
+ { videoId: "second", ownerId: userId, verification: null },
+ ]);
+ mocks.queue
+ .mockRejectedValueOnce(new Error("temporary database failure"))
+ .mockResolvedValueOnce("queued");
+ const result = await recoverStaleDesktopSegments({ limit: 3 });
+ expect(result.statuses).toEqual({ failed: 1, queued: 1 });
+ expect(mocks.queue).toHaveBeenCalledTimes(2);
+ });
+
+ it("reserves legacy adoption capacity when recurring durable retries fill their budget", async () => {
+ mocks.recoverable.mockImplementation(async ({ limit }) =>
+ Array.from({ length: limit }, (_, index) => ({
+ videoId: `retry-${index}`,
+ ownerId: userId,
+ verification: null,
+ })),
+ );
+ const legacy = selectChain(
+ Array.from({ length: 5 }, (_, index) => ({
+ videoId: `legacy-${index}`,
+ ownerId: userId,
+ })),
+ );
+ mocks.db.mockReturnValue(legacy);
+ const result = await recoverStaleDesktopSegments();
+ expect(mocks.recoverable).toHaveBeenCalledWith(
+ expect.objectContaining({ limit: 15 }),
+ );
+ expect(legacy.limit).toHaveBeenCalledWith(5);
+ expect(result.checked).toBe(20);
+ expect(
+ result.results.filter((entry) => entry.videoId.startsWith("legacy-")),
+ ).toHaveLength(5);
+ });
+});
diff --git a/apps/web/__tests__/unit/desktop-video-create.test.ts b/apps/web/__tests__/unit/desktop-video-create.test.ts
index be2b3f426..6dcf02ed9 100644
--- a/apps/web/__tests__/unit/desktop-video-create.test.ts
+++ b/apps/web/__tests__/unit/desktop-video-create.test.ts
@@ -1,7 +1,18 @@
import { getCurrentUser } from "@cap/database/auth/session";
-import { Option } from "effect";
+import {
+ CurrentUser,
+ Policy,
+ Storage as StorageDomain,
+ Video,
+} from "@cap/web-domain";
+import { Effect, Option } from "effect";
import { beforeEach, describe, expect, it, vi } from "vitest";
+const deletion = vi.hoisted(() => ({
+ deleteVideo: vi.fn(),
+ principal: vi.fn(),
+}));
+
const schema = {
organizations: { table: "organizations" },
organizationMembers: { table: "organizationMembers" },
@@ -9,12 +20,14 @@ const schema = {
videos: { table: "videos" },
videoUploads: { table: "videoUploads" },
importedVideos: { table: "importedVideos" },
+ authApiKeys: { table: "authApiKeys" },
};
const mockDb = {
select: vi.fn(),
from: vi.fn(),
innerJoin: vi.fn(),
+ leftJoin: vi.fn(),
insert: vi.fn(),
values: vi.fn(),
update: vi.fn(),
@@ -34,6 +47,10 @@ vi.mock("@cap/database/auth/session", () => ({
getCurrentUser: vi.fn(),
}));
+vi.mock("@cap/database/auth/auth-options", () => ({
+ getServerSession: vi.fn(),
+}));
+
vi.mock("@cap/database/schema", () => schema);
vi.mock("@cap/database/emails/config", () => ({
@@ -59,16 +76,41 @@ vi.mock("@cap/utils", () => ({
userIsPro: vi.fn(() => true),
}));
-vi.mock("@cap/web-backend", () => ({
- Storage: {
- getOrganizationWritableAccess: vi.fn(),
- getS3WritableAccessForUser: vi.fn(),
- },
-}));
+vi.mock("@cap/web-backend", async () => {
+ const { Effect } = await import("effect");
+ const { makeCurrentUserLayer } = await import("@cap/web-backend/src/Auth");
+ class Videos extends Effect.Service<Videos>()("Videos", {
+ sync: () => ({ delete: deletion.deleteVideo }),
+ }) {}
+ return {
+ makeCurrentUserLayer,
+ Videos,
+ Storage: {
+ getOrganizationWritableAccess: vi.fn(),
+ getS3WritableAccessForUser: vi.fn(),
+ },
+ };
+});
-vi.mock("@/lib/server", () => ({
- runPromise: vi.fn(async (value: unknown) => value),
-}));
+vi.mock("@/lib/server", async () => {
+ const { Effect } = await import("effect");
+ const { Videos } = await import("@cap/web-backend");
+ return {
+ runPromise: vi.fn(async (value: unknown) =>
+ Effect.isEffect(value)
+ ? Effect.runPromise(
+ (
+ value as Effect.Effect<
+ unknown,
+ unknown,
+ InstanceType<typeof Videos>
+ >
+ ).pipe(Effect.provide(Videos.Default)),
+ )
+ : value,
+ ),
+ };
+});
vi.mock("@/lib/video-storage", () => ({
decodeStorageVideo: vi.fn(() => null),
@@ -93,10 +135,9 @@ vi.mock("drizzle-orm", () => ({
const mockGetCurrentUser = getCurrentUser as ReturnType<typeof vi.fn>;
const { Storage } = await import("@cap/web-backend");
-
-const effectLike = <T>(value: T) => ({
- pipe: (fn: (value: T) => unknown) => fn(value),
-});
+const { invalidateGoogleDriveStorageQuotaCache } = await import(
+ "@/lib/google-drive-storage-quota"
+);
function resetMockDb() {
for (const key of Object.keys(mockDb)) {
@@ -108,6 +149,7 @@ function resetMockDb() {
mockDb.select.mockReturnValue(mockDb);
mockDb.from.mockReturnValue(mockDb);
mockDb.innerJoin.mockReturnValue(mockDb);
+ mockDb.leftJoin.mockReturnValue(mockDb);
mockDb.insert.mockReturnValue(mockDb);
mockDb.values.mockResolvedValue([]);
mockDb.update.mockReturnValue(mockDb);
@@ -133,9 +175,9 @@ function stubStorage() {
Storage.getOrganizationWritableAccess as ReturnType<typeof vi.fn>;
const getS3WritableAccessForUser =
Storage.getS3WritableAccessForUser as ReturnType<typeof vi.fn>;
- getOrganizationWritableAccess.mockReturnValue(effectLike(Option.none()));
+ getOrganizationWritableAccess.mockReturnValue(Effect.succeed(Option.none()));
getS3WritableAccessForUser.mockReturnValue(
- effectLike({
+ Effect.succeed({
bucketId: Option.some("bucket-1"),
storageIntegrationId: Option.none(),
}),
@@ -170,6 +212,187 @@ describe("GET /new-id", () => {
});
});
+describe("DELETE /delete", () => {
+ let app: typeof import("@/app/api/desktop/[...route]/video")["app"];
+ const ownedVideo = {
+ id: "video-1",
+ ownerId: "user-1",
+ storageIntegrationId: "drive-1",
+ };
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ resetMockDb();
+ mockGetCurrentUser.mockResolvedValue({
+ id: "user-1",
+ email: "[email protected]",
+ activeOrganizationId: "org-1",
+ image: null,
+ });
+ mockDb.where.mockResolvedValue([{ video: ownedVideo }]);
+ deletion.deleteVideo
+ .mockReset()
+ .mockImplementation(() =>
+ Effect.flatMap(CurrentUser, (principal) =>
+ Effect.sync(() => deletion.principal(principal)),
+ ),
+ );
+ app = (await import("@/app/api/desktop/[...route]/video")).app;
+ });
+
+ it("delegates deletion under the authenticated principal and then invalidates quota", async () => {
+ const response = await app.request(
+ "https://cap.test/delete?videoId=video-1",
+ { method: "DELETE" },
+ );
+ expect(response.status).toBe(200);
+ expect(await response.json()).toBe(true);
+ expect(deletion.deleteVideo).toHaveBeenCalledExactlyOnceWith("video-1");
+ expect(deletion.principal).toHaveBeenCalledWith({
+ id: "user-1",
+ email: "[email protected]",
+ activeOrganizationId: "org-1",
+ iconUrlOrKey: Option.none(),
+ });
+ expect(mockDb.delete).not.toHaveBeenCalled();
+ expect(
+ invalidateGoogleDriveStorageQuotaCache,
+ ).toHaveBeenCalledExactlyOnceWith("drive-1");
+ });
+
+ it("uses the desktop bearer principal without replacing it with a cookie session", async () => {
+ mockGetCurrentUser.mockResolvedValue({ id: "cookie-user" });
+ mockDb.where
+ .mockResolvedValueOnce([
+ {
+ users: {
+ id: "token-user",
+ email: "[email protected]",
+ activeOrganizationId: "token-org",
+ image: null,
+ },
+ },
+ ])
+ .mockResolvedValueOnce([
+ { video: { ...ownedVideo, ownerId: "token-user" } },
+ ]);
+ const response = await app.request(
+ "https://cap.test/delete?videoId=video-1",
+ {
+ method: "DELETE",
+ headers: {
+ Authorization: "Bearer 00000000-0000-4000-8000-000000000000",
+ },
+ },
+ );
+ expect(response.status).toBe(200);
+ expect(mockGetCurrentUser).not.toHaveBeenCalled();
+ expect(deletion.principal).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "token-user",
+ activeOrganizationId: "token-org",
+ }),
+ );
+ expect(mockDb.delete).not.toHaveBeenCalled();
+ });
+
+ it("does not invalidate quota or return success before central deletion finishes", async () => {
+ let release: (() => void) | undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ deletion.deleteVideo.mockReturnValue(Effect.promise(() => gate));
+ const pending = app.request("https://cap.test/delete?videoId=video-1", {
+ method: "DELETE",
+ });
+ await vi.waitFor(() =>
+ expect(deletion.deleteVideo).toHaveBeenCalledTimes(1),
+ );
+ expect(invalidateGoogleDriveStorageQuotaCache).not.toHaveBeenCalled();
+ if (!release) throw new Error("Missing central deletion resolver");
+ release();
+ const response = await pending;
+ expect(response.status).toBe(200);
+ expect(
+ invalidateGoogleDriveStorageQuotaCache,
+ ).toHaveBeenCalledExactlyOnceWith("drive-1");
+ });
+
+ it("keeps the not-found response when no owned recording matches", async () => {
+ mockDb.where.mockResolvedValue([]);
+ const response = await app.request(
+ "https://cap.test/delete?videoId=video-1",
+ { method: "DELETE" },
+ );
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({
+ error: true,
+ message: "Video not found",
+ });
+ expect(deletion.deleteVideo).not.toHaveBeenCalled();
+ expect(invalidateGoogleDriveStorageQuotaCache).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { reason: "missing", error: new Video.NotFoundError() },
+ { reason: "forbidden", error: new Policy.PolicyDeniedError() },
+ ])(
+ "preserves 404 if the central service reports $reason after the preflight",
+ async ({ error }) => {
+ deletion.deleteVideo.mockReturnValue(Effect.fail(error));
+ const response = await app.request(
+ "https://cap.test/delete?videoId=video-1",
+ { method: "DELETE" },
+ );
+ expect(response.status).toBe(404);
+ expect(await response.json()).toEqual({
+ error: true,
+ message: "Video not found",
+ });
+ expect(mockDb.delete).not.toHaveBeenCalled();
+ expect(invalidateGoogleDriveStorageQuotaCache).not.toHaveBeenCalled();
+ },
+ );
+
+ it("returns 500 without invalidating quota when central storage cleanup fails", async () => {
+ deletion.deleteVideo.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error("Provider deletion failed"),
+ }),
+ ),
+ );
+ const response = await app.request(
+ "https://cap.test/delete?videoId=video-1",
+ { method: "DELETE" },
+ );
+ expect(response.status).toBe(500);
+ expect(await response.json()).toEqual({ error: "Internal server error" });
+ expect(mockDb.delete).not.toHaveBeenCalled();
+ expect(invalidateGoogleDriveStorageQuotaCache).not.toHaveBeenCalled();
+ });
+
+ it("does not delegate an unauthenticated request", async () => {
+ mockGetCurrentUser.mockResolvedValue(null);
+ const response = await app.request(
+ "https://cap.test/delete?videoId=video-1",
+ { method: "DELETE" },
+ );
+ expect(response.status).toBe(401);
+ expect(deletion.deleteVideo).not.toHaveBeenCalled();
+ expect(mockDb.select).not.toHaveBeenCalled();
+ });
+
+ it("rejects a missing recording id before deletion", async () => {
+ const response = await app.request("https://cap.test/delete", {
+ method: "DELETE",
+ });
+ expect(response.status).toBe(400);
+ expect(deletion.deleteVideo).not.toHaveBeenCalled();
+ expect(mockDb.delete).not.toHaveBeenCalled();
+ });
+});
+
describe("GET /create", () => {
let app: typeof import("@/app/api/desktop/[...route]/video")["app"];
diff --git a/apps/web/__tests__/unit/finalize-desktop-recording.test.ts b/apps/web/__tests__/unit/finalize-desktop-recording.test.ts
new file mode 100644
index 000000000..91876428e
--- /dev/null
+++ b/apps/web/__tests__/unit/finalize-desktop-recording.test.ts
@@ -0,0 +1,588 @@
+import type { User, Video } from "@cap/web-domain";
+import { Effect } from "effect";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ DesktopRecordingAttempt,
+ DesktopRecordingJob,
+} from "@/lib/desktop-recording-jobs";
+
+const mocks = vi.hoisted(() => ({
+ state: vi.fn(),
+ claim: vi.fn(),
+ ensure: vi.fn(),
+ persist: vi.fn(),
+ heartbeat: vi.fn(),
+ blocked: vi.fn(),
+ retry: vi.fn(),
+ attach: vi.fn(),
+ defer: vi.fn(),
+ commitSource: vi.fn(),
+ checkpoint: vi.fn(),
+ saveCheckpoint: vi.fn(),
+ sourceUrls: vi.fn(),
+ observe: vi.fn(),
+ sleep: vi.fn(),
+ env: vi.fn(),
+ transcribe: vi.fn(),
+ fetch: vi.fn(),
+ put: vi.fn(),
+ databaseRows: vi.fn(),
+}));
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({
+ where: mocks.databaseRows,
+ }),
+ }),
+ }),
+}));
+vi.mock("@cap/database/schema", () => ({ users: {}, videos: {} }));
+vi.mock("drizzle-orm", () => ({ and: vi.fn(), eq: vi.fn() }));
+vi.mock("@cap/env", () => ({ serverEnv: mocks.env }));
+vi.mock("workflow", () => ({ sleep: mocks.sleep }));
+vi.mock("@/lib/desktop-recording-jobs", () => ({
+ getProcessingState: mocks.state,
+ claimProcessingAttempt: mocks.claim,
+ ensureSegmentProcessingJob: mocks.ensure,
+ persistCommittedSource: mocks.persist,
+ initializeSourceCommitCheckpoint: mocks.checkpoint,
+ persistSourceCommitCheckpoint: mocks.saveCheckpoint,
+ heartbeatAttempt: mocks.heartbeat,
+ markSourceBlocked: mocks.blocked,
+ scheduleRetry: mocks.retry,
+ attachRemoteJob: mocks.attach,
+ deferWithoutMediaServer: mocks.defer,
+}));
+vi.mock("@/lib/desktop-recording-source", () => ({
+ advanceDesktopRecordingSourceCommit: mocks.commitSource,
+ buildDesktopRecordingSourceUrls: mocks.sourceUrls,
+ getDesktopRecordingOutputKey: (
+ owner: string,
+ video: string,
+ generation: string,
+ attempt: string,
+ ) => `${owner}/${video}/.recording/outputs/${generation}/${attempt}.mp4`,
+}));
+vi.mock("@/lib/desktop-recording-job-status", () => ({
+ observeDesktopRecordingJob: mocks.observe,
+}));
+vi.mock("@/lib/ai-generation-entitlement", () => ({
+ isAiGenerationEnabledForUser: () => false,
+}));
+vi.mock("@/lib/google-drive-storage-quota-cache", () => ({
+ invalidateGoogleDriveStorageQuotaCache: vi.fn(),
+}));
+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: mocks.transcribe }));
+vi.mock("@/lib/video-storage", () => ({ decodeStorageVideo: () => ({}) }));
+vi.mock("@/lib/workflow-runtime", async () => ({
+ runWorkflowPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@cap/web-backend/src/Storage/index", async () => {
+ const { Effect } = await import("effect");
+ return {
+ Storage: {
+ getAccessForVideo: () =>
+ Effect.succeed([
+ {
+ provider: "test",
+ getInternalSignedObjectUrl: (key: string) =>
+ Effect.succeed(`https://storage.test/${key}`),
+ getInternalPresignedPutUrl: mocks.put,
+ },
+ ]),
+ },
+ };
+});
+
+import {
+ commitDesktopRecordingAttempt,
+ finalizeDesktopRecordingWorkflow,
+ pollDesktopRecordingAttempt,
+ startDesktopRecordingJob,
+} from "@/workflows/finalize-desktop-recording";
+
+const videoId = "video" as Video.VideoId;
+const userId = "user" as User.UserId;
+const now = new Date("2026-09-02T12:00:00Z");
+const source = {
+ version: 1 as const,
+ kind: "segments" as const,
+ manifestSha256: "a".repeat(64),
+ inventorySha256: "b".repeat(64),
+ inventoryKey: "user/video/.recording/sources/generation/inventory.json",
+ requiredAudio: true,
+};
+const fixture: DesktopRecordingAttempt = {
+ videoId,
+ ownerId: userId,
+ generation: "generation",
+ state: "processing",
+ attemptId: "attempt",
+ attemptCount: 1,
+ manifestSha256: source.manifestSha256,
+ leaseExpiresAt: new Date(now.getTime() + 5 * 60_000),
+ nextRetryAt: now,
+ workflowRunId: "run",
+ remoteJobId: null,
+ source,
+ verification: null,
+ output: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: now,
+ updatedAt: now,
+};
+let current: DesktopRecordingJob | null;
+
+function withCurrent(update: Partial<DesktopRecordingJob>) {
+ if (!current) throw new Error("Fixture job disappeared");
+ current = { ...current, ...update };
+}
+
+beforeEach(() => {
+ mocks.databaseRows.mockResolvedValue([
+ { id: "video", ownerId: "user", source: { type: "desktopSegments" } },
+ ]);
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(now);
+ current = { ...fixture };
+ mocks.state.mockImplementation(async () => (current ? { ...current } : null));
+ mocks.ensure.mockImplementation(async () => ({
+ job: current,
+ created: false,
+ }));
+ mocks.claim.mockImplementation(async () => {
+ if (!current) return null;
+ withCurrent({
+ state: current.source ? "processing" : "committing",
+ attemptId: `attempt-${current.attemptCount + 1}`,
+ attemptCount: current.attemptCount + 1,
+ leaseExpiresAt: new Date(Date.now() + 5 * 60_000),
+ updatedAt: new Date(),
+ remoteJobId: null,
+ });
+ return current;
+ });
+ mocks.persist.mockImplementation(async (_attempt, savedSource) => {
+ withCurrent({ source: savedSource, state: "processing" });
+ return true;
+ });
+ mocks.heartbeat.mockImplementation(async () => {
+ withCurrent({ leaseExpiresAt: new Date(Date.now() + 5 * 60_000) });
+ return true;
+ });
+ mocks.retry.mockImplementation(async () => {
+ withCurrent({
+ state: "retry",
+ leaseExpiresAt: null,
+ nextRetryAt: new Date(Date.now() + 15_000),
+ });
+ return true;
+ });
+ mocks.blocked.mockImplementation(async () => {
+ withCurrent({ state: "source-blocked", leaseExpiresAt: null });
+ return true;
+ });
+ mocks.attach.mockImplementation(async ({ remoteJobId }) => {
+ withCurrent({ remoteJobId });
+ return true;
+ });
+ mocks.defer.mockImplementation(async () => {
+ withCurrent({ state: "queued", leaseExpiresAt: null });
+ return true;
+ });
+ mocks.commitSource.mockResolvedValue({ source });
+ mocks.checkpoint.mockImplementation(
+ async () =>
+ current?.output ?? {
+ kind: "desktop-recording-source-commit",
+ version: 1,
+ generation: fixture.generation,
+ snapshotId: "snapshot",
+ revision: 0,
+ phase: "plan",
+ cursor: 0,
+ planRoots: [],
+ receiptRoots: [],
+ },
+ );
+ mocks.saveCheckpoint.mockImplementation(async (_fence, checkpoint) => {
+ withCurrent({ output: checkpoint });
+ return true;
+ });
+ mocks.sourceUrls.mockResolvedValue({
+ videoInitUrl: "https://source.test/init.mp4",
+ videoSegmentUrls: ["https://source.test/segment.m4s"],
+ sourceObjects: [
+ {
+ url: "https://source.test/init.mp4",
+ objectIdentity: '"init"',
+ size: 100,
+ },
+ {
+ url: "https://source.test/segment.m4s",
+ objectIdentity: '"segment"',
+ size: 1000,
+ },
+ ],
+ manifestSha256: source.manifestSha256,
+ inventorySha256: source.inventorySha256,
+ });
+ mocks.observe.mockImplementation(async () => {
+ withCurrent({ state: "verified" });
+ return { status: "terminal", delivered: true };
+ });
+ mocks.sleep.mockImplementation(async (delay: number | Date) =>
+ vi.setSystemTime(
+ delay instanceof Date ? delay : new Date(Date.now() + delay),
+ ),
+ );
+ mocks.env.mockReturnValue({
+ MEDIA_SERVER_URL: "https://media.test",
+ MEDIA_SERVER_WEBHOOK_SECRET: "secret",
+ ASSEMBLY_API_KEY: "assembly-test",
+ WEB_URL: "https://cap.test",
+ });
+ mocks.transcribe.mockResolvedValue({ success: true });
+ mocks.put.mockImplementation((key: string) =>
+ Effect.succeed(`https://storage.test/${key}`),
+ );
+ mocks.fetch.mockResolvedValue(Response.json({ jobId: "remote-job" }));
+ vi.stubGlobal("fetch", mocks.fetch);
+});
+
+describe("durable post-publication transcription enqueue", () => {
+ it.each(["returned failure", "thrown failure"])(
+ "retries %s without creating another media attempt",
+ async (failure) => {
+ withCurrent({ leaseExpiresAt: null });
+ if (failure === "returned failure")
+ mocks.transcribe.mockResolvedValueOnce({
+ success: false,
+ message: "Queue unavailable",
+ });
+ else
+ mocks.transcribe.mockRejectedValueOnce(new Error("Queue unavailable"));
+ const result = await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: fixture.generation,
+ });
+ expect(result).toMatchObject({ success: true, jobId: "remote-job" });
+ expect(mocks.transcribe).toHaveBeenCalledTimes(2);
+ expect(mocks.fetch).toHaveBeenCalledOnce();
+ expect(mocks.claim).toHaveBeenCalledOnce();
+ expect(mocks.retry).not.toHaveBeenCalled();
+ expect(current?.state).toBe("verified");
+ expect(mocks.sleep.mock.calls).toEqual([[15_000], [15_000]]);
+ },
+ );
+
+ it("resumes failed enqueue from an already verified recording without remuxing", async () => {
+ withCurrent({ state: "verified" });
+ mocks.transcribe.mockResolvedValueOnce({
+ success: false,
+ message: "Temporary queue error",
+ });
+ expect(
+ await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: fixture.generation,
+ }),
+ ).toEqual({ success: true });
+ expect(mocks.transcribe).toHaveBeenCalledTimes(2);
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ expect(mocks.claim).not.toHaveBeenCalled();
+ });
+
+ it.each(["unconfigured", "deleted"])(
+ "skips %s transcription without retrying forever",
+ async (reason) => {
+ withCurrent({ state: "verified" });
+ if (reason === "unconfigured") mocks.env.mockReturnValue({});
+ else mocks.databaseRows.mockResolvedValue([]);
+ expect(
+ await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: fixture.generation,
+ }),
+ ).toEqual({ success: true });
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ expect(mocks.sleep).not.toHaveBeenCalled();
+ },
+ );
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+function pollingInput() {
+ return {
+ videoId,
+ generation: fixture.generation,
+ attemptId: fixture.attemptId,
+ jobId: "remote-job",
+ deadline: new Date(now.getTime() + 2 * 60 * 60_000),
+ };
+}
+
+describe("short durable processing polls", () => {
+ it("does not treat a delivered terminal webhook as durable success until publication is committed", async () => {
+ mocks.observe.mockResolvedValue({ status: "terminal", delivered: true });
+ expect(await pollDesktopRecordingAttempt(pollingInput())).toBe("waiting");
+ expect(mocks.sleep).not.toHaveBeenCalled();
+ expect(mocks.heartbeat).not.toHaveBeenCalled();
+ });
+
+ it("returns success only from the current durable verified state", async () => {
+ withCurrent({ state: "verified" });
+ expect(await pollDesktopRecordingAttempt(pollingInput())).toBe("verified");
+ expect(mocks.observe).not.toHaveBeenCalled();
+ });
+
+ it("does not extend a lease when the remote worker is missing", async () => {
+ mocks.observe.mockResolvedValue({
+ status: "unavailable",
+ delivered: false,
+ });
+ expect(await pollDesktopRecordingAttempt(pollingInput())).toBe("waiting");
+ expect(mocks.heartbeat).not.toHaveBeenCalled();
+ vi.setSystemTime(new Date(now.getTime() + 6 * 60_000));
+ expect(await pollDesktopRecordingAttempt(pollingInput())).toBe("retry");
+ expect(current?.source).toEqual(source);
+ expect(mocks.retry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ errorCode: "worker-lease-expired",
+ generation: "generation",
+ attemptId: "attempt",
+ }),
+ );
+ });
+
+ it("renews only a positively observed matching active attempt", async () => {
+ mocks.observe.mockResolvedValue({ status: "active", delivered: false });
+ expect(await pollDesktopRecordingAttempt(pollingInput())).toBe("waiting");
+ expect(mocks.heartbeat).toHaveBeenCalledWith({
+ videoId,
+ generation: "generation",
+ attemptId: "attempt",
+ });
+ expect(mocks.observe).toHaveBeenCalledWith(
+ expect.objectContaining({
+ inventorySha256: source.inventorySha256,
+ generation: "generation",
+ attemptId: "attempt",
+ }),
+ );
+ });
+
+ it("ignores an older workflow after another attempt takes over", async () => {
+ withCurrent({ attemptId: "new-attempt" });
+ expect(await pollDesktopRecordingAttempt(pollingInput())).toBe(
+ "superseded",
+ );
+ expect(mocks.observe).not.toHaveBeenCalled();
+ expect(mocks.retry).not.toHaveBeenCalled();
+ });
+});
+
+describe("source commitment and media request compatibility", () => {
+ it("checkpoints each source batch in a separate durable step before processing", async () => {
+ withCurrent({ source: null, state: "committing", leaseExpiresAt: null });
+ mocks.commitSource.mockImplementationOnce(async (_video, checkpoint) => ({
+ checkpoint: { ...checkpoint, revision: 1, phase: "copy" },
+ }));
+ const result = await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: fixture.generation,
+ });
+ expect(result.success).toBe(true);
+ expect(mocks.commitSource).toHaveBeenCalledTimes(2);
+ expect(mocks.saveCheckpoint).toHaveBeenCalledOnce();
+ expect(mocks.persist).toHaveBeenCalledOnce();
+ expect(mocks.commitSource.mock.calls[1]?.[1]).toMatchObject({
+ revision: 1,
+ phase: "copy",
+ });
+ });
+
+ it.each(["source-missing", "source-changed", "source-invalid"])(
+ "keeps %s classification when committed inventory cannot be read",
+ async (code) => {
+ withCurrent({ leaseExpiresAt: null });
+ mocks.sourceUrls.mockRejectedValue(
+ Object.assign(new Error("Committed source cannot be read"), { code }),
+ );
+ expect(
+ await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: fixture.generation,
+ }),
+ ).toMatchObject({ success: false, reason: "source-blocked" });
+ expect(mocks.blocked).toHaveBeenCalledWith(
+ expect.objectContaining({ errorCode: code }),
+ );
+ expect(mocks.retry).not.toHaveBeenCalled();
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not start media processing before durable source commitment", async () => {
+ withCurrent({ source: null });
+ await expect(startDesktopRecordingJob(fixture)).rejects.toThrow(
+ "superseded",
+ );
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+
+ it("preserves incomplete originals without calling the media server", async () => {
+ withCurrent({ source: null, state: "committing" });
+ mocks.commitSource.mockRejectedValue(
+ Object.assign(new Error("Manifest is incomplete"), {
+ code: "source-incomplete",
+ }),
+ );
+ expect(await commitDesktopRecordingAttempt(fixture)).toBe("source-blocked");
+ expect(mocks.persist).not.toHaveBeenCalled();
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+
+ it("sends immutable inventory identities without estimated legacy duration", async () => {
+ await startDesktopRecordingJob(fixture);
+ const body = JSON.parse(mocks.fetch.mock.calls[0]?.[1]?.body ?? "{}");
+ expect(body).toMatchObject({
+ generation: "generation",
+ attemptId: "attempt",
+ inventorySha256: source.inventorySha256,
+ manifestSha256: source.manifestSha256,
+ outputKey: "user/video/.recording/outputs/generation/attempt.mp4",
+ outputUpload: { type: "put", ifNoneMatch: "*" },
+ });
+ expect(body).not.toHaveProperty("expectedDuration");
+ expect(body.thumbnailPresignedUrl).toContain(
+ "/generation/attempt/screenshot.jpg",
+ );
+ });
+
+ it("reuses a recorded remote job after a step replay instead of submitting another mux", async () => {
+ withCurrent({ remoteJobId: "existing-worker" });
+ expect(await startDesktopRecordingJob(fixture)).toBe("existing-worker");
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+
+ it("verifies a legacy MP4 from its immutable snapshot without inventing a capture duration", async () => {
+ withCurrent({
+ source: {
+ ...source,
+ kind: "mp4",
+ manifestSha256: undefined,
+ mp4: { fileSize: 1000, objectIdentity: '"original"' },
+ },
+ });
+ mocks.sourceUrls.mockResolvedValue({
+ videoUrl: "https://source.test/recording.mp4",
+ sourceObjectIdentity: '"snapshot"',
+ outputKey: "user/video/.recording/sources/generation/mp4/0.mp4",
+ });
+ await startDesktopRecordingJob(fixture);
+ expect(mocks.fetch.mock.calls[0]?.[0]).toBe(
+ "https://media.test/video/verify-recording",
+ );
+ const body = JSON.parse(mocks.fetch.mock.calls[0]?.[1]?.body ?? "{}");
+ expect(body).toMatchObject({
+ originalObjectIdentity: '"original"',
+ sourceObjectIdentity: '"snapshot"',
+ fileSize: 1000,
+ });
+ expect(body).not.toHaveProperty("duration");
+ });
+
+ it("retains explicit modern MP4 duration and audio requirements", async () => {
+ withCurrent({
+ source: {
+ ...source,
+ kind: "mp4",
+ manifestSha256: undefined,
+ mp4: { fileSize: 1000, objectIdentity: '"original"' },
+ },
+ verification: {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: 1000,
+ duration: 91.6,
+ objectIdentity: '"original"',
+ },
+ requiredAudio: true,
+ },
+ });
+ mocks.sourceUrls.mockResolvedValue({
+ videoUrl: "https://source.test/recording.mp4",
+ sourceObjectIdentity: '"snapshot"',
+ outputKey: "user/video/.recording/sources/generation/mp4/0.mp4",
+ });
+ await startDesktopRecordingJob(fixture);
+ const body = JSON.parse(mocks.fetch.mock.calls[0]?.[1]?.body ?? "{}");
+ expect(body).toMatchObject({ duration: 91.6, requiredAudio: true });
+ });
+});
+
+describe("workflow retry lifetime", () => {
+ it("waits durably between failed attempts and continues past the old eight-attempt cutoff", async () => {
+ withCurrent({
+ state: "committing",
+ source: null,
+ leaseExpiresAt: null,
+ attemptId: null,
+ attemptCount: 0,
+ });
+ let submitted = 0;
+ mocks.fetch.mockImplementation(async () => {
+ if (++submitted <= 9) throw new Error("worker restarting");
+ return Response.json({ jobId: "recovered-worker" });
+ });
+ const result = await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: "generation",
+ });
+ expect(result).toEqual({ success: true, jobId: "recovered-worker" });
+ expect(mocks.retry).toHaveBeenCalledTimes(9);
+ expect(mocks.commitSource).toHaveBeenCalledOnce();
+ expect(
+ mocks.sleep.mock.calls.some(([delay]) => delay instanceof Date),
+ ).toBe(true);
+ expect(mocks.sleep.mock.calls.some(([delay]) => delay === 15_000)).toBe(
+ true,
+ );
+ });
+
+ it("preserves the self-hosted playback fallback without issuing a verified cleanup receipt", async () => {
+ withCurrent({
+ state: "queued",
+ leaseExpiresAt: null,
+ attemptId: null,
+ attemptCount: 0,
+ });
+ mocks.env.mockReturnValue({ WEB_URL: "https://self-hosted.test" });
+ const result = await finalizeDesktopRecordingWorkflow({
+ videoId,
+ userId,
+ generation: "generation",
+ });
+ expect(result).toEqual({
+ success: false,
+ reason: "media-server-unconfigured",
+ });
+ expect(current?.source).toEqual(source);
+ expect(current?.state).not.toBe("verified");
+ expect(mocks.fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/media-server-multipart.test.ts b/apps/web/__tests__/unit/media-server-multipart.test.ts
new file mode 100644
index 000000000..886171c3a
--- /dev/null
+++ b/apps/web/__tests__/unit/media-server-multipart.test.ts
@@ -0,0 +1,367 @@
+import { Effect } from "effect";
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DesktopRecordingJob } from "@/lib/desktop-recording-jobs";
+
+const mocks = vi.hoisted(() => ({
+ secret: "media-secret" as string | undefined,
+ rows: [] as unknown[],
+ getState: vi.fn(),
+ storage: vi.fn(),
+ signPart: vi.fn(),
+ complete: vi.fn(),
+ abort: vi.fn(),
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: () => ({
+ from: () => ({ where: async () => mocks.rows }),
+ }),
+ }),
+}));
+vi.mock("@cap/database/schema", () => ({
+ videos: { id: "videos.id" },
+ videoProcessingJobs: { videoId: "jobs.videoId" },
+ videoUploads: { videoId: "uploads.videoId" },
+}));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ MEDIA_SERVER_WEBHOOK_SECRET: mocks.secret }),
+}));
+vi.mock("@cap/web-backend", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@cap/web-backend/src/Storage/index", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@/lib/desktop-recording-jobs", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/desktop-recording-jobs")>()),
+ getProcessingState: mocks.getState,
+}));
+vi.mock("@/lib/server", async () => ({
+ runPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/workflow-runtime", async () => ({
+ runWorkflowPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: (video: unknown) => video,
+}));
+
+import { POST } from "@/app/api/webhooks/media-server/multipart/[action]/route";
+import { getDesktopRecordingOutputKey } from "@/lib/desktop-recording-source";
+
+const ownerId = "owned-user" as DesktopRecordingJob["ownerId"];
+const videoId = "owned-video" as DesktopRecordingJob["videoId"];
+const generation = "c9699f1a-fe24-44f9-ac89-63d5744a058c";
+const attemptId = "cf9f55f8-4d6d-44b4-a670-30c2f7e51d9b";
+const outputKey = getDesktopRecordingOutputKey(
+ ownerId,
+ videoId,
+ generation,
+ attemptId,
+);
+
+function currentJob(): DesktopRecordingJob {
+ const now = new Date();
+ return {
+ videoId,
+ ownerId,
+ generation,
+ attemptId,
+ state: "processing",
+ attemptCount: 1,
+ leaseExpiresAt: new Date(now.getTime() + 60_000),
+ nextRetryAt: now,
+ manifestSha256: "a".repeat(64),
+ remoteJobId: "remote-job",
+ workflowRunId: "workflow",
+ source: {
+ version: 1,
+ kind: "segments",
+ manifestSha256: "a".repeat(64),
+ inventorySha256: "b".repeat(64),
+ inventoryKey: `${ownerId}/${videoId}/.recording/sources/${generation}/snapshot/inventory.json`,
+ requiredAudio: true,
+ },
+ verification: null,
+ output: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+}
+
+function payload() {
+ return {
+ videoId,
+ generation,
+ attemptId,
+ key: outputKey,
+ uploadId: "multipart-upload",
+ partNumber: 1,
+ contentLength: 1024,
+ parts: [
+ { partNumber: 2, etag: '"part-2"', size: 1024 },
+ { partNumber: 1, etag: '"part-1"', size: 5 * 1024 * 1024 },
+ ],
+ };
+}
+
+async function request(
+ action: string,
+ body: unknown = payload(),
+ secret: string | null = "media-secret",
+) {
+ const headers = new Headers({ "Content-Type": "application/json" });
+ if (secret !== null) headers.set("x-media-server-secret", secret);
+ const response = await POST(
+ new NextRequest(
+ `https://cap.so/api/webhooks/media-server/multipart/${action}`,
+ {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ },
+ ),
+ { params: Promise.resolve({ action }) },
+ );
+ if (!response) throw new Error("Multipart route did not return a response");
+ return response;
+}
+
+function useStorage(provider = "s3") {
+ mocks.storage.mockReturnValue(
+ Effect.succeed([
+ {
+ provider,
+ multipart: {
+ getPresignedUploadPartUrl: mocks.signPart,
+ complete: mocks.complete,
+ abort: mocks.abort,
+ },
+ },
+ ]),
+ );
+}
+
+describe("media-server multipart fencing", () => {
+ beforeEach(() => {
+ mocks.secret = "media-secret";
+ mocks.rows = [
+ { id: videoId, ownerId, source: { type: "desktopSegments" } },
+ ];
+ mocks.getState.mockReset().mockResolvedValue(currentJob());
+ mocks.signPart
+ .mockReset()
+ .mockReturnValue(Effect.succeed("https://storage.test/part"));
+ mocks.complete.mockReset().mockReturnValue(
+ Effect.succeed({
+ Location: "https://storage.test/output",
+ ETag: '"output-etag"',
+ }),
+ );
+ mocks.abort.mockReset().mockReturnValue(Effect.void);
+ useStorage();
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ });
+
+ it.each([null, "wrong-secret", "éééééééééééé"])(
+ "rejects missing or incorrect webhook authentication %s",
+ async (secret) => {
+ expect((await request("sign-part", payload(), secret)).status).toBe(401);
+ expect(mocks.getState).not.toHaveBeenCalled();
+ expect(mocks.storage).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not accept an unset configured secret", async () => {
+ mocks.secret = undefined;
+ expect((await request("sign-part")).status).toBe(401);
+ expect(mocks.storage).not.toHaveBeenCalled();
+ });
+
+ it("signs only the exact current attempt key and part", async () => {
+ const response = await request("sign-part");
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ url: "https://storage.test/part" });
+ expect(mocks.getState).toHaveBeenCalledWith({ videoId });
+ expect(mocks.signPart).toHaveBeenCalledWith(
+ outputKey,
+ "multipart-upload",
+ 1,
+ );
+ });
+
+ it.each([
+ "owner",
+ "generation",
+ "attempt",
+ "expired",
+ "unleased",
+ "state",
+ "source",
+ "missing",
+ ])(
+ "refuses signing and completion for an invalid %s fence",
+ async (reason) => {
+ const job = currentJob();
+ if (reason === "owner") job.ownerId = "other-user" as typeof ownerId;
+ if (reason === "generation") job.generation = "different-generation";
+ if (reason === "attempt") job.attemptId = "different-attempt";
+ if (reason === "expired") job.leaseExpiresAt = new Date(Date.now() - 1);
+ if (reason === "unleased") job.leaseExpiresAt = null;
+ if (reason === "state") job.state = "retry";
+ if (reason === "source") job.source = null;
+ mocks.getState.mockResolvedValue(reason === "missing" ? null : job);
+ expect((await request("sign-part")).status).toBe(409);
+ expect((await request("complete")).status).toBe(409);
+ expect(mocks.storage).not.toHaveBeenCalled();
+ expect(mocks.signPart).not.toHaveBeenCalled();
+ expect(mocks.complete).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ "other-user/owned-video/.recording/outputs/generation/attempt.mp4",
+ "owned-user/other-video/result.mp4",
+ "owned-user/owned-video/result.mp4",
+ "owned-user/owned-video/.recording/outputs/../attempt.mp4",
+ "owned-user/owned-video/.recording/outputs/%2e%2e/attempt.mp4",
+ ])(
+ "rejects a foreign, canonical, or traversing fenced key %s",
+ async (key) => {
+ for (const action of ["sign-part", "complete", "abort"]) {
+ expect((await request(action, { ...payload(), key })).status).toBe(400);
+ }
+ expect(mocks.storage).not.toHaveBeenCalled();
+ },
+ );
+
+ it("completes contiguous parts in order without replacing an existing output", async () => {
+ const response = await request("complete");
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ success: true,
+ location: "https://storage.test/output",
+ objectIdentity: '"output-etag"',
+ });
+ expect(mocks.complete).toHaveBeenCalledWith(outputKey, "multipart-upload", {
+ MultipartUpload: {
+ Parts: [
+ { PartNumber: 1, ETag: '"part-1"' },
+ { PartNumber: 2, ETag: '"part-2"' },
+ ],
+ },
+ IfNoneMatch: "*",
+ });
+ });
+
+ it.each([[1, 3], [1, 1], [2], []])(
+ "refuses missing or duplicate multipart sequence %j",
+ async (...partNumbers) => {
+ const parts = partNumbers.map((partNumber) => ({
+ partNumber,
+ etag: '"part"',
+ size: 1024,
+ }));
+ expect((await request("complete", { ...payload(), parts })).status).toBe(
+ 400,
+ );
+ expect(mocks.complete).not.toHaveBeenCalled();
+ },
+ );
+
+ it("permits aborting the old exact key after the lease or attempt changes", async () => {
+ mocks.getState.mockResolvedValue({
+ ...currentJob(),
+ attemptId: "new-attempt",
+ leaseExpiresAt: new Date(Date.now() - 1),
+ });
+ const response = await request("abort");
+ expect(response.status).toBe(200);
+ expect(mocks.getState).not.toHaveBeenCalled();
+ expect(mocks.abort).toHaveBeenCalledWith(outputKey, "multipart-upload");
+ expect((await request("sign-part")).status).toBe(409);
+ expect((await request("complete")).status).toBe(409);
+ });
+
+ it("retains the canonical multipart contract for an unfenced legacy worker", async () => {
+ const body = {
+ ...payload(),
+ generation: undefined,
+ attemptId: undefined,
+ key: `${ownerId}/${videoId}/result.mp4`,
+ };
+ expect((await request("sign-part", body)).status).toBe(200);
+ expect((await request("complete", body)).status).toBe(200);
+ expect(mocks.getState).not.toHaveBeenCalled();
+ expect(mocks.complete).toHaveBeenCalledWith(body.key, body.uploadId, {
+ MultipartUpload: {
+ Parts: [
+ { PartNumber: 1, ETag: '"part-1"' },
+ { PartNumber: 2, ETag: '"part-2"' },
+ ],
+ },
+ });
+ });
+
+ it.each([
+ { generation: undefined },
+ { attemptId: undefined },
+ { generation: "../elsewhere" },
+ { attemptId: 1 },
+ { partNumber: 0 },
+ { partNumber: 1.5 },
+ { contentLength: 0 },
+ { uploadId: "" },
+ ])(
+ "rejects malformed or partially fenced sign requests %#",
+ async (change) => {
+ expect(
+ (await request("sign-part", { ...payload(), ...change })).status,
+ ).toBe(400);
+ expect(mocks.signPart).not.toHaveBeenCalled();
+ },
+ );
+
+ it("returns not found for a deleted video and rejects non-S3 storage", async () => {
+ mocks.rows = [];
+ expect((await request("complete")).status).toBe(404);
+ mocks.rows = [
+ { id: videoId, ownerId, source: { type: "desktopSegments" } },
+ ];
+ useStorage("google-drive");
+ expect((await request("complete")).status).toBe(400);
+ expect(mocks.complete).not.toHaveBeenCalled();
+ });
+
+ it("does not report success when conditional multipart completion fails", async () => {
+ mocks.complete.mockReturnValueOnce(
+ Effect.fail(new Error("Precondition failed")),
+ );
+ expect((await request("complete")).status).toBe(500);
+ });
+
+ it("rejects invalid JSON and unknown multipart actions", async () => {
+ const response = await POST(
+ new NextRequest(
+ "https://cap.so/api/webhooks/media-server/multipart/complete",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-media-server-secret": "media-secret",
+ },
+ body: "{",
+ },
+ ),
+ { params: Promise.resolve({ action: "complete" }) },
+ );
+ if (!response) throw new Error("Multipart route did not return a response");
+ expect(response.status).toBe(400);
+ expect((await request("unexpected")).status).toBe(404);
+ expect(mocks.storage).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/media-server-progress.test.ts b/apps/web/__tests__/unit/media-server-progress.test.ts
new file mode 100644
index 000000000..e63dfe8bc
--- /dev/null
+++ b/apps/web/__tests__/unit/media-server-progress.test.ts
@@ -0,0 +1,669 @@
+import { Effect } from "effect";
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { DesktopRecordingJob } from "@/lib/desktop-recording-jobs";
+
+const mocks = vi.hoisted(() => ({
+ secret: "media-secret" as string | undefined,
+ db: vi.fn(),
+ getState: vi.fn(),
+ retry: vi.fn(),
+ blocked: vi.fn(),
+ head: vi.fn(),
+ storage: vi.fn(),
+ queue: vi.fn(),
+ transcribe: vi.fn(),
+ invalidateQuota: vi.fn(),
+ tables: {
+ videos: {
+ id: "videos.id",
+ ownerId: "videos.ownerId",
+ metadata: "videos.metadata",
+ },
+ jobs: { videoId: "jobs.videoId" },
+ uploads: { videoId: "uploads.videoId", rawFileKey: "uploads.rawFileKey" },
+ },
+}));
+
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/database/schema", () => ({
+ videos: mocks.tables.videos,
+ videoProcessingJobs: mocks.tables.jobs,
+ videoUploads: mocks.tables.uploads,
+}));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ MEDIA_SERVER_WEBHOOK_SECRET: mocks.secret }),
+}));
+vi.mock("@cap/web-backend", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@cap/web-backend/src/Storage/index", () => ({
+ Storage: { getAccessForVideo: mocks.storage },
+}));
+vi.mock("@/lib/desktop-recording-jobs", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/lib/desktop-recording-jobs")>()),
+ getProcessingState: mocks.getState,
+ scheduleRetry: mocks.retry,
+ markSourceBlocked: mocks.blocked,
+}));
+vi.mock("@/lib/server", async () => ({
+ runPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/workflow-runtime", async () => ({
+ runWorkflowPromise: (await import("effect")).Effect.runPromise,
+}));
+vi.mock("@/lib/video-storage", () => ({
+ decodeStorageVideo: (video: unknown) => video,
+}));
+vi.mock("@/lib/desktop-segments-finalization", () => ({
+ queueDesktopSegmentsFinalization: mocks.queue,
+}));
+vi.mock("@/lib/google-drive-storage-quota", () => ({
+ invalidateGoogleDriveStorageQuotaCache: mocks.invalidateQuota,
+}));
+vi.mock("@/lib/google-drive-storage-quota-cache", () => ({
+ invalidateGoogleDriveStorageQuotaCache: mocks.invalidateQuota,
+}));
+vi.mock("@/lib/queue-video-transcription", () => ({
+ queueVideoTranscription: mocks.transcribe,
+ shouldQueueTranscriptionAfterMediaComplete: () => true,
+}));
+
+import { POST } from "@/app/api/webhooks/media-server/progress/route";
+import {
+ parseDesktopRecordingJob,
+ SourceCommitPendingError,
+} from "@/lib/desktop-recording-jobs";
+import { getDesktopRecordingOutputKey } from "@/lib/desktop-recording-source";
+
+const ownerId = "owned-user" as DesktopRecordingJob["ownerId"];
+const videoId = "owned-video" as DesktopRecordingJob["videoId"];
+const generation = "c9699f1a-fe24-44f9-ac89-63d5744a058c";
+const attemptId = "cf9f55f8-4d6d-44b4-a670-30c2f7e51d9b";
+const manifestSha256 = "a".repeat(64);
+const inventorySha256 = "b".repeat(64);
+const outputKey = getDesktopRecordingOutputKey(
+ ownerId,
+ videoId,
+ generation,
+ attemptId,
+);
+const metadata = {
+ fileSize: 4096,
+ duration: 5,
+ width: 320,
+ height: 180,
+ fps: 30,
+ videoCodec: "h264",
+ audioCodec: "aac",
+};
+const verification = {
+ version: 1 as const,
+ artifact: { kind: "segments" as const, manifestSha256 },
+ requiredAudio: true,
+};
+
+function fixture() {
+ const now = new Date();
+ const job: DesktopRecordingJob = {
+ videoId,
+ ownerId,
+ generation,
+ attemptId,
+ manifestSha256,
+ state: "processing",
+ attemptCount: 1,
+ leaseExpiresAt: new Date(now.getTime() + 60_000),
+ nextRetryAt: now,
+ workflowRunId: "workflow-1",
+ remoteJobId: "remote-1",
+ source: {
+ version: 1,
+ kind: "segments",
+ manifestSha256,
+ inventorySha256,
+ inventoryKey: `${ownerId}/${videoId}/.recording/sources/${generation}/snapshot/inventory.json`,
+ requiredAudio: true,
+ },
+ verification,
+ output: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const payload = {
+ jobId: "remote-1",
+ videoId,
+ generation,
+ attemptId,
+ phase: "complete",
+ progress: 100,
+ metadata: { ...metadata },
+ recordingVerification: {
+ request: verification,
+ fullDecode: true,
+ objectIdentity: '"output-etag"',
+ outputKey,
+ outputSha256: "c".repeat(64),
+ sourceProof: {
+ version: 1,
+ manifestSha256,
+ inventorySha256,
+ sourcePreserved: true,
+ videoDuration: metadata.duration,
+ hasAudio: true,
+ audioVerified: true,
+ },
+ },
+ };
+ return { job, payload };
+}
+
+type Mutation = {
+ operation: "update" | "delete";
+ table: unknown;
+ values?: Record<string, unknown>;
+};
+
+function databaseFixture(initial: DesktopRecordingJob | null = fixture().job) {
+ let current = initial;
+ let rawFileKey: string | null = null;
+ const video: Record<string, unknown> = {
+ id: videoId,
+ ownerId,
+ source: { type: "desktopSegments" },
+ metadata: {},
+ storageIntegrationId: null,
+ bucket: null,
+ };
+ const mutations: Mutation[] = [];
+ const rows = (table: unknown) => {
+ if (table === mocks.tables.videos) return [structuredClone(video)];
+ if (table === mocks.tables.jobs)
+ return current ? [structuredClone(current)] : [];
+ if (table === mocks.tables.uploads) return [{ rawFileKey }];
+ throw new Error("Unexpected table");
+ };
+ const writes = (pending: Mutation[]) => ({
+ update: (table: unknown) => ({
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ pending.push({ operation: "update", table, values });
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ }),
+ delete: (table: unknown) => ({
+ where: async () => {
+ pending.push({ operation: "delete", table });
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ });
+ function transactionHandle(pending: Mutation[]) {
+ return {
+ select: () => ({
+ from: (table: unknown) => ({
+ where: () => ({ for: async () => rows(table) }),
+ }),
+ }),
+ ...writes(pending),
+ };
+ }
+ const transaction = vi.fn(
+ async (
+ operation: (tx: ReturnType<typeof transactionHandle>) => Promise<unknown>,
+ ) => {
+ const pending: Mutation[] = [];
+ const result = await operation(transactionHandle(pending));
+ for (const mutation of pending) {
+ mutations.push(mutation);
+ if (mutation.operation !== "update") continue;
+ if (mutation.table === mocks.tables.jobs && current) {
+ current = { ...current, ...mutation.values };
+ } else if (mutation.table === mocks.tables.videos) {
+ Object.assign(video, mutation.values);
+ }
+ }
+ return result;
+ },
+ );
+ mocks.db.mockReturnValue({
+ select: () => ({
+ from: (table: unknown) => ({ where: async () => rows(table) }),
+ }),
+ ...writes(mutations),
+ transaction,
+ });
+ mocks.getState.mockImplementation(async () =>
+ current ? parseDesktopRecordingJob(structuredClone(current)) : null,
+ );
+ return {
+ mutations,
+ video,
+ transaction,
+ setRawFileKey: (key: string) => {
+ rawFileKey = key;
+ },
+ };
+}
+
+function request(
+ body: unknown = fixture().payload,
+ secret: string | null = "media-secret",
+) {
+ const headers = new Headers({ "Content-Type": "application/json" });
+ if (secret !== null) headers.set("x-media-server-secret", secret);
+ return POST(
+ new NextRequest("https://cap.so/api/webhooks/media-server/progress", {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ }),
+ );
+}
+
+describe("media-server recording progress webhook", () => {
+ beforeEach(() => {
+ mocks.secret = "media-secret";
+ mocks.storage.mockReturnValue(Effect.succeed([{ headObject: mocks.head }]));
+ mocks.head.mockImplementation((key: string) =>
+ key.endsWith(".mp4")
+ ? Effect.succeed({
+ ContentLength: metadata.fileSize,
+ ETag: '"output-etag"',
+ })
+ : Effect.fail(new Error("Asset absent")),
+ );
+ mocks.queue.mockReset().mockResolvedValue("queued");
+ mocks.transcribe.mockReset().mockResolvedValue({ success: true });
+ mocks.invalidateQuota.mockResolvedValue(undefined);
+ mocks.retry.mockResolvedValue(true);
+ mocks.blocked.mockResolvedValue(true);
+ vi.spyOn(console, "log").mockImplementation(() => undefined);
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
+ });
+
+ it.each([null, "wrong-secret", "éééééééééééé"])(
+ "rejects unauthenticated callbacks before publication %s",
+ async (secret) => {
+ const database = databaseFixture();
+ expect((await request(fixture().payload, secret)).status).toBe(401);
+ expect(mocks.getState).not.toHaveBeenCalled();
+ expect(database.mutations).toEqual([]);
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ },
+ );
+
+ it("refuses callbacks when the webhook secret is not configured", async () => {
+ databaseFixture();
+ mocks.secret = undefined;
+ expect((await request()).status).toBe(401);
+ expect(mocks.getState).not.toHaveBeenCalled();
+ });
+
+ it("publishes the fenced immutable output before queueing transcription", async () => {
+ const database = databaseFixture();
+ mocks.transcribe.mockImplementation(async () => {
+ expect(database.mutations).toContainEqual(
+ expect.objectContaining({
+ table: mocks.tables.jobs,
+ values: expect.objectContaining({ state: "verified" }),
+ }),
+ );
+ return { success: true };
+ });
+ const response = await request();
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ success: true });
+ expect(database.mutations).toContainEqual(
+ expect.objectContaining({
+ table: mocks.tables.videos,
+ values: expect.objectContaining({
+ source: { type: "desktopMP4", outputKey },
+ }),
+ }),
+ );
+ expect(mocks.head).toHaveBeenCalledWith(outputKey);
+ expect(mocks.transcribe).toHaveBeenCalledExactlyOnceWith(videoId);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("does not repeat publication or transcription for a duplicate callback", async () => {
+ const database = databaseFixture();
+ expect((await request()).status).toBe(200);
+ const count = database.mutations.length;
+ expect((await request()).status).toBe(200);
+ expect(database.mutations).toHaveLength(count);
+ expect(mocks.transcribe).toHaveBeenCalledOnce();
+ });
+
+ it("keeps the completed recording published if transcription is unavailable", async () => {
+ const database = databaseFixture();
+ mocks.transcribe.mockRejectedValueOnce(
+ new Error("Transcription unavailable"),
+ );
+ expect((await request()).status).toBe(200);
+ expect(database.video.source).toEqual({ type: "desktopMP4", outputKey });
+ });
+
+ it.each(["generation", "attempt", "remote", "expired"])(
+ "acknowledges but does not publish a stale %s callback",
+ async (reason) => {
+ const { job, payload } = fixture();
+ if (reason === "generation") job.generation = "new-generation";
+ if (reason === "attempt") job.attemptId = "new-attempt";
+ if (reason === "remote") job.remoteJobId = "new-remote-job";
+ if (reason === "expired") job.leaseExpiresAt = new Date(Date.now() - 1);
+ const database = databaseFixture(job);
+ expect((await request(payload)).status).toBe(200);
+ expect(database.mutations).toEqual([]);
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(mocks.queue).not.toHaveBeenCalled();
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects fenced callbacks without a current job or from a different owner", async () => {
+ let database = databaseFixture(null);
+ expect((await request()).status).toBe(409);
+ expect(database.mutations).toEqual([]);
+ database = databaseFixture();
+ database.video.ownerId = "different-owner";
+ expect((await request()).status).toBe(409);
+ expect(database.mutations).toEqual([]);
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { generation: 123 },
+ { generation: "" },
+ { generation: undefined },
+ { attemptId: undefined },
+ { attemptId: {} },
+ { videoId: undefined },
+ { videoId: 123 },
+ { jobId: undefined },
+ { phase: "unexpected" },
+ { progress: 101 },
+ { recordingVerification: { request: verification, fullDecode: false } },
+ ])(
+ "rejects malformed callbacks without falling through to legacy writes %#",
+ async (change) => {
+ const database = databaseFixture();
+ const response = await request({ ...fixture().payload, ...change });
+ expect(response.status).toBe(400);
+ expect(database.mutations).toEqual([]);
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(mocks.queue).not.toHaveBeenCalled();
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ },
+ );
+
+ it("leaves the upload pending when the remotely verified object was replaced", async () => {
+ const database = databaseFixture();
+ mocks.head.mockReturnValue(
+ Effect.succeed({
+ ContentLength: metadata.fileSize,
+ ETag: '"other-output"',
+ }),
+ );
+ const response = await request();
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expect(database.mutations).toEqual([]);
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ });
+
+ it.each(["processing-unavailable", "source-missing"])(
+ "routes a current %s failure to durable recovery without publishing",
+ async (errorCode) => {
+ const database = databaseFixture();
+ const response = await request({
+ ...fixture().payload,
+ phase: "error",
+ errorCode,
+ error: "Worker failed",
+ });
+ expect(response.status).toBe(200);
+ const expected =
+ errorCode === "source-missing" ? mocks.blocked : mocks.retry;
+ expect(expected).toHaveBeenCalledWith({
+ videoId,
+ generation,
+ attemptId,
+ errorCode,
+ errorMessage: "Worker failed",
+ });
+ expect(database.mutations).toEqual([]);
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ { sourceType: "desktopSegments", hasProof: false },
+ { sourceType: "desktopMP4", hasProof: false },
+ { sourceType: "desktopMP4", hasProof: true },
+ ])(
+ "adopts $sourceType completion (proof: $hasProof) without publishing canonical media",
+ async ({ sourceType, hasProof }) => {
+ const database = databaseFixture(null);
+ database.video.source = { type: sourceType };
+ const proof = hasProof
+ ? {
+ request: {
+ version: 1,
+ artifact: {
+ kind: "mp4",
+ fileSize: 4096,
+ duration: 5,
+ objectIdentity: '"legacy-upload"',
+ },
+ requiredAudio: true,
+ },
+ fullDecode: true,
+ objectIdentity: '"legacy-upload"',
+ }
+ : undefined;
+ const response = await request({
+ jobId: "legacy-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ metadata,
+ recordingVerification: proof,
+ });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ success: true,
+ status: "queued-for-verification",
+ });
+ expect(mocks.queue).toHaveBeenCalledWith({
+ videoId,
+ userId: ownerId,
+ verification: proof?.request,
+ });
+ expect(database.mutations).toEqual([]);
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ },
+ );
+
+ it("accepts a legacy worker callback while durable source commitment remains pending", async () => {
+ const database = databaseFixture(null);
+ mocks.queue.mockRejectedValueOnce(new SourceCommitPendingError());
+ const response = await request({
+ jobId: "legacy-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ });
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({
+ success: true,
+ status: "queued-for-verification",
+ });
+ expect(database.mutations).toEqual([]);
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ });
+
+ it("keeps the explicit edit path for this recording's owned original source", async () => {
+ const database = databaseFixture(null);
+ database.video.source = { type: "desktopMP4" };
+ database.setRawFileKey(`${ownerId}/${videoId}/source/original.mp4`);
+ const response = await request({
+ jobId: "edit-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ metadata,
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ expect(database.mutations).toContainEqual(
+ expect.objectContaining({
+ operation: "update",
+ table: mocks.tables.uploads,
+ values: expect.objectContaining({ phase: "complete" }),
+ }),
+ );
+ expect(
+ database.mutations.some(({ operation }) => operation === "delete"),
+ ).toBe(false);
+ expect(mocks.head).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ `other-user/${videoId}/source/original.mp4`,
+ `${ownerId}/other-video/source/original.mp4`,
+ ])("does not treat the foreign key %s as an edit exception", async (key) => {
+ const database = databaseFixture(null);
+ database.video.source = { type: "desktopMP4" };
+ database.setRawFileKey(key);
+ const response = await request({
+ jobId: "legacy-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ metadata,
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.queue).toHaveBeenCalledWith({
+ videoId,
+ userId: ownerId,
+ verification: undefined,
+ });
+ expect(database.mutations).toEqual([]);
+ });
+
+ it.each(["verified", "output-replaced"])(
+ "preserves intentional generic replacement processing after %s",
+ async (state) => {
+ const { job } = fixture();
+ if (state === "verified") job.state = "verified";
+ else {
+ job.state = "source-blocked";
+ job.errorCode = "output-replaced";
+ }
+ const database = databaseFixture(job);
+ database.video.source = { type: "desktopMP4", outputKey };
+ database.setRawFileKey(`${ownerId}/${videoId}/replacement.mp4`);
+ const response = await request({
+ jobId: "replacement-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ metadata,
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(database.mutations).toContainEqual({
+ operation: "delete",
+ table: mocks.tables.uploads,
+ });
+ expect(
+ database.mutations.some(
+ ({ table, values }) =>
+ table === mocks.tables.jobs || values?.source !== undefined,
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it("does not discard an invalid proof while adopting an old completion", async () => {
+ const database = databaseFixture(null);
+ const response = await request({
+ jobId: "legacy-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ recordingVerification: {
+ request: { ...verification, version: 2 },
+ fullDecode: true,
+ },
+ });
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ expect(database.mutations).toEqual([]);
+ });
+
+ it("updates only the current attempt's progress without treating it as completed", async () => {
+ const database = databaseFixture();
+ const response = await request({
+ ...fixture().payload,
+ phase: "processing",
+ progress: 42,
+ message: "Verifying source media",
+ });
+ expect(response.status).toBe(200);
+ expect(database.mutations).toContainEqual(
+ expect.objectContaining({
+ table: mocks.tables.uploads,
+ values: expect.objectContaining({
+ phase: "processing",
+ processingProgress: 42,
+ }),
+ }),
+ );
+ expect(
+ database.mutations.some(({ table }) => table === mocks.tables.videos),
+ ).toBe(false);
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ });
+
+ it("does not let an unfenced old worker replace a managed recording", async () => {
+ const database = databaseFixture();
+ const response = await request({
+ jobId: "legacy-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ metadata,
+ });
+ expect(response.status).toBe(200);
+ expect(database.mutations).toEqual([]);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ expect(mocks.head).not.toHaveBeenCalled();
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ });
+
+ it("never falls back to canonical publication if legacy source adoption fails", async () => {
+ const database = databaseFixture(null);
+ mocks.queue.mockRejectedValueOnce(new Error("Durable queue unavailable"));
+ expect(
+ (
+ await request({
+ jobId: "legacy-worker",
+ videoId,
+ phase: "complete",
+ progress: 100,
+ })
+ ).status,
+ ).toBe(500);
+ expect(database.mutations).toEqual([]);
+ expect(mocks.transcribe).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/multipart-upload-utils.test.ts b/apps/web/__tests__/unit/multipart-upload-utils.test.ts
index 179488ef7..5a1f80681 100644
--- a/apps/web/__tests__/unit/multipart-upload-utils.test.ts
+++ b/apps/web/__tests__/unit/multipart-upload-utils.test.ts
@@ -52,4 +52,18 @@ describe("multipart upload utils", () => {
}),
).toThrow("Video id not found");
});
+
+ it("rejects writes into retained sources and immutable outputs", () => {
+ for (const subpath of [
+ ".recording/sources/generation/snapshot/video/0.mp4",
+ ".recording/outputs/generation/attempt.mp4",
+ ]) {
+ expect(() =>
+ getMultipartFileKey("owner", { videoId: "video", subpath }),
+ ).toThrow("Recording snapshots are immutable");
+ expect(() =>
+ getMultipartFileKey("owner", { fileKey: `owner/video/${subpath}` }),
+ ).toThrow("Recording snapshots are immutable");
+ }
+ });
});
diff --git a/apps/web/__tests__/unit/recording-complete.test.ts b/apps/web/__tests__/unit/recording-complete.test.ts
index cb8b9c6c4..56cdc8e09 100644
--- a/apps/web/__tests__/unit/recording-complete.test.ts
+++ b/apps/web/__tests__/unit/recording-complete.test.ts
@@ -1,8 +1,11 @@
+import { MySqlDialect } from "drizzle-orm/mysql-core";
import type { Context, Next } from "hono";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
rows: [] as unknown[][],
+ userId: "owner" as string | null,
+ where: vi.fn(),
queue: vi.fn(),
verify: vi.fn(),
validate: vi.fn(),
@@ -10,21 +13,21 @@ const mocks = vi.hoisted(() => ({
vi.mock("@cap/database", () => ({
db: () => ({
- select: () => ({
- from: () => ({ where: async () => mocks.rows.shift() ?? [] }),
- }),
+ select: () => ({ from: () => ({ where: mocks.where }) }),
}),
}));
vi.mock("@cap/database/schema", () => ({
videos: { id: "id", ownerId: "ownerId" },
videoUploads: { videoId: "videoId", phase: "phase" },
+ videoProcessingJobs: { videoId: "videoId" },
}));
vi.mock("@cap/web-domain", () => ({
Video: { VideoId: { make: (id: string) => id } },
}));
vi.mock("@/app/api/utils", () => ({
withAuth: async (context: Context, next: Next) => {
- context.set("user", { id: "owner" });
+ if (!mocks.userId) return context.json({ error: "Unauthorized" }, 401);
+ context.set("user", { id: mocks.userId });
await next();
},
}));
@@ -37,6 +40,10 @@ vi.mock("@/lib/desktop-recording-upload-status", () => ({
}));
import { app } from "@/app/api/upload/[...route]/recording-complete";
+import {
+ DesktopRecordingSourceBlockedError,
+ SourceCommitPendingError,
+} from "@/lib/desktop-recording-jobs";
const verification = {
version: 1,
@@ -44,111 +51,162 @@ const verification = {
requiredAudio: true,
};
-function request(verify = true) {
+async function request(body: unknown = { videoId: "recording", verification }) {
return app.request("/", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- videoId: "recording",
- ...(verify ? { verification } : {}),
- }),
+ body: JSON.stringify(body),
});
}
+function setSource(type: "desktopMP4" | "desktopSegments" | "local") {
+ mocks.rows[0] = [{ id: "recording", ownerId: "owner", source: { type } }];
+}
+
describe("recording completion acknowledgement", () => {
beforeEach(() => {
- mocks.rows = [
- [{ id: "recording", ownerId: "owner", source: { type: "desktopMP4" } }],
- [],
- ];
- mocks.queue.mockResolvedValue("queued");
- mocks.verify.mockResolvedValue(null);
- mocks.validate.mockResolvedValue(undefined);
+ mocks.rows = [[], []];
+ setSource("desktopMP4");
+ mocks.userId = "owner";
+ mocks.where.mockImplementation(async () => mocks.rows.shift() ?? []);
+ mocks.queue.mockReset().mockResolvedValue("queued");
+ mocks.verify.mockReset().mockResolvedValue(null);
+ mocks.validate.mockReset().mockResolvedValue(undefined);
+ vi.spyOn(console, "error").mockImplementation(() => undefined);
});
- it("preserves the legacy client acknowledgement without granting verified cleanup", async () => {
- const response = await request(false);
- expect(await response.json()).toEqual({
- success: true,
- status: "already-complete",
- });
- expect(mocks.queue).not.toHaveBeenCalled();
- });
+ it.each([false, true])(
+ "returns a retryable non-2xx until the source is secured (proof: %s)",
+ async (hasProof) => {
+ mocks.queue.mockRejectedValueOnce(new SourceCommitPendingError());
+ const response = await request({
+ videoId: "recording",
+ ...(hasProof ? { verification } : {}),
+ });
+ expect(response.status).toBe(503);
+ expect(response.headers.get("Retry-After")).toBe("5");
+ expect(await response.json()).toMatchObject({
+ success: false,
+ status: "source-commit-pending",
+ });
+ expect(mocks.queue).toHaveBeenCalledWith({
+ videoId: "recording",
+ userId: "owner",
+ verification: hasProof ? verification : undefined,
+ });
+ },
+ );
- it("reconciles a legacy completed upload missing its verification receipt", async () => {
- const response = await request();
- expect(await response.json()).toEqual({ success: true, status: "queued" });
- expect(mocks.validate).toHaveBeenCalledOnce();
- expect(mocks.queue).toHaveBeenCalledWith({
- videoId: "recording",
- userId: "owner",
- verification,
+ it.each([
+ ["processing", false],
+ ["processing", true],
+ ["error", false],
+ ["error", true],
+ ["complete", false],
+ ["complete", true],
+ ])(
+ "does not acknowledge from an old %s upload row (proof: %s)",
+ async (phase, hasProof) => {
+ mocks.rows[1] = [{ videoId: "recording", phase }];
+ mocks.queue.mockRejectedValueOnce(new SourceCommitPendingError());
+ const response = await request({
+ videoId: "recording",
+ ...(hasProof ? { verification } : {}),
+ });
+ expect(response.status).toBe(503);
+ expect(mocks.queue).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("waits for the source queue before acknowledging a legacy client", async () => {
+ let release: (() => void) | undefined;
+ const committed = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ mocks.queue.mockImplementation(async () => {
+ await committed;
+ return "queued";
});
+ let settled = false;
+ const pending = request({ videoId: "recording" }).then((response) => {
+ settled = true;
+ return response;
+ });
+ await vi.waitFor(() => expect(mocks.queue).toHaveBeenCalledOnce());
+ expect(settled).toBe(false);
+ if (!release) throw new Error("Missing source commit resolver");
+ release();
+ const response = await pending;
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ success: true, status: "queued" });
+ expect(mocks.verify).not.toHaveBeenCalled();
});
- it("does not enqueue a second job while verification is processing", async () => {
+ it("attaches a late proof even when the earlier upload row says processing", async () => {
+ setSource("desktopSegments");
mocks.rows[1] = [{ videoId: "recording", phase: "processing" }];
+ mocks.queue.mockResolvedValueOnce("already-processing");
const response = await request();
+ expect(response.status).toBe(200);
expect(await response.json()).toEqual({
success: true,
status: "already-processing",
});
- expect(mocks.queue).not.toHaveBeenCalled();
+ expect(mocks.validate).toHaveBeenCalledOnce();
+ expect(mocks.queue).toHaveBeenCalledWith({
+ videoId: "recording",
+ userId: "owner",
+ verification,
+ });
+ expect(mocks.verify).not.toHaveBeenCalled();
});
- it("queues verification after upload bytes finish but the progress row remains", async () => {
- mocks.rows[1] = [{ videoId: "recording", phase: "uploading" }];
- const response = await request();
+ it("retries processing after an old worker error when the source is secured", async () => {
+ mocks.rows[1] = [{ videoId: "recording", phase: "error" }];
+ const response = await request({ videoId: "recording" });
+ expect(response.status).toBe(200);
expect(await response.json()).toEqual({ success: true, status: "queued" });
expect(mocks.queue).toHaveBeenCalledOnce();
});
- it("validates required tracks before finalizing a segmented upload", async () => {
- mocks.rows[0] = [
- {
- id: "recording",
- ownerId: "owner",
- source: { type: "desktopSegments" },
- },
- ];
- mocks.validate.mockRejectedValueOnce(new Error("Missing final audio"));
- const response = await request();
- expect(response.status).toBe(503);
- expect(mocks.queue).not.toHaveBeenCalled();
- });
-
- it("requests retransmission after a segmented upload failed verification", async () => {
- mocks.rows[0] = [
- {
- id: "recording",
- ownerId: "owner",
- source: { type: "desktopSegments" },
- },
- ];
- mocks.rows[1] = [{ videoId: "recording", phase: "error" }];
- const response = await request();
- expect(response.status).toBe(409);
- expect(mocks.queue).not.toHaveBeenCalled();
- });
+ it.each([false, true])(
+ "requests retransmission only for a confirmed blocked source (proof: %s)",
+ async (hasProof) => {
+ mocks.queue.mockRejectedValueOnce(
+ new DesktopRecordingSourceBlockedError(
+ "source-missing",
+ "The final video segment is missing",
+ ),
+ );
+ const response = await request({
+ videoId: "recording",
+ ...(hasProof ? { verification } : {}),
+ });
+ expect(response.status).toBe(409);
+ expect(response.headers.get("Retry-After")).toBeNull();
+ expect(await response.json()).toEqual({
+ success: false,
+ status: "reupload-required",
+ code: "source-missing",
+ error: "The final video segment is missing",
+ });
+ },
+ );
- it("asks for retransmission when a completed remote recording failed validation", async () => {
- mocks.rows[1] = [{ videoId: "recording", phase: "error" }];
+ it("keeps local data when required-track validation is unavailable", async () => {
+ setSource("desktopSegments");
+ mocks.validate.mockRejectedValueOnce(new Error("Storage unavailable"));
const response = await request();
- expect(response.status).toBe(409);
- expect(await response.json()).toEqual({
+ expect(response.status).toBe(503);
+ expect(response.headers.get("Retry-After")).toBe("5");
+ expect(await response.json()).toMatchObject({
success: false,
- status: "reupload-required",
+ error: expect.stringContaining("retain the local recording"),
});
- });
-
- it("does not issue a ready receipt when verification or manifest validation fails", async () => {
- mocks.validate.mockRejectedValueOnce(new Error("Missing final audio"));
- const response = await request();
- expect(response.status).toBe(503);
expect(mocks.queue).not.toHaveBeenCalled();
});
- it("returns only the verified result for the owned recording", async () => {
+ it("returns an existing verified receipt without starting another job", async () => {
const receipt = {
version: 1,
videoId: "recording",
@@ -165,6 +223,55 @@ describe("recording completion acknowledgement", () => {
status: "verified",
verification: receipt,
});
+ expect(mocks.validate).not.toHaveBeenCalled();
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("looks up the video using the authenticated owner, not a supplied owner", async () => {
+ mocks.rows[0] = [];
+ const response = await request({
+ videoId: "recording",
+ ownerId: "somebody-else",
+ verification,
+ });
+ expect(response.status).toBe(404);
+ const [condition] = mocks.where.mock.calls[0] ?? [];
+ if (!condition) throw new Error("Missing owned-video query");
+ expect(new MySqlDialect().sqlToQuery(condition).params).toEqual([
+ "id",
+ "recording",
+ "ownerId",
+ "owner",
+ ]);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it("rejects unauthenticated and non-desktop requests before queueing", async () => {
+ mocks.userId = null;
+ expect((await request()).status).toBe(401);
+ expect(mocks.where).not.toHaveBeenCalled();
+ mocks.userId = "owner";
+ setSource("local");
+ expect((await request()).status).toBe(400);
+ expect(mocks.queue).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ {},
+ { videoId: 123 },
+ { videoId: "recording", verification: null },
+ { videoId: "recording", verification: { ...verification, version: 2 } },
+ {
+ videoId: "recording",
+ verification: { ...verification, artifact: { kind: "segments" } },
+ },
+ {
+ videoId: "recording",
+ verification: { ...verification, requiredAudio: "true" },
+ },
+ ])("does not downgrade malformed completion proof %#", async (body) => {
+ expect((await request(body)).status).toBe(400);
+ expect(mocks.where).not.toHaveBeenCalled();
expect(mocks.queue).not.toHaveBeenCalled();
});
});
diff --git a/apps/web/__tests__/unit/recording-output.test.ts b/apps/web/__tests__/unit/recording-output.test.ts
new file mode 100644
index 000000000..0620e3602
--- /dev/null
+++ b/apps/web/__tests__/unit/recording-output.test.ts
@@ -0,0 +1,135 @@
+import {
+ getPublishedRecordingCopyKeys,
+ getPublishedRecordingOutputKey,
+ isInternalRecordingKey,
+ resolveRecordingObjectKey,
+} from "@cap/web-backend/src/Storage/recording-output";
+import { Video } from "@cap/web-domain";
+import { describe, expect, it } from "vitest";
+
+const prefix = "owner/video/";
+const outputKey = `${prefix}.recording/outputs/generation/attempt.mp4`;
+const thumbnailKey = `${prefix}.recording/outputs/generation/attempt/screenshot.jpg`;
+const previewKey = `${prefix}.recording/outputs/generation/attempt/preview.gif`;
+const video = {
+ id: "video",
+ ownerId: "owner",
+ source: { type: "desktopMP4", outputKey, thumbnailKey, previewKey },
+};
+
+describe("published recording storage keys", () => {
+ it("duplicates the verified output and current assets using new canonical keys", () => {
+ expect(getPublishedRecordingCopyKeys(video)).toEqual([
+ `${prefix}result.mp4`,
+ `${prefix}screenshot/screen-capture.jpg`,
+ `${prefix}preview/animated-preview.gif`,
+ ]);
+ expect(
+ getPublishedRecordingCopyKeys({
+ ...video,
+ source: { type: "desktopMP4" },
+ }),
+ ).toEqual([]);
+ });
+ it("resolves legacy playback, download, and media keys to one committed attempt", () => {
+ expect(
+ new Video.Mp4Source({
+ ownerId: video.ownerId,
+ videoId: video.id,
+ outputKey,
+ }).getFileKey(),
+ ).toBe(outputKey);
+ expect(resolveRecordingObjectKey(video, `${prefix}result.mp4`)).toBe(
+ outputKey,
+ );
+ expect(
+ resolveRecordingObjectKey(
+ video,
+ `${prefix}screenshot/screen-capture.jpg`,
+ ),
+ ).toBe(thumbnailKey);
+ expect(
+ resolveRecordingObjectKey(video, `${prefix}preview/animated-preview.gif`),
+ ).toBe(previewKey);
+ });
+
+ it("serves a retained MP4 snapshot without overwriting the uploaded original", () => {
+ const snapshot = `${prefix}.recording/sources/generation/snapshot/mp4/0.mp4`;
+ expect(
+ getPublishedRecordingOutputKey({
+ ...video,
+ source: { type: "desktopMP4", outputKey: snapshot },
+ }),
+ ).toBe(snapshot);
+ });
+
+ it.each([
+ "owner/other/.recording/outputs/generation/attempt.mp4",
+ "other/video/.recording/outputs/generation/attempt.mp4",
+ "owner/video/.recording/../result.mp4",
+ "owner/video/.recording/outputs/attempt.mp4?token=secret",
+ "owner/video/result.mp4",
+ "owner/video/.recording/outputs/attempt.json",
+ ])("rejects an invalid committed output pointer %s", (key) => {
+ const invalid = { ...video, source: { ...video.source, outputKey: key } };
+ expect(
+ new Video.Mp4Source({
+ ownerId: video.ownerId,
+ videoId: video.id,
+ outputKey: key,
+ }).getFileKey(),
+ ).toBe(`${prefix}result.mp4`);
+ expect(getPublishedRecordingOutputKey(invalid)).toBeUndefined();
+ expect(resolveRecordingObjectKey(invalid, `${prefix}result.mp4`)).toBe(
+ `${prefix}result.mp4`,
+ );
+ });
+
+ it("does not redirect other videos or raw recording fragments", () => {
+ for (const key of [
+ "owner/other/result.mp4",
+ `${prefix}segments/manifest.json`,
+ `${prefix}video/1.m4s`,
+ outputKey,
+ ]) {
+ expect(resolveRecordingObjectKey(video, key)).toBe(key);
+ }
+ });
+
+ it("does not redirect legacy or intentionally replaced recordings", () => {
+ for (const source of [
+ { type: "desktopMP4" },
+ { type: "desktopSegments", outputKey },
+ ]) {
+ expect(
+ resolveRecordingObjectKey({ ...video, source }, `${prefix}result.mp4`),
+ ).toBe(`${prefix}result.mp4`);
+ }
+ });
+
+ it.each([
+ "other/video/.recording/outputs/attempt/screenshot.jpg",
+ `${prefix}.recording/sources/snapshot/video/0.mp4`,
+ `${prefix}.recording/outputs/../screenshot.jpg`,
+ ])("does not alias an invalid thumbnail pointer %s", (key) => {
+ expect(
+ resolveRecordingObjectKey(
+ { ...video, source: { ...video.source, thumbnailKey: key } },
+ `${prefix}screenshot/screen-capture.jpg`,
+ ),
+ ).toBe(`${prefix}screenshot/screen-capture.jpg`);
+ });
+
+ it("reserves both retained sources and uncommitted attempt outputs", () => {
+ expect(isInternalRecordingKey(outputKey)).toBe(true);
+ expect(
+ isInternalRecordingKey(
+ `${prefix}.recording/sources/generation/inventory.json`,
+ ),
+ ).toBe(true);
+ expect(isInternalRecordingKey(`${prefix}result.mp4`)).toBe(false);
+ expect(isInternalRecordingKey(`${prefix}.recording-copy/result.mp4`)).toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts b/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts
new file mode 100644
index 000000000..b90707558
--- /dev/null
+++ b/apps/web/__tests__/unit/recording-storage-lifecycle.test.ts
@@ -0,0 +1,1648 @@
+import * as S3 from "@aws-sdk/client-s3";
+import * as Db from "@cap/database/schema";
+import {
+ CurrentUser,
+ DatabaseError,
+ type ImageUpload,
+ Organisation,
+ Storage as StorageDomain,
+ User,
+ Video,
+} from "@cap/web-domain";
+import type { SQL } from "drizzle-orm";
+import { MySqlDialect } from "drizzle-orm/mysql-core";
+import { Cause, Effect, Exit, Logger, Option, Schema } from "effect";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ database: vi.fn(),
+ bucketAccess: vi.fn(),
+ driveDelete: vi.fn(),
+ driveMetadata: vi.fn(),
+ driveCopy: vi.fn(),
+ driveText: vi.fn(),
+ driveFind: vi.fn(),
+ nextId: "duplicate-video",
+}));
+
+vi.mock("@cap/database", () => ({ db: mocks.database }));
+vi.mock("@cap/database/helpers", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@cap/database/helpers")>()),
+ nanoId: () => mocks.nextId,
+}));
+vi.mock("@cap/web-backend/src/S3Buckets/index.ts", async () => {
+ const { Effect } = await import("effect");
+ class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
+ sync: () => ({ getBucketAccess: mocks.bucketAccess }),
+ }) {}
+ return { S3Buckets };
+});
+vi.mock("@cap/web-backend/src/Tinybird/index.ts", async () => {
+ const { Effect } = await import("effect");
+ class Tinybird extends Effect.Service<Tinybird>()("Tinybird", {
+ sync: () => ({ querySql: () => Effect.succeed({ data: [] }) }),
+ }) {}
+ return { Tinybird };
+});
+vi.mock(
+ "@cap/web-backend/src/Storage/GoogleDrive.ts",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@cap/web-backend/src/Storage/GoogleDrive")
+ >()),
+ deleteGoogleDriveFile: mocks.driveDelete,
+ getGoogleDriveFileMetadata: mocks.driveMetadata,
+ copyGoogleDriveFile: mocks.driveCopy,
+ getGoogleDriveObjectText: mocks.driveText,
+ findGoogleDriveFileByObjectKey: mocks.driveFind,
+ }),
+);
+
+import { S3Buckets } from "@cap/web-backend/src/S3Buckets";
+import { createS3BucketAccess } from "@cap/web-backend/src/S3Buckets/S3BucketAccess";
+import { S3BucketClientProvider } from "@cap/web-backend/src/S3Buckets/S3BucketClientProvider";
+import { Storage } from "@cap/web-backend/src/Storage";
+import {
+ type copyGoogleDriveFile,
+ type GoogleDriveFile,
+ GoogleDriveRequestError,
+} from "@cap/web-backend/src/Storage/GoogleDrive";
+import { StorageRepo } from "@cap/web-backend/src/Storage/StorageRepo";
+import { Videos } from "@cap/web-backend/src/Videos";
+import { VideosRepo } from "@cap/web-backend/src/Videos/VideosRepo";
+
+const ownerId = User.UserId.make("owned-user");
+const videoId = Video.VideoId.make("owned-video");
+const orgId = Organisation.OrganisationId.make("owned-org");
+const prefix = `${ownerId}/${videoId}/`;
+const newPrefix = `${ownerId}/duplicate-video/`;
+const outputKey = `${prefix}.recording/outputs/generation/attempt.mp4`;
+const thumbnailKey = `${prefix}.recording/outputs/generation/attempt/screenshot.jpg`;
+const previewKey = `${prefix}.recording/outputs/generation/attempt/preview.gif`;
+const currentUser = {
+ id: ownerId,
+ email: "[email protected]",
+ activeOrganizationId: orgId,
+ iconUrlOrKey: Option.none<ImageUpload.ImageUrlOrKey>(),
+};
+
+function recording(
+ source: Video.Video["source"] = {
+ type: "desktopMP4",
+ outputKey,
+ thumbnailKey,
+ previewKey,
+ },
+) {
+ return Video.Video.make({
+ id: videoId,
+ ownerId,
+ orgId,
+ name: "Retained recording",
+ public: true,
+ source,
+ metadata: Option.some({
+ sourceName: "Test display",
+ desktopRecordingUpload: {
+ version: 1,
+ artifact: { kind: "segments", manifestSha256: "a".repeat(64) },
+ fileSize: 4096,
+ duration: 5,
+ hasAudio: true,
+ fullDecode: true,
+ requiredAudioVerified: true,
+ objectIdentity: '"old-output"',
+ outputKey,
+ },
+ }),
+ bucketId: Option.none(),
+ storageIntegrationId: Option.none(),
+ folderId: Option.none(),
+ transcriptionStatus: Option.none(),
+ width: Option.some(320),
+ height: Option.some(180),
+ duration: Option.some(5),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ });
+}
+
+type DatabaseMutation = {
+ operation: "insert" | "delete";
+ table: unknown;
+ id?: string;
+ values?: Record<string, unknown>;
+};
+
+function databaseFixture(video = recording()) {
+ const encoded = Schema.encodeSync(Video.Video)(video);
+ const original = {
+ ...encoded,
+ bucket: encoded.bucketId,
+ createdAt: video.createdAt,
+ updatedAt: video.updatedAt,
+ };
+ const rows = new Map<string, Record<string, unknown>>([[videoId, original]]);
+ const jobs = new Map<string, Record<string, unknown>>([
+ [
+ videoId,
+ {
+ videoId,
+ ownerId,
+ generation: "active-generation",
+ state: "processing",
+ },
+ ],
+ ]);
+ const uploads = new Map<string, typeof Db.videoUploads.$inferSelect>();
+ const mutations: DatabaseMutation[] = [];
+ const events: string[] = [];
+ let beforeJobDelete: (() => Promise<void>) | undefined;
+ let beforePrepareDelete: (() => Promise<void>) | undefined;
+ let loseNextCreateResponse = false;
+ const idFrom = (condition: SQL) => {
+ const id = new MySqlDialect().sqlToQuery(condition).params[0];
+ if (typeof id !== "string") throw new Error("Missing database video id");
+ return id;
+ };
+ const read = (table: unknown, condition: SQL) => {
+ const source =
+ table === Db.videos
+ ? rows
+ : table === Db.videoProcessingJobs
+ ? jobs
+ : null;
+ if (!source) throw new Error("Unexpected table read");
+ const row = source.get(idFrom(condition));
+ return row ? [structuredClone(row)] : [];
+ };
+ function transactionHandle(pending: DatabaseMutation[]) {
+ return {
+ select: () => ({
+ from: (table: unknown) => ({
+ where: (condition: SQL) => ({
+ for: async () => read(table, condition),
+ }),
+ }),
+ }),
+ delete: (table: unknown) => ({
+ where: async (condition: SQL) => {
+ const id = idFrom(condition);
+ if (table === Db.videoProcessingJobs) {
+ events.push("job-delete-request");
+ await beforeJobDelete?.();
+ events.push("job-delete-complete");
+ } else {
+ events.push("dependent-delete");
+ }
+ pending.push({ operation: "delete", table, id });
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ insert: (table: unknown) => ({
+ values: (
+ values: Record<string, unknown>[] | Record<string, unknown>,
+ ) => {
+ if (Array.isArray(values)) {
+ for (const value of values) {
+ pending.push({ operation: "insert", table, values: value });
+ }
+ return Promise.resolve([{ affectedRows: 1 }]);
+ }
+ return {
+ onDuplicateKeyUpdate: async ({
+ set,
+ }: {
+ set: Record<string, unknown>;
+ }) => {
+ events.push("job-fence-request");
+ await beforePrepareDelete?.();
+ const id = values.videoId;
+ if (typeof id !== "string")
+ throw new Error("Missing retired job id");
+ pending.push({
+ operation: "insert",
+ table,
+ values: jobs.has(id) ? { ...jobs.get(id), ...set } : values,
+ });
+ return [{ affectedRows: 1 }];
+ },
+ };
+ },
+ }),
+ };
+ }
+ const transaction = vi.fn(
+ async (
+ operation: (tx: ReturnType<typeof transactionHandle>) => Promise<unknown>,
+ ) => {
+ const pending: DatabaseMutation[] = [];
+ const result = await operation(transactionHandle(pending));
+ for (const mutation of pending) {
+ mutations.push(mutation);
+ const table =
+ mutation.table === Db.videos
+ ? rows
+ : mutation.table === Db.videoProcessingJobs
+ ? jobs
+ : null;
+ if (!table) continue;
+ if (mutation.operation === "delete" && mutation.id)
+ table.delete(mutation.id);
+ if (mutation.operation === "insert" && mutation.values) {
+ const id =
+ mutation.table === Db.videos
+ ? mutation.values.id
+ : mutation.values.videoId;
+ if (typeof id !== "string") throw new Error("Missing inserted id");
+ table.set(id, mutation.values);
+ }
+ }
+ if (
+ loseNextCreateResponse &&
+ pending.some(
+ ({ operation, table }) =>
+ operation === "insert" && table === Db.videos,
+ )
+ ) {
+ loseNextCreateResponse = false;
+ throw new Error("Committed video creation response was lost");
+ }
+ return result;
+ },
+ );
+ mocks.database.mockReturnValue({
+ select: () => ({
+ from: (table: unknown) => ({
+ where: async (condition: SQL) => read(table, condition),
+ leftJoin: (joined: unknown) => ({
+ where: async (condition: SQL) => {
+ if (table !== Db.videoUploads || joined !== Db.videoProcessingJobs)
+ throw new Error("Unexpected joined progress read");
+ const id = idFrom(condition);
+ const upload = uploads.get(id);
+ return upload
+ ? [{ ...upload, processingJobState: jobs.get(id)?.state ?? null }]
+ : [];
+ },
+ }),
+ }),
+ }),
+ delete: (table: unknown) => ({
+ where: async () => {
+ if (table !== Db.storageObjects)
+ throw new Error("Unexpected direct delete");
+ return [{ affectedRows: 1 }];
+ },
+ }),
+ transaction,
+ });
+ return {
+ rows,
+ jobs,
+ uploads,
+ mutations,
+ events,
+ transaction,
+ beforeJobDelete: (callback: () => Promise<void>) => {
+ beforeJobDelete = callback;
+ },
+ beforePrepareDelete: (callback: () => Promise<void>) => {
+ beforePrepareDelete = callback;
+ },
+ loseNextCreateResponse: () => {
+ loseNextCreateResponse = true;
+ },
+ };
+}
+
+const clients: S3.S3Client[] = [];
+
+async function storageFixture(seed: Iterable<readonly [string, string]>) {
+ const objects = new Map(seed);
+ const sizes = new Map(
+ [...objects].map(([key, value]) => [key, value.length]),
+ );
+ const identities = new Map(
+ [...objects.keys()].map((key, index) => [key, `"source-${index}"`]),
+ );
+ const requests: Array<{
+ operation:
+ | "copy"
+ | "list"
+ | "delete"
+ | "head"
+ | "multipart-create"
+ | "multipart-part"
+ | "multipart-complete"
+ | "multipart-abort";
+ source?: string;
+ key?: string;
+ keys?: string[];
+ token?: string;
+ }> = [];
+ const copyInputs: S3.CopyObjectCommandInput[] = [];
+ const partInputs: S3.UploadPartCopyCommandInput[] = [];
+ const completeInputs: S3.CompleteMultipartUploadCommandInput[] = [];
+ const createInputs: S3.CreateMultipartUploadCommandInput[] = [];
+ const uploads = new Map<
+ string,
+ {
+ key: string;
+ parts: Map<
+ number,
+ { source: string; start: number; end: number; etag: string }
+ >;
+ }
+ >();
+ const deniedDeletes = new Set<string>();
+ let copyFailure: string | undefined;
+ let listFailure: string | undefined;
+ let failedPart: number | undefined;
+ let malformedPagination: "missing" | "repeated" | undefined;
+ let beforeDelete: (() => void) | undefined;
+ let beforeCopy: (() => void) | undefined;
+ let afterCopy: (() => void) | undefined;
+ const client = new S3.S3Client({
+ credentials: { accessKeyId: "test-key", secretAccessKey: "test-secret" },
+ endpoint: "http://storage.test",
+ region: "us-east-1",
+ forcePathStyle: true,
+ });
+ clients.push(client);
+ const sourceKeyFrom = (source: string | undefined) => {
+ if (!source?.startsWith("test-bucket/"))
+ throw new Error("Invalid copy source");
+ return decodeURIComponent(source.slice("test-bucket/".length));
+ };
+ const copy = (
+ sourceKey: string,
+ key: string,
+ size: number,
+ identity: string,
+ ) => {
+ const content = objects.get(sourceKey);
+ if (content === undefined) throw new Error("Copy source not found");
+ objects.set(key, content);
+ sizes.set(key, size);
+ identities.set(key, identity);
+ afterCopy?.();
+ };
+ vi.spyOn(client, "send").mockImplementation(async (command) => {
+ if (command instanceof S3.HeadObjectCommand) {
+ const key = command.input.Key;
+ if (!key || !objects.has(key)) throw new Error("Object not found");
+ requests.push({ operation: "head", key });
+ return {
+ ContentLength: sizes.get(key),
+ ETag: identities.get(key),
+ ContentType: "video/mp4",
+ Metadata: { recording: "retained" },
+ $metadata: {},
+ };
+ }
+ if (command instanceof S3.CopyObjectCommand) {
+ const sourceKey = sourceKeyFrom(command.input.CopySource);
+ const key = command.input.Key;
+ if (!key) throw new Error("Missing copy destination");
+ beforeCopy?.();
+ requests.push({ operation: "copy", source: sourceKey, key });
+ copyInputs.push(command.input);
+ if (key === copyFailure) throw new Error("Copy unavailable");
+ if (command.input.CopySourceIfMatch !== identities.get(sourceKey))
+ throw new Error("Source precondition failed");
+ const size = sizes.get(sourceKey);
+ if (size === undefined || size > 5 * 1024 ** 3)
+ throw new Error("Single-copy size limit");
+ const identity = `"copied-${key}"`;
+ copy(sourceKey, key, size, identity);
+ return { CopyObjectResult: { ETag: identity }, $metadata: {} };
+ }
+ if (command instanceof S3.CreateMultipartUploadCommand) {
+ const key = command.input.Key;
+ if (!key) throw new Error("Missing multipart destination");
+ beforeCopy?.();
+ const UploadId = `copy-upload-${createInputs.length}`;
+ createInputs.push(command.input);
+ uploads.set(UploadId, { key, parts: new Map() });
+ requests.push({ operation: "multipart-create", key });
+ return { UploadId, $metadata: {} };
+ }
+ if (command instanceof S3.UploadPartCopyCommand) {
+ const {
+ Key: key,
+ UploadId: uploadId,
+ PartNumber: partNumber,
+ } = command.input;
+ const upload = uploadId ? uploads.get(uploadId) : undefined;
+ const sourceKey = sourceKeyFrom(command.input.CopySource);
+ if (!upload || upload.key !== key || !partNumber)
+ throw new Error("Invalid multipart part");
+ partInputs.push(command.input);
+ requests.push({ operation: "multipart-part", key, source: sourceKey });
+ if (partNumber === failedPart) throw new Error("Part copy unavailable");
+ if (command.input.CopySourceIfMatch !== identities.get(sourceKey))
+ throw new Error("Source precondition failed");
+ const range = /^bytes=(\d+)-(\d+)$/.exec(
+ command.input.CopySourceRange ?? "",
+ );
+ if (!range) throw new Error("Missing part range");
+ const start = Number(range[1]);
+ const end = Number(range[2]);
+ const etag = `"part-${partNumber}"`;
+ upload.parts.set(partNumber, { source: sourceKey, start, end, etag });
+ return { CopyPartResult: { ETag: etag }, $metadata: {} };
+ }
+ if (command instanceof S3.CompleteMultipartUploadCommand) {
+ const { Key: key, UploadId: uploadId } = command.input;
+ const upload = uploadId ? uploads.get(uploadId) : undefined;
+ if (
+ !key ||
+ !upload ||
+ command.input.IfNoneMatch !== "*" ||
+ objects.has(key)
+ )
+ throw new Error("Invalid multipart completion");
+ completeInputs.push(command.input);
+ requests.push({ operation: "multipart-complete", key });
+ let position = 0;
+ let sourceKey: string | undefined;
+ for (const [index, completed] of (
+ command.input.MultipartUpload?.Parts ?? []
+ ).entries()) {
+ const part = upload.parts.get(index + 1);
+ if (
+ !part ||
+ completed.PartNumber !== index + 1 ||
+ completed.ETag !== part.etag ||
+ part.start !== position
+ )
+ throw new Error("Incomplete multipart sequence");
+ position = part.end + 1;
+ sourceKey = part.source;
+ }
+ if (!sourceKey || position !== sizes.get(sourceKey))
+ throw new Error("Incomplete multipart copy");
+ const identity = '"multipart-output-etag"';
+ copy(sourceKey, key, position, identity);
+ if (uploadId) uploads.delete(uploadId);
+ return { ETag: identity, $metadata: {} };
+ }
+ if (command instanceof S3.AbortMultipartUploadCommand) {
+ if (command.input.UploadId) uploads.delete(command.input.UploadId);
+ requests.push({ operation: "multipart-abort", key: command.input.Key });
+ return { $metadata: {} };
+ }
+ if (command instanceof S3.ListObjectsV2Command) {
+ const token = command.input.ContinuationToken;
+ requests.push({ operation: "list", token });
+ if (token !== undefined && token === listFailure)
+ throw new Error("Listing unavailable");
+ const keys = [...objects.keys()]
+ .filter(
+ (key) =>
+ key.startsWith(command.input.Prefix ?? "") &&
+ (token === undefined || key > token),
+ )
+ .sort();
+ const page = keys.slice(0, 1000);
+ return {
+ Contents: page.map((Key) => ({ Key, Size: sizes.get(Key) })),
+ IsTruncated:
+ malformedPagination !== undefined || keys.length > page.length,
+ NextContinuationToken:
+ malformedPagination === "missing"
+ ? undefined
+ : malformedPagination === "repeated"
+ ? "repeated-token"
+ : keys.length > page.length
+ ? page.at(-1)
+ : undefined,
+ $metadata: {},
+ };
+ }
+ if (command instanceof S3.DeleteObjectsCommand) {
+ beforeDelete?.();
+ const keys = (command.input.Delete?.Objects ?? [])
+ .map((object) => object.Key)
+ .filter((key): key is string => key !== undefined);
+ requests.push({ operation: "delete", keys });
+ for (const key of keys) {
+ if (!deniedDeletes.has(key)) {
+ objects.delete(key);
+ sizes.delete(key);
+ identities.delete(key);
+ }
+ }
+ return {
+ Deleted: keys
+ .filter((key) => !deniedDeletes.has(key))
+ .map((Key) => ({ Key })),
+ Errors: keys
+ .filter((key) => deniedDeletes.has(key))
+ .map((Key) => ({ Key, Code: "AccessDenied" })),
+ $metadata: {},
+ };
+ }
+ throw new Error("Unexpected S3 request");
+ });
+ const access = await Effect.runPromise(
+ createS3BucketAccess.pipe(
+ Effect.provideService(S3BucketClientProvider, {
+ bucket: "test-bucket",
+ getInternal: Effect.succeed(client),
+ getPublic: Effect.succeed(client),
+ isPathStyle: true,
+ }),
+ ),
+ );
+ mocks.bucketAccess.mockReturnValue(Effect.succeed([access, Option.none()]));
+ return {
+ objects,
+ sizes,
+ identities,
+ requests,
+ copyInputs,
+ partInputs,
+ completeInputs,
+ createInputs,
+ uploads,
+ deniedDeletes,
+ failCopy: (key: string) => {
+ copyFailure = key;
+ },
+ failList: (token: string) => {
+ listFailure = token;
+ },
+ failPart: (partNumber: number) => {
+ failedPart = partNumber;
+ },
+ malformedPagination: (kind: "missing" | "repeated") => {
+ malformedPagination = kind;
+ },
+ beforeDelete: (callback: () => void) => {
+ beforeDelete = callback;
+ },
+ beforeCopy: (callback: () => void) => {
+ beforeCopy = callback;
+ },
+ afterCopy: (callback: () => void) => {
+ afterCopy = callback;
+ },
+ };
+}
+
+async function driveFixture() {
+ databaseFixture();
+ const integrationId =
+ StorageDomain.StorageIntegrationId.make("drive-integration");
+ const now = new Date();
+ const integration: typeof Db.storageIntegrations.$inferSelect = {
+ id: integrationId,
+ ownerId,
+ organizationId: orgId,
+ provider: "googleDrive",
+ displayName: "Test Drive",
+ status: "active",
+ active: true,
+ encryptedConfig: "unused-encrypted-fixture",
+ googleDriveAccessToken: null,
+ googleDriveAccessTokenExpiresAt: null,
+ googleDriveTokenRefreshLeaseId: null,
+ googleDriveTokenRefreshLeaseExpiresAt: null,
+ googleDriveStorageQuotaCache: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const original: typeof Db.storageObjects.$inferSelect = {
+ id: StorageDomain.StorageObjectId.make("source-object"),
+ integrationId,
+ ownerId,
+ videoId,
+ objectKey: outputKey,
+ objectKeyHash: "a".repeat(64),
+ providerObjectId: "original-file",
+ uploadSessionUrl: null,
+ uploadStatus: "complete",
+ contentType: "video/mp4",
+ contentLength: 10,
+ metadata: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+ const records = new Map([[outputKey, original]]);
+ const files = new Map<string, GoogleDriveFile>([
+ [
+ "original-file",
+ { id: "original-file", version: "1", size: "10", mimeType: "video/mp4" },
+ ],
+ ]);
+ const repo = await Effect.runPromise(
+ StorageRepo.pipe(Effect.provide(StorageRepo.Default)),
+ );
+ vi.spyOn(repo, "getIntegrationById").mockReturnValue(
+ Effect.succeed(Option.some(integration)),
+ );
+ vi.spyOn(repo, "getGoogleDriveConfig").mockReturnValue(
+ Effect.succeed({
+ refreshToken: "fixture-token",
+ folderId: "fixture-folder",
+ }),
+ );
+ const getIndex = vi
+ .spyOn(repo, "getObjectByKey")
+ .mockImplementation((_integration, key) =>
+ Effect.sync(() => Option.fromNullable(records.get(key))),
+ );
+ const upsertIndex = vi
+ .spyOn(repo, "upsertObject")
+ .mockImplementation((input) =>
+ Effect.sync(() => {
+ records.set(input.objectKey, {
+ ...(records.get(input.objectKey) ?? original),
+ objectKey: input.objectKey,
+ providerObjectId: input.providerObjectId,
+ contentType: input.contentType ?? null,
+ contentLength: input.contentLength ?? null,
+ metadata: input.metadata ?? null,
+ });
+ }),
+ );
+ const deleteFromRepo = repo.deleteObjectByKey;
+ const deleteIndex = vi
+ .spyOn(repo, "deleteObjectByKey")
+ .mockImplementation((...args) =>
+ deleteFromRepo(...args).pipe(
+ Effect.tap(() => Effect.sync(() => records.delete(args[1]))),
+ ),
+ );
+ mocks.driveDelete.mockReset().mockReturnValue(Effect.void);
+ mocks.driveText
+ .mockReset()
+ .mockReturnValue(Effect.succeed("fixture-recording-text"));
+ mocks.driveFind
+ .mockReset()
+ .mockReturnValue(Effect.succeed(Option.none<GoogleDriveFile>()));
+ mocks.driveMetadata
+ .mockReset()
+ .mockImplementation((_config: unknown, fileId: string) =>
+ Effect.sync(() => {
+ const file = files.get(fileId);
+ if (!file) throw new Error("Missing Google Drive file fixture");
+ return { ...file };
+ }),
+ );
+ mocks.driveCopy
+ .mockReset()
+ .mockImplementation(
+ ({ input, sourceFileId }: Parameters<typeof copyGoogleDriveFile>[0]) =>
+ Effect.sync(() => {
+ const source = files.get(sourceFileId);
+ if (!source)
+ throw new Error("Missing Google Drive copy source fixture");
+ files.set("copied-file", {
+ ...source,
+ id: "copied-file",
+ version: "1",
+ });
+ records.set(input.key, {
+ ...original,
+ id: StorageDomain.StorageObjectId.make("copied-object"),
+ objectKey: input.key,
+ providerObjectId: "copied-file",
+ });
+ }),
+ );
+ const video = Video.Video.make({
+ ...recording({ type: "desktopMP4", outputKey }),
+ storageIntegrationId: Option.some(integrationId),
+ });
+ const [access] = await Effect.runPromise(
+ Effect.flatMap(Storage, (storage) => storage.getAccessForVideo(video)).pipe(
+ Effect.provide(Storage.DefaultWithoutDependencies),
+ Effect.provideService(StorageRepo, repo),
+ Effect.provide(S3Buckets.Default),
+ ),
+ );
+ return {
+ access,
+ records,
+ files,
+ integrationId,
+ deleteIndex,
+ getIndex,
+ upsertIndex,
+ };
+}
+
+function runVideoOperation(
+ operation: "duplicate" | "delete",
+ userId = ownerId,
+) {
+ return Effect.runPromiseExit(
+ Effect.gen(function* () {
+ const videos = yield* Videos;
+ return yield* videos[operation](videoId);
+ }).pipe(
+ Effect.provide(Videos.Default),
+ Effect.provideService(CurrentUser, { ...currentUser, id: userId }),
+ Effect.provide(Logger.remove(Logger.defaultLogger)),
+ ),
+ );
+}
+
+beforeEach(() => {
+ mocks.nextId = "duplicate-video";
+});
+
+afterEach(() => {
+ for (const client of clients.splice(0)) client.destroy();
+});
+
+describe("recording storage lifecycle", () => {
+ it.each([
+ "committing",
+ "queued",
+ "processing",
+ "retry",
+ "source-blocked",
+ null,
+ ] as const)(
+ "reports durable state %s without treating recoverable worker failures as final failures",
+ async (state) => {
+ const database = databaseFixture();
+ const previousUpdate = new Date(Date.now() - 60 * 60 * 1000);
+ database.uploads.set(videoId, {
+ videoId,
+ uploaded: 100,
+ total: 100,
+ startedAt: previousUpdate,
+ updatedAt: previousUpdate,
+ mode: "multipart",
+ phase: "error",
+ processingProgress: 50,
+ processingMessage: "Source retained",
+ processingError: "Previous processing attempt failed",
+ rawFileKey: null,
+ });
+ if (state) database.jobs.set(videoId, { state });
+ else database.jobs.delete(videoId);
+ const result = await Effect.runPromise(
+ Effect.flatMap(Videos, (videos) =>
+ videos.getUploadProgress(videoId),
+ ).pipe(
+ Effect.provide(Videos.Default),
+ Effect.provideService(CurrentUser, currentUser),
+ Effect.provide(Logger.remove(Logger.defaultLogger)),
+ ),
+ );
+ const progress = Option.getOrThrow(result);
+ expect(progress.updatedAt).toEqual(previousUpdate);
+ if (state === "source-blocked" || state === null) {
+ expect(progress.phase).toBe("error");
+ expect(progress.automaticRetry).toBe(false);
+ expect(progress.processingError).toEqual(
+ Option.some("Previous processing attempt failed"),
+ );
+ } else {
+ expect(progress.phase).toBe("processing");
+ expect(progress.automaticRetry).toBe(true);
+ expect(progress.processingError).toEqual(Option.none());
+ }
+ },
+ );
+
+ it("duplicates the published video and hidden assets into canonical destinations", async () => {
+ const database = databaseFixture();
+ const storage = await storageFixture([
+ [outputKey, "verified-video"],
+ [thumbnailKey, "verified-thumbnail"],
+ [previewKey, "verified-preview"],
+ [`${prefix}result.mp4`, "stale-canonical-video"],
+ [`${prefix}screenshot/screen-capture.jpg`, "stale-thumbnail"],
+ ]);
+ storage.beforeCopy(() =>
+ expect(database.rows.has("duplicate-video")).toBe(false),
+ );
+ const result = await runVideoOperation("duplicate");
+ expect(Exit.isSuccess(result)).toBe(true);
+ expect(storage.objects.get(`${newPrefix}result.mp4`)).toBe(
+ "verified-video",
+ );
+ expect(
+ storage.objects.get(`${newPrefix}screenshot/screen-capture.jpg`),
+ ).toBe("verified-thumbnail");
+ expect(
+ storage.objects.get(`${newPrefix}preview/animated-preview.gif`),
+ ).toBe("verified-preview");
+ expect(database.rows.get("duplicate-video")).toMatchObject({
+ source: { type: "desktopMP4" },
+ metadata: { sourceName: "Test display" },
+ });
+ expect(database.rows.get("duplicate-video")?.metadata).not.toHaveProperty(
+ "desktopRecordingUpload",
+ );
+ expect(database.rows.get("owned-video")?.metadata).toHaveProperty(
+ "desktopRecordingUpload",
+ );
+ expect(
+ storage.requests.filter(({ operation }) => operation === "copy"),
+ ).toEqual([
+ { operation: "copy", source: outputKey, key: `${newPrefix}result.mp4` },
+ {
+ operation: "copy",
+ source: thumbnailKey,
+ key: `${newPrefix}screenshot/screen-capture.jpg`,
+ },
+ {
+ operation: "copy",
+ source: previewKey,
+ key: `${newPrefix}preview/animated-preview.gif`,
+ },
+ ]);
+ });
+
+ it("does not duplicate source inventories, raw fragments, or comment attachments across pages", async () => {
+ const database = databaseFixture();
+ const retained = Array.from(
+ { length: 1100 },
+ (_, index) =>
+ [
+ `${prefix}.recording/sources/generation/snapshot/video/${String(index).padStart(5, "0")}.m4s`,
+ "source-fragment",
+ ] as const,
+ );
+ const storage = await storageFixture([
+ ...retained,
+ [outputKey, "verified-video"],
+ [thumbnailKey, "verified-thumbnail"],
+ [previewKey, "verified-preview"],
+ [
+ `${prefix}.recording/sources/generation/snapshot/inventory.json`,
+ "inventory",
+ ],
+ [
+ `${prefix}.recording/outputs/old-generation/old-attempt.mp4`,
+ "old-output",
+ ],
+ [`${prefix}segments/video/0.m4s`, "legacy-raw-fragment"],
+ [`${prefix}comments/comment/attachment.mp4`, "comment-attachment"],
+ [`${prefix}transcription.vtt`, "published-transcription"],
+ [`${prefix}chapter-data.json`, "published-chapters"],
+ ]);
+ const result = await runVideoOperation("duplicate");
+ expect(Exit.isSuccess(result)).toBe(true);
+ expect(
+ storage.requests.filter(({ operation }) => operation === "list"),
+ ).toHaveLength(2);
+ expect(
+ [...storage.objects.keys()]
+ .filter((key) => key.startsWith(newPrefix))
+ .sort(),
+ ).toEqual([
+ `${newPrefix}chapter-data.json`,
+ `${newPrefix}preview/animated-preview.gif`,
+ `${newPrefix}result.mp4`,
+ `${newPrefix}screenshot/screen-capture.jpg`,
+ `${newPrefix}transcription.vtt`,
+ ]);
+ expect(database.rows.get("duplicate-video")?.source).toEqual({
+ type: "desktopMP4",
+ });
+ expect(storage.objects.get(retained.at(-1)?.[0] ?? "")).toBe(
+ "source-fragment",
+ );
+ });
+
+ it("copies a published MP4 snapshot without retaining its original output pointer", async () => {
+ const snapshotKey = `${prefix}.recording/sources/generation/snapshot/mp4/0.mp4`;
+ const database = databaseFixture(
+ recording({ type: "desktopMP4", outputKey: snapshotKey }),
+ );
+ const storage = await storageFixture([
+ [snapshotKey, "verified-snapshot"],
+ [`${prefix}result.mp4`, "new-unverified-upload"],
+ ]);
+ expect(Exit.isSuccess(await runVideoOperation("duplicate"))).toBe(true);
+ expect(storage.objects.get(`${newPrefix}result.mp4`)).toBe(
+ "verified-snapshot",
+ );
+ expect(database.rows.get("duplicate-video")?.source).toEqual({
+ type: "desktopMP4",
+ });
+ expect(
+ storage.objects.has(
+ `${newPrefix}.recording/sources/generation/snapshot/mp4/0.mp4`,
+ ),
+ ).toBe(false);
+ });
+
+ it("preserves the legacy canonical MP4 copy contract without copying cleanup receipts", async () => {
+ const database = databaseFixture(recording({ type: "desktopMP4" }));
+ const storage = await storageFixture([
+ [`${prefix}result.mp4`, "legacy-recording"],
+ [`${prefix}screenshot/screen-capture.jpg`, "legacy-thumbnail"],
+ ]);
+ expect(Exit.isSuccess(await runVideoOperation("duplicate"))).toBe(true);
+ expect(storage.objects.get(`${newPrefix}result.mp4`)).toBe(
+ "legacy-recording",
+ );
+ expect(database.rows.get("duplicate-video")?.metadata).toEqual({
+ sourceName: "Test display",
+ });
+ });
+
+ it.each(["duplicate", "delete"] as const)(
+ "does not %s another owner's recording or media",
+ async (operation) => {
+ const database = databaseFixture();
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ const result = await runVideoOperation(
+ operation,
+ User.UserId.make("different-user"),
+ );
+ expect(Exit.isFailure(result)).toBe(true);
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(database.mutations).toEqual([]);
+ expect(storage.requests).toEqual([]);
+ },
+ );
+
+ it("waits for job deletion before deleting any dependent database row", async () => {
+ const database = databaseFixture();
+ let release: (() => void) | undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ database.beforeJobDelete(() => gate);
+ const pending = Effect.runPromise(
+ Effect.flatMap(VideosRepo, (repo) => repo.delete(videoId)).pipe(
+ Effect.provide(VideosRepo.Default),
+ ),
+ );
+ await vi.waitFor(() =>
+ expect(database.events).toEqual(["job-delete-request"]),
+ );
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(database.mutations).toEqual([]);
+ if (!release) throw new Error("Missing job deletion resolver");
+ release();
+ await pending;
+ expect(database.events.slice(0, 2)).toEqual([
+ "job-delete-request",
+ "job-delete-complete",
+ ]);
+ expect(database.mutations.at(0)?.table).toBe(Db.videoProcessingJobs);
+ expect(database.rows.has(videoId)).toBe(false);
+ });
+
+ it("keeps database rows and storage intact when retiring the worker fails", async () => {
+ const database = databaseFixture();
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ database.beforePrepareDelete(async () => {
+ throw new Error("Job retirement unavailable");
+ });
+ expect(Exit.isFailure(await runVideoOperation("delete"))).toBe(true);
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(database.mutations).toEqual([]);
+ expect(storage.requests).toEqual([]);
+ });
+
+ it("does not report successful deletion when S3 rejects a retained source object", async () => {
+ const database = databaseFixture();
+ const retainedKey = `${prefix}.recording/sources/generation/snapshot/video/0.m4s`;
+ const storage = await storageFixture([
+ [outputKey, "verified-video"],
+ [retainedKey, "retained-fragment"],
+ ]);
+ storage.deniedDeletes.add(retainedKey);
+ expect(Exit.isFailure(await runVideoOperation("delete"))).toBe(true);
+ expect(storage.objects.get(retainedKey)).toBe("retained-fragment");
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(database.jobs.get(videoId)).toMatchObject({
+ state: "source-blocked",
+ errorCode: "video-deleting",
+ });
+ storage.deniedDeletes.clear();
+ expect(Exit.isSuccess(await runVideoOperation("delete"))).toBe(true);
+ expect(database.rows.has(videoId)).toBe(false);
+ expect(database.jobs.has(videoId)).toBe(false);
+ expect(storage.objects.has(retainedKey)).toBe(false);
+ });
+
+ it("does not leave a published duplicate when copying its output fails", async () => {
+ const database = databaseFixture();
+ const storage = await storageFixture([
+ [outputKey, "verified-video"],
+ [thumbnailKey, "verified-thumbnail"],
+ [previewKey, "verified-preview"],
+ ]);
+ storage.failCopy(`${newPrefix}result.mp4`);
+ expect(Exit.isFailure(await runVideoOperation("duplicate"))).toBe(true);
+ expect(database.rows.has("duplicate-video")).toBe(false);
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(storage.objects.get(outputKey)).toBe("verified-video");
+ });
+
+ it("returns the copy failure without publishing when rollback cleanup also fails", async () => {
+ const database = databaseFixture();
+ const storage = await storageFixture([
+ [outputKey, "verified-video"],
+ [thumbnailKey, "verified-thumbnail"],
+ ]);
+ storage.failCopy(`${newPrefix}screenshot/screen-capture.jpg`);
+ storage.deniedDeletes.add(`${newPrefix}result.mp4`);
+ const result = await runVideoOperation("duplicate");
+ expect(Exit.isFailure(result)).toBe(true);
+ expect(database.rows.has("duplicate-video")).toBe(false);
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(storage.requests).toContainEqual(
+ expect.objectContaining({ operation: "delete" }),
+ );
+ expect(storage.objects.get(`${newPrefix}result.mp4`)).toBe(
+ "verified-video",
+ );
+ expect(storage.objects.get(outputKey)).toBe("verified-video");
+ });
+
+ it("keeps cloned media when video creation committed but its response was lost", async () => {
+ const database = databaseFixture(
+ recording({ type: "desktopMP4", outputKey }),
+ );
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ database.loseNextCreateResponse();
+ expect(Exit.isFailure(await runVideoOperation("duplicate"))).toBe(true);
+ expect(database.rows.has("duplicate-video")).toBe(true);
+ expect(storage.objects.get(`${newPrefix}result.mp4`)).toBe(
+ "verified-video",
+ );
+ expect(
+ storage.requests.filter(({ operation }) => operation === "delete"),
+ ).toEqual([]);
+ });
+
+ it("does not leave a partial duplicate when a later object listing fails", async () => {
+ const database = databaseFixture();
+ const retained = Array.from(
+ { length: 1100 },
+ (_, index) =>
+ [
+ `${prefix}.recording/sources/generation/snapshot/video/${String(index).padStart(5, "0")}.m4s`,
+ "fragment",
+ ] as const,
+ );
+ const storage = await storageFixture([
+ ...retained,
+ [outputKey, "verified-video"],
+ [thumbnailKey, "verified-thumbnail"],
+ [previewKey, "verified-preview"],
+ ]);
+ const firstPageEnd = [...storage.objects.keys()].sort().at(999);
+ if (!firstPageEnd) throw new Error("Missing pagination boundary");
+ storage.failList(firstPageEnd);
+ expect(Exit.isFailure(await runVideoOperation("duplicate"))).toBe(true);
+ expect(database.rows.has("duplicate-video")).toBe(false);
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(
+ [...storage.objects.keys()].some((key) => key.startsWith(newPrefix)),
+ ).toBe(false);
+ });
+
+ it("pins single-copy source identities and permits empty ancillary objects", async () => {
+ databaseFixture(recording({ type: "desktopMP4", outputKey }));
+ const ancillaryKey = `${prefix}empty.vtt`;
+ const storage = await storageFixture([
+ [outputKey, "verified-video"],
+ [ancillaryKey, ""],
+ ]);
+ expect(Exit.isSuccess(await runVideoOperation("duplicate"))).toBe(true);
+ expect(storage.copyInputs).toHaveLength(2);
+ expect(storage.copyInputs).toContainEqual(
+ expect.objectContaining({
+ CopySource: `test-bucket/${ancillaryKey}`,
+ CopySourceIfMatch: storage.identities.get(ancillaryKey),
+ }),
+ );
+ expect(storage.objects.get(`${newPrefix}empty.vtt`)).toBe("");
+ expect(storage.sizes.get(`${newPrefix}empty.vtt`)).toBe(0);
+ });
+
+ it("copies an 8 GiB recording in complete conditional server-side ranges", async () => {
+ const database = databaseFixture(
+ recording({ type: "desktopMP4", outputKey }),
+ );
+ const storage = await storageFixture([[outputKey, "large-verified-video"]]);
+ const fileSize = 8 * 1024 ** 3;
+ storage.sizes.set(outputKey, fileSize);
+ const sourceIdentity = storage.identities.get(outputKey);
+ expect(Exit.isSuccess(await runVideoOperation("duplicate"))).toBe(true);
+ expect(storage.copyInputs).toHaveLength(0);
+ expect(storage.createInputs).toEqual([
+ expect.objectContaining({
+ Key: `${newPrefix}result.mp4`,
+ ContentType: "video/mp4",
+ Metadata: { recording: "retained" },
+ }),
+ ]);
+ expect(storage.partInputs).toHaveLength(64);
+ let position = 0;
+ for (const [index, part] of storage.partInputs.entries()) {
+ expect(part.CopySourceIfMatch).toBe(sourceIdentity);
+ expect(part.CopySource).toBe(`test-bucket/${outputKey}`);
+ expect(part.PartNumber).toBe(index + 1);
+ const range = /^bytes=(\d+)-(\d+)$/.exec(part.CopySourceRange ?? "");
+ if (!range) throw new Error("Missing multipart range");
+ expect(Number(range[1])).toBe(position);
+ position = Number(range[2]) + 1;
+ }
+ expect(position).toBe(fileSize);
+ expect(storage.completeInputs).toEqual([
+ expect.objectContaining({
+ IfNoneMatch: "*",
+ MultipartUpload: {
+ Parts: Array.from({ length: 64 }, (_, index) => ({
+ PartNumber: index + 1,
+ ETag: `"part-${index + 1}"`,
+ })),
+ },
+ }),
+ ]);
+ expect(storage.sizes.get(`${newPrefix}result.mp4`)).toBe(fileSize);
+ expect(storage.identities.get(`${newPrefix}result.mp4`)).not.toBe(
+ sourceIdentity,
+ );
+ expect(database.rows.has("duplicate-video")).toBe(true);
+ expect(storage.uploads.size).toBe(0);
+ });
+
+ it("aborts a failed multipart copy without publishing or deleting the original", async () => {
+ const database = databaseFixture(
+ recording({ type: "desktopMP4", outputKey }),
+ );
+ const storage = await storageFixture([[outputKey, "large-verified-video"]]);
+ storage.sizes.set(outputKey, 8 * 1024 ** 3);
+ storage.failPart(2);
+ expect(Exit.isFailure(await runVideoOperation("duplicate"))).toBe(true);
+ expect(storage.completeInputs).toHaveLength(0);
+ expect(
+ storage.requests.filter(
+ ({ operation }) => operation === "multipart-abort",
+ ),
+ ).toHaveLength(1);
+ expect(storage.uploads.size).toBe(0);
+ expect(database.rows.has("duplicate-video")).toBe(false);
+ expect(storage.objects.get(outputKey)).toBe("large-verified-video");
+ });
+
+ it.each([
+ "source-changed",
+ "copy-truncated",
+ "copy-replaced",
+ "weak-source-identity",
+ ])("does not publish a duplicate with %s", async (reason) => {
+ const database = databaseFixture(
+ recording({ type: "desktopMP4", outputKey }),
+ );
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ if (reason === "source-changed")
+ storage.afterCopy(() =>
+ storage.identities.set(outputKey, '"replacement-source"'),
+ );
+ else if (reason === "copy-truncated")
+ storage.afterCopy(() => storage.sizes.set(`${newPrefix}result.mp4`, 1));
+ else if (reason === "copy-replaced")
+ storage.afterCopy(() =>
+ storage.identities.set(`${newPrefix}result.mp4`, '"unexpected-output"'),
+ );
+ else storage.identities.set(outputKey, 'W/"weak"');
+ expect(Exit.isFailure(await runVideoOperation("duplicate"))).toBe(true);
+ expect(database.rows.has("duplicate-video")).toBe(false);
+ expect(storage.objects.has(`${newPrefix}result.mp4`)).toBe(false);
+ expect(storage.objects.get(outputKey)).toBe("verified-video");
+ });
+
+ it.each([
+ { operation: "delete" as const, kind: "missing" as const },
+ { operation: "delete" as const, kind: "repeated" as const },
+ { operation: "duplicate" as const, kind: "missing" as const },
+ { operation: "duplicate" as const, kind: "repeated" as const },
+ ])(
+ "fails $operation safely on a $kind continuation token",
+ async ({ operation, kind }) => {
+ const database = databaseFixture(
+ recording({ type: "desktopMP4", outputKey }),
+ );
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ storage.malformedPagination(kind);
+ expect(Exit.isFailure(await runVideoOperation(operation))).toBe(true);
+ expect(
+ storage.requests.filter(({ operation }) => operation === "list"),
+ ).toHaveLength(kind === "missing" ? 1 : 2);
+ expect(database.rows.has(videoId)).toBe(true);
+ if (operation === "delete")
+ expect(database.jobs.get(videoId)?.errorCode).toBe("video-deleting");
+ else {
+ expect(database.rows.has("duplicate-video")).toBe(false);
+ expect(storage.objects.has(`${newPrefix}result.mp4`)).toBe(false);
+ }
+ },
+ );
+
+ it("rolls back the deletion fence if the owner changes before the locked read", async () => {
+ const database = databaseFixture();
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ database.beforePrepareDelete(async () => {
+ const row = database.rows.get(videoId);
+ if (!row) throw new Error("Missing video row");
+ row.ownerId = "new-owner";
+ });
+ expect(Exit.isFailure(await runVideoOperation("delete"))).toBe(true);
+ expect(database.jobs.get(videoId)?.generation).toBe("active-generation");
+ expect(storage.requests).toEqual([]);
+ });
+
+ it("retains the video and deletion fence if ownership changes during cloud cleanup", async () => {
+ const database = databaseFixture();
+ const storage = await storageFixture([[outputKey, "verified-video"]]);
+ storage.beforeDelete(() => {
+ const row = database.rows.get(videoId);
+ if (!row) throw new Error("Missing video row");
+ row.ownerId = "new-owner";
+ });
+ expect(Exit.isFailure(await runVideoOperation("delete"))).toBe(true);
+ expect(database.rows.get(videoId)?.ownerId).toBe("new-owner");
+ expect(database.jobs.get(videoId)?.errorCode).toBe("video-deleting");
+ expect(
+ database.mutations.filter(({ operation }) => operation === "delete"),
+ ).toEqual([]);
+ });
+
+ it("deletes every retained source page after fencing the worker and removes the row last", async () => {
+ const database = databaseFixture();
+ const retained = Array.from(
+ { length: 1100 },
+ (_, index) =>
+ [
+ `${prefix}.recording/sources/generation/snapshot/video/${String(index).padStart(5, "0")}.m4s`,
+ "fragment",
+ ] as const,
+ );
+ const storage = await storageFixture([
+ ...retained,
+ [outputKey, "verified-output"],
+ [`${prefix}comments/comment/attachment.mp4`, "comment-attachment"],
+ ["other-user/other-video/result.mp4", "unrelated"],
+ ]);
+ storage.beforeDelete(() => {
+ expect(database.rows.has(videoId)).toBe(true);
+ expect(database.jobs.get(videoId)?.errorCode).toBe("video-deleting");
+ });
+ const result = await runVideoOperation("delete");
+ expect(Exit.isSuccess(result)).toBe(true);
+ expect(database.rows.has(videoId)).toBe(false);
+ expect(database.events.slice(0, 3)).toEqual([
+ "job-fence-request",
+ "job-delete-request",
+ "job-delete-complete",
+ ]);
+ expect(storage.objects).toEqual(
+ new Map([["other-user/other-video/result.mp4", "unrelated"]]),
+ );
+ expect(
+ storage.requests.filter(({ operation }) => operation === "list"),
+ ).toHaveLength(2);
+ const deleted = storage.requests.filter(
+ ({ operation }) => operation === "delete",
+ );
+ expect(deleted.map(({ keys }) => keys?.length)).toEqual([1000, 102]);
+ });
+
+ it.each([
+ { suffix: "segments/manifest.json", status: 403 },
+ { suffix: "segments/manifest.json", status: 503 },
+ {
+ suffix: ".recording/sources/generation/snapshot/pages/0.json",
+ status: 403,
+ },
+ {
+ suffix: ".recording/sources/generation/snapshot/pages/0.json",
+ status: 503,
+ },
+ ])(
+ "preserves a $status Drive read failure for $suffix without recovery or index changes",
+ async ({ suffix, status }) => {
+ const drive = await driveFixture();
+ const original = drive.records.get(outputKey);
+ if (!original) throw new Error("Missing indexed Drive object");
+ const key = `${prefix}${suffix}`;
+ drive.records.set(key, { ...original, objectKey: key });
+ const error = new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(status, "fixture read failure"),
+ });
+ mocks.driveText.mockReturnValue(Effect.fail(error));
+ const result = await Effect.runPromiseExit(drive.access.getObject(key));
+ if (Exit.isSuccess(result))
+ throw new Error("Transient Drive failure was not propagated");
+ expect(Option.getOrThrow(Cause.failureOption(result.cause))).toBe(error);
+ expect(drive.records.get(key)?.providerObjectId).toBe("original-file");
+ expect(mocks.driveFind).not.toHaveBeenCalled();
+ expect(drive.upsertIndex).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([403, 503])(
+ "does not replace the Drive index after a %s metadata failure",
+ async (status) => {
+ const drive = await driveFixture();
+ const error = new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(status, "fixture metadata failure"),
+ });
+ mocks.driveMetadata.mockReturnValue(Effect.fail(error));
+ const result = await Effect.runPromiseExit(
+ drive.access.headObject(outputKey),
+ );
+ if (Exit.isSuccess(result))
+ throw new Error("Transient Drive metadata failure was not propagated");
+ expect(Option.getOrThrow(Cause.failureOption(result.cause))).toBe(error);
+ expect(mocks.driveFind).not.toHaveBeenCalled();
+ expect(drive.records.get(outputKey)?.providerObjectId).toBe(
+ "original-file",
+ );
+ },
+ );
+
+ it("keeps network and database read errors distinct from missing Drive objects", async () => {
+ const drive = await driveFixture();
+ const networkError = new StorageDomain.StorageError({
+ cause: new Error("Network read unavailable"),
+ });
+ mocks.driveText.mockReturnValue(Effect.fail(networkError));
+ const networkResult = await Effect.runPromiseExit(
+ drive.access.getObject(outputKey),
+ );
+ if (Exit.isSuccess(networkResult))
+ throw new Error("Network failure was not propagated");
+ expect(Option.getOrThrow(Cause.failureOption(networkResult.cause))).toBe(
+ networkError,
+ );
+ const databaseError = new DatabaseError({
+ cause: new Error("Index read unavailable"),
+ });
+ drive.getIndex.mockReturnValue(Effect.fail(databaseError));
+ const databaseResult = await Effect.runPromiseExit(
+ drive.access.getObject(outputKey),
+ );
+ if (Exit.isSuccess(databaseResult))
+ throw new Error("Database failure was not propagated");
+ expect(
+ Option.getOrThrow(Cause.failureOption(databaseResult.cause)).cause,
+ ).toBe(databaseError);
+ expect(mocks.driveFind).not.toHaveBeenCalled();
+ expect(drive.upsertIndex).not.toHaveBeenCalled();
+ });
+
+ it("returns none for a genuinely missing Drive file with no replacement", async () => {
+ const drive = await driveFixture();
+ mocks.driveText.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(404, "Missing file"),
+ }),
+ ),
+ );
+ expect(await Effect.runPromise(drive.access.getObject(outputKey))).toEqual(
+ Option.none(),
+ );
+ expect(mocks.driveFind).toHaveBeenCalledTimes(1);
+ expect(drive.records.get(outputKey)?.providerObjectId).toBe(
+ "original-file",
+ );
+ expect(drive.upsertIndex).not.toHaveBeenCalled();
+ });
+
+ it("returns none for a missing index without requesting or recovering a Drive file", async () => {
+ const drive = await driveFixture();
+ drive.records.delete(outputKey);
+ expect(await Effect.runPromise(drive.access.getObject(outputKey))).toEqual(
+ Option.none(),
+ );
+ expect(mocks.driveText).not.toHaveBeenCalled();
+ expect(mocks.driveFind).not.toHaveBeenCalled();
+ });
+
+ it.each(["index", "provider"])(
+ "returns a typed missing-object error from Drive HEAD for an absent %s object",
+ async (origin) => {
+ const drive = await driveFixture();
+ if (origin === "index") {
+ drive.records.delete(outputKey);
+ } else {
+ mocks.driveMetadata.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(404, "Missing file"),
+ }),
+ ),
+ );
+ }
+ const result = await Effect.runPromiseExit(
+ drive.access.headObject(outputKey),
+ );
+ if (Exit.isSuccess(result))
+ throw new Error("Missing Drive metadata was not reported");
+ const error = Option.getOrThrow(Cause.failureOption(result.cause));
+ const cause =
+ error.cause instanceof StorageDomain.StorageError
+ ? error.cause.cause
+ : error.cause;
+ expect(cause).toBeInstanceOf(GoogleDriveRequestError);
+ expect(cause).toHaveProperty("status", 404);
+ expect(mocks.driveFind).toHaveBeenCalledTimes(origin === "index" ? 0 : 1);
+ expect(drive.upsertIndex).not.toHaveBeenCalled();
+ },
+ );
+
+ it("recovers an indexed 404 to the replacement file before returning its text", async () => {
+ const drive = await driveFixture();
+ const text = '{"source":"retained"}';
+ mocks.driveText
+ .mockReturnValueOnce(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(404, "Missing indexed file"),
+ }),
+ ),
+ )
+ .mockReturnValueOnce(Effect.succeed(text));
+ mocks.driveFind.mockReturnValue(
+ Effect.succeed(
+ Option.some({
+ id: "recovered-file",
+ size: String(text.length),
+ mimeType: "application/json",
+ }),
+ ),
+ );
+ expect(await Effect.runPromise(drive.access.getObject(outputKey))).toEqual(
+ Option.some(text),
+ );
+ expect(mocks.driveText.mock.calls.map((args) => args[1])).toEqual([
+ "original-file",
+ "recovered-file",
+ ]);
+ expect(drive.records.get(outputKey)?.providerObjectId).toBe(
+ "recovered-file",
+ );
+ expect(drive.upsertIndex).toHaveBeenCalledTimes(1);
+ });
+
+ it("propagates a provider failure while looking for a replacement of an indexed 404", async () => {
+ const drive = await driveFixture();
+ mocks.driveText.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(404, "Missing indexed file"),
+ }),
+ ),
+ );
+ const error = new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(503, "Recovery unavailable"),
+ });
+ mocks.driveFind.mockReturnValue(Effect.fail(error));
+ const result = await Effect.runPromiseExit(
+ drive.access.getObject(outputKey),
+ );
+ if (Exit.isSuccess(result))
+ throw new Error("Recovery failure was not propagated");
+ expect(Option.getOrThrow(Cause.failureOption(result.cause))).toBe(error);
+ expect(drive.records.get(outputKey)?.providerObjectId).toBe(
+ "original-file",
+ );
+ expect(drive.upsertIndex).not.toHaveBeenCalled();
+ });
+
+ it.each([403, 503])(
+ "preserves the Drive object index when provider deletion returns %s",
+ async (status) => {
+ const drive = await driveFixture();
+ mocks.driveDelete.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(
+ status,
+ "fixture provider failure",
+ ),
+ }),
+ ),
+ );
+ const result = await Effect.runPromiseExit(
+ drive.access.deleteObjects([{ Key: outputKey }]),
+ );
+ expect(Exit.isFailure(result)).toBe(true);
+ expect(drive.records.get(outputKey)?.providerObjectId).toBe(
+ "original-file",
+ );
+ expect(drive.deleteIndex).not.toHaveBeenCalled();
+ },
+ );
+
+ it("clears a genuinely missing Drive object and makes repeated deletion idempotent", async () => {
+ const drive = await driveFixture();
+ mocks.driveDelete.mockReturnValue(
+ Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new GoogleDriveRequestError(404, "missing fixture file"),
+ }),
+ ),
+ );
+ await Effect.runPromise(drive.access.deleteObject(outputKey));
+ await Effect.runPromise(drive.access.deleteObject(outputKey));
+ expect(drive.records.has(outputKey)).toBe(false);
+ expect(drive.deleteIndex).toHaveBeenCalledExactlyOnceWith(
+ drive.integrationId,
+ outputKey,
+ );
+ expect(mocks.driveDelete).toHaveBeenCalledTimes(1);
+ });
+
+ it("retains the Drive index until the provider confirms deletion", async () => {
+ const drive = await driveFixture();
+ let release: (() => void) | undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ mocks.driveDelete.mockReturnValue(Effect.promise(() => gate));
+ const pending = Effect.runPromise(drive.access.deleteObject(outputKey));
+ await vi.waitFor(() => expect(mocks.driveDelete).toHaveBeenCalledTimes(1));
+ expect(drive.records.has(outputKey)).toBe(true);
+ expect(drive.deleteIndex).not.toHaveBeenCalled();
+ if (!release) throw new Error("Missing Drive delete resolver");
+ release();
+ await pending;
+ expect(drive.records.has(outputKey)).toBe(false);
+ });
+
+ it("copies the published Drive object and checks both file identities after native copy", async () => {
+ const drive = await driveFixture();
+ await Effect.runPromise(
+ drive.access.copyObjectForRecording(
+ `google-drive/${prefix}result.mp4`,
+ `${newPrefix}result.mp4`,
+ ),
+ );
+ expect(mocks.driveCopy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sourceFileId: "original-file",
+ input: expect.objectContaining({
+ key: `${newPrefix}result.mp4`,
+ contentType: "video/mp4",
+ }),
+ }),
+ );
+ expect(mocks.driveMetadata.mock.calls.map((args) => args[1])).toEqual([
+ "original-file",
+ "original-file",
+ "copied-file",
+ ]);
+ expect(drive.records.get(`${newPrefix}result.mp4`)?.providerObjectId).toBe(
+ "copied-file",
+ );
+ });
+
+ it.each(["source-version", "destination-size"] as const)(
+ "rejects a Drive copy when %s changes during readback",
+ async (change) => {
+ const drive = await driveFixture();
+ const nativeCopy = mocks.driveCopy.getMockImplementation();
+ if (!nativeCopy) throw new Error("Missing native Drive copy fixture");
+ mocks.driveCopy.mockImplementation(
+ (input: Parameters<typeof copyGoogleDriveFile>[0]) =>
+ nativeCopy(input).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ if (change === "source-version") {
+ const original = drive.files.get("original-file");
+ if (!original)
+ throw new Error("Missing original Drive fixture");
+ original.version = "2";
+ } else {
+ const destination = drive.files.get("copied-file");
+ if (!destination)
+ throw new Error("Missing copied Drive fixture");
+ destination.size = "9";
+ }
+ }),
+ ),
+ ),
+ );
+ const result = await Effect.runPromiseExit(
+ drive.access.copyObjectForRecording(
+ `google-drive/${outputKey}`,
+ `${newPrefix}result.mp4`,
+ ),
+ );
+ expect(Exit.isFailure(result)).toBe(true);
+ expect(drive.records.has(outputKey)).toBe(true);
+ },
+ );
+});
diff --git a/apps/web/__tests__/unit/storage-object-verification.test.ts b/apps/web/__tests__/unit/storage-object-verification.test.ts
index 9a43973c6..1563bc49c 100644
--- a/apps/web/__tests__/unit/storage-object-verification.test.ts
+++ b/apps/web/__tests__/unit/storage-object-verification.test.ts
@@ -5,6 +5,17 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
head: vi.fn(),
read: vi.fn(),
+ token: null as { videoId: string; key: string } | null,
+ video: {
+ id: "video",
+ ownerId: "owner",
+ source: { type: "desktopMP4" } as {
+ type: string;
+ outputKey?: string;
+ thumbnailKey?: string;
+ previewKey?: string;
+ },
+ },
}));
vi.mock("@cap/web-backend", async () => {
@@ -17,15 +28,13 @@ vi.mock("@cap/web-backend", async () => {
{ headObject: mocks.head, getObjectResponse: mocks.read },
]),
},
- Videos: {},
- VideosRepo: Effect.succeed({
- getById: () =>
- Effect.succeed(Option.some([{ id: "video", ownerId: "owner" }])),
+ Videos: Effect.succeed({
+ getByIdForViewing: () => Effect.succeed(Option.some([mocks.video])),
}),
- verifyStorageObjectToken: () => ({
- videoId: "video",
- key: "owner/video/result.mp4",
+ VideosRepo: Effect.succeed({
+ getById: () => Effect.succeed(Option.some([mocks.video])),
}),
+ verifyStorageObjectToken: () => mocks.token,
};
});
vi.mock("@/lib/server", async () => {
@@ -36,10 +45,13 @@ vi.mock("@/utils/helpers", () => ({ CACHE_CONTROL_HEADERS: {} }));
import { GET } from "@/app/api/storage/object/route";
-function request(headers: Record<string, string> = {}) {
+function request(
+ headers: Record<string, string> = {},
+ key = "owner/video/result.mp4",
+) {
return GET(
new NextRequest(
- "https://cap.test/api/storage/object?videoId=video&key=owner/video/result.mp4&token=test",
+ `https://cap.test/api/storage/object?videoId=video&key=${encodeURIComponent(key)}&token=test`,
{ headers },
),
);
@@ -47,6 +59,8 @@ function request(headers: Record<string, string> = {}) {
describe("recording verification object reads", () => {
beforeEach(() => {
+ mocks.token = { videoId: "video", key: "owner/video/result.mp4" };
+ mocks.video.source = { type: "desktopMP4" };
mocks.head.mockReturnValue(
Effect.succeed({ ETag: '"drive-file:42"', ContentLength: 100 }),
);
@@ -94,4 +108,55 @@ describe("recording verification object reads", () => {
expect(response.status).toBe(503);
expect(mocks.read).not.toHaveBeenCalled();
});
+
+ it.each([
+ "owner/video/.recording/sources/generation/snapshot/inventory.json",
+ "owner/video/.recording/sources/generation/snapshot/video/0.mp4",
+ "owner/video/.recording/outputs/generation/unpublished.mp4",
+ ])(
+ "does not expose retained or unpublished data to ordinary viewers: %s",
+ async (key) => {
+ mocks.token = null;
+ const response = await request({}, key);
+ expect(response.status).toBe(404);
+ expect(mocks.read).not.toHaveBeenCalled();
+ },
+ );
+
+ it("allows a server-signed read of the exact retained source object", async () => {
+ const key =
+ "owner/video/.recording/sources/generation/snapshot/video/0.mp4";
+ mocks.token = { videoId: "video", key };
+ const response = await request(
+ { "X-Cap-Recording-Verification": "1", "If-Match": '"drive-file:42"' },
+ key,
+ );
+ expect(response.status).toBe(206);
+ expect(mocks.read).toHaveBeenCalledWith(key, null);
+ });
+
+ it("does not authorize another retained object using a valid token", async () => {
+ mocks.token = {
+ videoId: "video",
+ key: "owner/video/.recording/sources/generation/snapshot/video/0.mp4",
+ };
+ const response = await request(
+ {},
+ "owner/video/.recording/sources/generation/snapshot/audio/0.mp4",
+ );
+ expect(response.status).toBe(404);
+ expect(mocks.read).not.toHaveBeenCalled();
+ });
+
+ it.each(["outputKey", "thumbnailKey", "previewKey"] as const)(
+ "allows viewers to read only the published %s",
+ async (field) => {
+ const key = "owner/video/.recording/outputs/generation/published.mp4";
+ mocks.token = null;
+ mocks.video.source = { type: "desktopMP4", [field]: key };
+ const response = await request({}, key);
+ expect(response.status).toBe(206);
+ expect(mocks.read).toHaveBeenCalledWith(key, null);
+ },
+ );
});
diff --git a/apps/web/__tests__/unit/upload-progress-playback.test.ts b/apps/web/__tests__/unit/upload-progress-playback.test.ts
index 77448b0db..303f3ef27 100644
--- a/apps/web/__tests__/unit/upload-progress-playback.test.ts
+++ b/apps/web/__tests__/unit/upload-progress-playback.test.ts
@@ -192,4 +192,18 @@ describe("shouldDeferPlaybackSource", () => {
}),
).toBe("Video processing stalled. Retry processing.");
});
+
+ it.each([0, 25, 90])(
+ "does not report a durable automatic retry as failed at %i percent",
+ (processingProgress) => {
+ expect(
+ getStalledProcessingMessage({
+ phase: "processing",
+ updatedAt: new Date(Date.now() - 2 * 60 * 60 * 1000),
+ processingProgress,
+ automaticRetry: true,
+ }),
+ ).toBeNull();
+ },
+ );
});
diff --git a/apps/web/actions/admin/replace-video.ts b/apps/web/actions/admin/replace-video.ts
index d7af00742..46d68589f 100644
--- a/apps/web/actions/admin/replace-video.ts
+++ b/apps/web/actions/admin/replace-video.ts
@@ -6,15 +6,17 @@ import {
} from "@aws-sdk/client-cloudfront";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
-import { videos } from "@cap/database/schema";
+import { videos, videoUploads } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { AwsCredentials, S3Buckets } from "@cap/web-backend";
-import { S3Bucket, Video } from "@cap/web-domain";
+import { AwsCredentials, Storage } from "@cap/web-backend";
+import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
-import { Effect, Option } from "effect";
+import { Effect } from "effect";
+import { retireDesktopRecordingJobForOutputReplacement } from "@/lib/desktop-recording-jobs";
import { MESSENGER_ADMIN_EMAIL } from "@/lib/messenger/constants";
import { runPromise } from "@/lib/server";
+import { decodeStorageVideo } from "@/lib/video-storage";
async function requireAdmin() {
const user = await getCurrentUser();
@@ -26,11 +28,7 @@ async function requireAdmin() {
async function getVideoOrThrow(videoId: string) {
const [video] = await db()
- .select({
- id: videos.id,
- ownerId: videos.ownerId,
- bucket: videos.bucket,
- })
+ .select()
.from(videos)
.where(eq(videos.id, Video.VideoId.make(videoId)));
@@ -46,17 +44,15 @@ export async function getVideoReplaceUploadUrl(videoId: string) {
const fileKey = `${video.ownerId}/${video.id}/result.mp4`;
- const bucketIdOption = Option.fromNullable(video.bucket).pipe(
- Option.map((id) => S3Bucket.S3BucketId.make(id)),
- );
-
- const presignedPostData = await Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccess(bucketIdOption);
- return yield* bucket.getPresignedPostUrl(fileKey, {
+ const [bucket] = await Storage.getAccessForVideo(decodeStorageVideo(video), {
+ resolvePublishedOutput: false,
+ }).pipe(runPromise);
+ const presignedPostData = await bucket
+ .getPresignedPostUrl(fileKey, {
Fields: { "Content-Type": "video/mp4" },
Expires: 1800,
- });
- }).pipe(runPromise);
+ })
+ .pipe(runPromise);
return { presignedPostData };
}
@@ -64,6 +60,46 @@ export async function getVideoReplaceUploadUrl(videoId: string) {
export async function invalidateVideoCache(videoId: string) {
await requireAdmin();
const video = await getVideoOrThrow(videoId);
+ const fileKey = `${video.ownerId}/${video.id}/result.mp4`;
+ const [bucket] = await Storage.getAccessForVideo(decodeStorageVideo(video), {
+ resolvePublishedOutput: false,
+ }).pipe(runPromise);
+ const head = await bucket.headObject(fileKey).pipe(runPromise);
+ if (!head.ETag || !head.ContentLength || head.ContentLength <= 0) {
+ throw new Error("Replacement recording has not finished uploading");
+ }
+ await db().transaction(async (tx) => {
+ await retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId: video.id,
+ userId: video.ownerId,
+ });
+ const [lockedVideo] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, video.id))
+ .for("update");
+ if (
+ !lockedVideo ||
+ lockedVideo.ownerId !== video.ownerId ||
+ lockedVideo.bucket !== video.bucket ||
+ lockedVideo.storageIntegrationId !== video.storageIntegrationId
+ ) {
+ throw new Error("Recording storage changed during replacement");
+ }
+ const metadata = { ...(lockedVideo.metadata ?? {}) };
+ delete metadata.desktopRecordingUpload;
+ await tx
+ .update(videos)
+ .set({
+ metadata,
+ source:
+ lockedVideo.source.type === "webMP4"
+ ? lockedVideo.source
+ : { type: "desktopMP4" },
+ })
+ .where(eq(videos.id, video.id));
+ await tx.delete(videoUploads).where(eq(videoUploads.videoId, video.id));
+ });
if (video.bucket) {
return;
@@ -74,8 +110,6 @@ export async function invalidateVideoCache(videoId: string) {
return;
}
- const fileKey = `${video.ownerId}/${video.id}/result.mp4`;
-
const cloudfront = new CloudFrontClient({
region: serverEnv().CAP_AWS_REGION || "us-east-1",
credentials: await runPromise(
diff --git a/apps/web/actions/video/finalize-desktop-segments.ts b/apps/web/actions/video/finalize-desktop-segments.ts
index ce8be7515..adfcf02f1 100644
--- a/apps/web/actions/video/finalize-desktop-segments.ts
+++ b/apps/web/actions/video/finalize-desktop-segments.ts
@@ -33,6 +33,11 @@ export async function finalizeDesktopSegmentsRecording({
if (result.status === "manifest-changed") {
throw new Error("Segment manifest changed while finalizing");
}
+ if (result.status === "source-incomplete") {
+ throw new Error(
+ "This recording has not finished uploading. Keep Cap open on the recording device to complete the upload. Uploaded files are retained.",
+ );
+ }
return result;
}
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index b3041a7b9..469db105e 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -3,7 +3,6 @@ import { sendEmail } from "@cap/database/emails/config";
import { FirstShareableLink } from "@cap/database/emails/first-shareable-link";
import { nanoId } from "@cap/database/helpers";
import {
- importedVideos,
organizationMembers,
organizations,
users,
@@ -13,7 +12,7 @@ import {
import type { VideoMetadata } from "@cap/database/types";
import { serverEnv } from "@cap/env";
import { userIsPro } from "@cap/utils";
-import { Storage } from "@cap/web-backend";
+import { makeCurrentUserLayer, Storage, Videos } from "@cap/web-backend";
import { Organisation, Video } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, count, eq, lte } from "drizzle-orm";
@@ -24,7 +23,6 @@ import { z } from "zod";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import { maybeStartLiveTranscription } from "@/lib/live-transcribe";
import { runPromise } from "@/lib/server";
-import { decodeStorageVideo } from "@/lib/video-storage";
import {
GOOGLE_DRIVE_UPLOAD_FEATURE,
hasDesktopFeature,
@@ -423,28 +421,23 @@ app.delete(
{ status: 404 },
);
- await db().delete(videoUploads).where(eq(videoUploads.videoId, videoId));
- await db().delete(importedVideos).where(eq(importedVideos.id, videoId));
-
- await db()
- .delete(videos)
- .where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)));
-
- await Effect.gen(function* () {
- const video = decodeStorageVideo(result.video);
- const [bucket] = yield* Storage.getAccessForVideo(video);
-
- const listedObjects = yield* bucket.listObjects({
- prefix: `${user.id}/${videoId}/`,
- });
-
- if (listedObjects.Contents)
- yield* bucket.deleteObjects(
- listedObjects.Contents.map((content) => ({
- Key: content.Key,
- })),
- );
- }).pipe(runPromise);
+ const deleted = await Effect.gen(function* () {
+ const videoService = yield* Videos;
+ yield* videoService.delete(videoId);
+ return true;
+ }).pipe(
+ Effect.provide(makeCurrentUserLayer(user)),
+ Effect.catchTags({
+ VideoNotFoundError: () => Effect.succeed(false),
+ PolicyDenied: () => Effect.succeed(false),
+ }),
+ runPromise,
+ );
+ if (!deleted)
+ return c.json(
+ { error: true, message: "Video not found" },
+ { status: 404 },
+ );
await invalidateGoogleDriveStorageQuotaCache(
result.video.storageIntegrationId,
);
diff --git a/apps/web/app/api/storage/object/route.ts b/apps/web/app/api/storage/object/route.ts
index c2409f42c..87f342721 100644
--- a/apps/web/app/api/storage/object/route.ts
+++ b/apps/web/app/api/storage/object/route.ts
@@ -5,6 +5,7 @@ import {
VideosRepo,
verifyStorageObjectToken,
} from "@cap/web-backend";
+import { isInternalRecordingKey } from "@cap/web-backend/src/Storage/recording-output";
import { Storage as StorageDomain, Video } from "@cap/web-domain";
import { Effect, Option } from "effect";
import type { NextRequest } from "next/server";
@@ -122,6 +123,20 @@ export async function GET(request: NextRequest) {
if (!key.startsWith(`${video.ownerId}/${video.id}/`)) {
return yield* Effect.fail("not-found" as const);
}
+ if (
+ isInternalRecordingKey(key) &&
+ !(tokenPayload?.videoId === videoIdParam && tokenPayload.key === key) &&
+ !(
+ video.source.type === "desktopMP4" &&
+ [
+ key === video.source.outputKey,
+ key === video.source.thumbnailKey,
+ key === video.source.previewKey,
+ ].some(Boolean)
+ )
+ ) {
+ return yield* Effect.fail("not-found" as const);
+ }
const [storage] = yield* Storage.getAccessForVideo(video);
if (!("getObjectResponse" in storage)) {
diff --git a/apps/web/app/api/upload/[...route]/multipart-utils.ts b/apps/web/app/api/upload/[...route]/multipart-utils.ts
index 8365d747e..552ec3bbe 100644
--- a/apps/web/app/api/upload/[...route]/multipart-utils.ts
+++ b/apps/web/app/api/upload/[...route]/multipart-utils.ts
@@ -1,5 +1,13 @@
+import { isInternalRecordingKey } from "@cap/web-backend/src/Storage/recording-output";
import { parseVideoIdOrFileKey } from "../utils";
+function assertWritableFileKey(key: string) {
+ if (isInternalRecordingKey(key)) {
+ throw new Error("Recording snapshots are immutable");
+ }
+ return key;
+}
+
export const getSubpath = (input: { subpath?: string; fileKey?: string }) => {
if ("fileKey" in input) {
return undefined;
@@ -17,17 +25,21 @@ export const getMultipartFileKey = (
},
) => {
if ("fileKey" in input && input.fileKey) {
- return parseVideoIdOrFileKey(userId, { fileKey: input.fileKey });
+ return assertWritableFileKey(
+ parseVideoIdOrFileKey(userId, { fileKey: input.fileKey }),
+ );
}
if (!("videoId" in input) || !input.videoId) {
throw new Error("Video id not found");
}
- return parseVideoIdOrFileKey(userId, {
- videoId: input.videoId,
- subpath: input.subpath ?? "result.mp4",
- });
+ return assertWritableFileKey(
+ parseVideoIdOrFileKey(userId, {
+ videoId: input.videoId,
+ subpath: input.subpath ?? "result.mp4",
+ }),
+ );
};
export const isRawRecorderUpload = (subpath: string) =>
diff --git a/apps/web/app/api/upload/[...route]/recording-complete.ts b/apps/web/app/api/upload/[...route]/recording-complete.ts
index 78b176b03..25a85dee0 100644
--- a/apps/web/app/api/upload/[...route]/recording-complete.ts
+++ b/apps/web/app/api/upload/[...route]/recording-complete.ts
@@ -5,6 +5,10 @@ import { zValidator } from "@hono/zod-validator";
import { and, eq } from "drizzle-orm";
import { Hono } from "hono";
import { z } from "zod";
+import {
+ DesktopRecordingSourceBlockedError,
+ SourceCommitPendingError,
+} from "@/lib/desktop-recording-jobs";
import {
validateDesktopRecordingRequest,
verifyDesktopRecordingUpload,
@@ -44,67 +48,55 @@ export const app = new Hono().post(
return c.json({ error: "Video is not a desktop recording" }, 400);
}
- if (verification) {
- const [upload] = await db()
- .select({
- videoId: Db.videoUploads.videoId,
- phase: Db.videoUploads.phase,
- })
- .from(Db.videoUploads)
- .where(eq(Db.videoUploads.videoId, videoId));
- if (upload?.phase === "error") {
- return c.json({ success: false, status: "reupload-required" }, 409);
- }
- if (
- upload?.phase === "processing" ||
- upload?.phase === "generating_thumbnail"
- ) {
- return c.json({ success: true, status: "already-processing" });
- }
- try {
+ try {
+ if (verification) {
const receipt =
video.source.type === "desktopMP4"
? await verifyDesktopRecordingUpload(video, verification)
: null;
- if (!receipt) {
- await validateDesktopRecordingRequest(video, verification);
- const status = await queueDesktopSegmentsFinalization({
- videoId,
- userId: user.id,
- verification,
+ if (receipt) {
+ return c.json({
+ success: true,
+ status: "verified",
+ verification: receipt,
});
- return c.json({ success: true, status });
}
- return c.json({
- success: true,
- status: "verified",
- verification: receipt,
- });
- } catch {
- return c.json(
- {
- error:
- "Recording verification is unavailable; retain the local recording",
- },
- 503,
- );
+ await validateDesktopRecordingRequest(video, verification);
}
- }
-
- if (video.source.type === "desktopMP4") {
- return c.json({ success: true, status: "already-complete" });
- }
-
- try {
const status = await queueDesktopSegmentsFinalization({
videoId,
userId: user.id,
+ verification,
});
-
return c.json({ success: true, status });
} catch (error) {
- console.error("[recording-complete] Error queueing mux:", error);
- return c.json({ error: "Failed to queue muxing" }, 500);
+ if (error instanceof DesktopRecordingSourceBlockedError) {
+ return c.json(
+ {
+ success: false,
+ status: "reupload-required",
+ code: error.code,
+ error: error.message,
+ },
+ 409,
+ );
+ }
+ c.header("Retry-After", "5");
+ if (error instanceof SourceCommitPendingError) {
+ return c.json(
+ { success: false, status: error.code, error: error.message },
+ 503,
+ );
+ }
+ console.error("[recording-complete] Finalization unavailable:", error);
+ return c.json(
+ {
+ success: false,
+ error:
+ "Recording verification is unavailable; retain the local recording. Processing will retry automatically.",
+ },
+ 503,
+ );
}
},
);
diff --git a/apps/web/app/api/upload/[...route]/signed.ts b/apps/web/app/api/upload/[...route]/signed.ts
index 7e30a8ff2..ce8d4e84f 100644
--- a/apps/web/app/api/upload/[...route]/signed.ts
+++ b/apps/web/app/api/upload/[...route]/signed.ts
@@ -3,6 +3,7 @@ import { inspect } from "node:util";
import { db, updateIfDefined } from "@cap/database";
import * as Db from "@cap/database/schema";
import { Storage } from "@cap/web-backend";
+import { isInternalRecordingKey } from "@cap/web-backend/src/Storage/recording-output";
import { Video } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, eq } from "drizzle-orm";
@@ -45,7 +46,10 @@ app.post(
z
.string()
.refine(
- (s) => !s.includes("..") && !s.startsWith("/"),
+ (s) =>
+ !s.includes("..") &&
+ !s.startsWith("/") &&
+ s.split("/")[0] !== ".recording",
"Invalid subpath",
),
)
@@ -127,6 +131,9 @@ app.post(
c.req.valid("json");
const fileKey = parseVideoIdOrFileKey(user.id, body);
+ if (isInternalRecordingKey(fileKey)) {
+ return c.json({ error: "Recording snapshots are immutable" }, 403);
+ }
const videoIdFromKey = fileKey.split("/")[1];
const videoIdToUse = "videoId" in body ? body.videoId : videoIdFromKey;
if (!videoIdToUse) return c.json({ error: "Video id not found" }, 400);
diff --git a/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts b/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts
index 4d56f8cd9..1a956e072 100644
--- a/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts
+++ b/apps/web/app/api/webhooks/media-server/multipart/[action]/route.ts
@@ -7,6 +7,8 @@ import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { type NextRequest, NextResponse } from "next/server";
import { z } from "zod";
+import { getProcessingState } from "@/lib/desktop-recording-jobs";
+import { getDesktopRecordingOutputKey } from "@/lib/desktop-recording-source";
import { runPromise } from "@/lib/server";
import { decodeStorageVideo } from "@/lib/video-storage";
@@ -14,6 +16,14 @@ const baseSchema = z.object({
videoId: z.string().min(1),
key: z.string().min(1),
uploadId: z.string().min(1),
+ generation: z
+ .string()
+ .regex(/^[a-zA-Z0-9_-]{1,64}$/)
+ .optional(),
+ attemptId: z
+ .string()
+ .regex(/^[a-zA-Z0-9_-]{1,64}$/)
+ .optional(),
});
const signPartSchema = baseSchema.extend({
@@ -50,7 +60,10 @@ function isAuthorized(request: NextRequest) {
);
}
-async function getMultipartContext(payload: MultipartPayload) {
+async function getMultipartContext(
+ payload: MultipartPayload,
+ allowExpired = false,
+) {
const [video] = await db()
.select()
.from(videos)
@@ -65,8 +78,21 @@ async function getMultipartContext(payload: MultipartPayload) {
};
}
- const expectedKey = `${video.ownerId}/${video.id}/result.mp4`;
- if (payload.key !== expectedKey) {
+ const fenced =
+ payload.generation !== undefined || payload.attemptId !== undefined;
+ const expectedKey =
+ fenced && payload.generation && payload.attemptId
+ ? getDesktopRecordingOutputKey(
+ video.ownerId,
+ video.id,
+ payload.generation,
+ payload.attemptId,
+ )
+ : `${video.ownerId}/${video.id}/result.mp4`;
+ if (
+ payload.key !== expectedKey ||
+ (fenced && (!payload.generation || !payload.attemptId))
+ ) {
return {
response: NextResponse.json(
{ error: "Invalid multipart upload key" },
@@ -74,6 +100,26 @@ async function getMultipartContext(payload: MultipartPayload) {
),
};
}
+ if (fenced && !allowExpired) {
+ const job = await getProcessingState({ videoId: video.id });
+ if (
+ !job ||
+ job.ownerId !== video.ownerId ||
+ job.state !== "processing" ||
+ !job.source ||
+ job.generation !== payload.generation ||
+ job.attemptId !== payload.attemptId ||
+ !job.leaseExpiresAt ||
+ job.leaseExpiresAt <= new Date()
+ ) {
+ return {
+ response: NextResponse.json(
+ { error: "Recording attempt is no longer active" },
+ { status: 409 },
+ ),
+ };
+ }
+ }
const [bucket] = await Storage.getAccessForVideo(
decodeStorageVideo(video),
@@ -88,7 +134,7 @@ async function getMultipartContext(payload: MultipartPayload) {
};
}
- return { bucket };
+ return { bucket, fenced };
}
async function readJson(request: NextRequest) {
@@ -152,10 +198,17 @@ export async function POST(
PartNumber: part.partNumber,
ETag: part.etag,
}));
+ if (parts.some((part, index) => part.PartNumber !== index + 1)) {
+ return NextResponse.json(
+ { error: "Multipart parts must be contiguous and unique" },
+ { status: 400 },
+ );
+ }
const result = await multipartContext.bucket.multipart
.complete(payload.data.key, payload.data.uploadId, {
MultipartUpload: { Parts: parts },
+ ...(multipartContext.fenced ? { IfNoneMatch: "*" } : {}),
})
.pipe(runPromise);
@@ -175,7 +228,7 @@ export async function POST(
);
}
- const multipartContext = await getMultipartContext(payload.data);
+ const multipartContext = await getMultipartContext(payload.data, true);
if ("response" in multipartContext) return multipartContext.response;
await multipartContext.bucket.multipart
diff --git a/apps/web/app/api/webhooks/media-server/progress/route.ts b/apps/web/app/api/webhooks/media-server/progress/route.ts
index fd97e5332..b7f66c066 100644
--- a/apps/web/app/api/webhooks/media-server/progress/route.ts
+++ b/apps/web/app/api/webhooks/media-server/progress/route.ts
@@ -5,11 +5,14 @@ import { serverEnv } from "@cap/env";
import type { Video } from "@cap/web-domain";
import { eq, sql } from "drizzle-orm";
import { type NextRequest, NextResponse } from "next/server";
+import { SourceCommitPendingError } from "@/lib/desktop-recording-jobs";
+import { applyDesktopRecordingProgress } from "@/lib/desktop-recording-publication";
import { createVerifiedRecordingReceipt } from "@/lib/desktop-recording-upload-status";
import {
type RecordingVerification,
recordingVerificationSchema,
} from "@/lib/desktop-recording-verification";
+import { queueDesktopSegmentsFinalization } from "@/lib/desktop-segments-finalization";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import {
queueVideoTranscription,
@@ -98,6 +101,25 @@ export async function POST(request: NextRequest) {
}
const payload: ProgressWebhookPayload = await request.json();
+ const recordingProgress = await applyDesktopRecordingProgress(payload);
+ if (recordingProgress.handled) {
+ if (recordingProgress.published) {
+ try {
+ await queueVideoTranscription(payload.videoId as Video.VideoId);
+ } catch {
+ console.warn(
+ "[media-server-webhook] Transcription queue unavailable",
+ {
+ videoId: payload.videoId,
+ },
+ );
+ }
+ }
+ return NextResponse.json(
+ { success: recordingProgress.status === 200 },
+ { status: recordingProgress.status ?? 200 },
+ );
+ }
const isRetryableWorkflowError =
request.nextUrl.searchParams.get("retryable") === "true" &&
payload.phase === "error";
@@ -116,7 +138,40 @@ export async function POST(request: NextRequest) {
.select()
.from(videos)
.where(eq(videos.id, payload.videoId as Video.VideoId));
+ const [currentUpload] = await db()
+ .select({ rawFileKey: videoUploads.rawFileKey })
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, payload.videoId as Video.VideoId));
+ const isEditUpload =
+ currentVideo &&
+ isEditSourceKey({
+ ownerId: currentVideo.ownerId,
+ videoId: payload.videoId,
+ rawFileKey: currentUpload?.rawFileKey,
+ });
const proof = payload.recordingVerification;
+ if (
+ !isEditUpload &&
+ !recordingProgress.allowLegacyProcessing &&
+ (currentVideo?.source.type === "desktopSegments" ||
+ currentVideo?.source.type === "desktopMP4")
+ ) {
+ try {
+ await queueDesktopSegmentsFinalization({
+ videoId: currentVideo.id,
+ userId: currentVideo.ownerId,
+ verification: proof
+ ? recordingVerificationSchema.parse(proof.request)
+ : undefined,
+ });
+ } catch (error) {
+ if (!(error instanceof SourceCommitPendingError)) throw error;
+ }
+ return NextResponse.json({
+ success: true,
+ status: "queued-for-verification",
+ });
+ }
const receipt = proof
? currentVideo && payload.metadata
? await createVerifiedRecordingReceipt(
@@ -149,12 +204,7 @@ export async function POST(request: NextRequest) {
.where(eq(videos.id, payload.videoId as Video.VideoId));
}
- const [currentUpload] = await db()
- .select({ rawFileKey: videoUploads.rawFileKey })
- .from(videoUploads)
- .where(eq(videoUploads.videoId, payload.videoId as Video.VideoId));
-
- if (currentVideo?.source?.type === "desktopSegments" || receipt) {
+ if (receipt) {
await db()
.update(videos)
.set({
@@ -168,14 +218,6 @@ export async function POST(request: NextRequest) {
.where(eq(videos.id, payload.videoId as Video.VideoId));
}
- const isEditUpload =
- currentVideo &&
- isEditSourceKey({
- ownerId: currentVideo.ownerId,
- videoId: payload.videoId,
- rawFileKey: currentUpload?.rawFileKey,
- });
-
if (isEditUpload) {
await db()
.update(videoUploads)
diff --git a/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx b/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
index 8aea8a326..32725a837 100644
--- a/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
+++ b/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
@@ -59,6 +59,7 @@ export function useUploadProgress(
phase,
updatedAt: lastUpdated,
processingProgress: query.data.processingProgress,
+ automaticRetry: query.data.automaticRetry,
});
if (phase === "complete") {
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 745ce641e..c3d98b177 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -356,8 +356,10 @@ export const ShareVideo = forwardRef<
setConfirmStoppedError(null);
try {
- await finalizeDesktopSegmentsRecording({ videoId: data.id });
- setUserConfirmedStopped(true);
+ const result = await finalizeDesktopSegmentsRecording({
+ videoId: data.id,
+ });
+ setUserConfirmedStopped(result.status !== "source-committing");
router.refresh();
} catch (error) {
setConfirmStoppedError(
diff --git a/apps/web/app/s/[videoId]/_components/upload-progress.ts b/apps/web/app/s/[videoId]/_components/upload-progress.ts
index 4a51bdbba..0b8c2f046 100644
--- a/apps/web/app/s/[videoId]/_components/upload-progress.ts
+++ b/apps/web/app/s/[videoId]/_components/upload-progress.ts
@@ -98,7 +98,9 @@ export function getStalledProcessingMessage(input: {
| "error";
updatedAt: Date;
processingProgress: number;
+ automaticRetry?: boolean;
}): string | null {
+ if (input.automaticRetry) return null;
const ageMs = Date.now() - input.updatedAt.getTime();
if (input.phase === "processing") {
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 6bf3f6982..b1ac88879 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -439,7 +439,9 @@ async function AuthorizedContent({
userId: user.id,
});
recoveredDesktopSegmentsUpload =
- result.status === "queued" || result.status === "already-processing";
+ result.status === "queued" ||
+ result.status === "already-processing" ||
+ result.status === "source-committing";
} catch (error) {
console.error(
`[ShareVideoPage] Failed to recover desktop segments upload ${videoId}:`,
diff --git a/apps/web/lib/desktop-recording-job-status.ts b/apps/web/lib/desktop-recording-job-status.ts
index 751d533db..2d7d50af3 100644
--- a/apps/web/lib/desktop-recording-job-status.ts
+++ b/apps/web/lib/desktop-recording-job-status.ts
@@ -1,27 +1,54 @@
import { z } from "zod";
-const terminalJobSchema = z
+const jobSchema = z
.object({
jobId: z.string(),
videoId: z.string(),
- phase: z.enum(["complete", "error", "cancelled"]),
+ generation: z.string().optional(),
+ attemptId: z.string().optional(),
+ inventorySha256: z.string().optional(),
+ phase: z.enum([
+ "queued",
+ "downloading",
+ "probing",
+ "processing",
+ "uploading",
+ "generating_thumbnail",
+ "complete",
+ "error",
+ "cancelled",
+ ]),
})
.passthrough();
-export async function reconcileDesktopRecordingJob({
- videoId,
- jobId,
- mediaServerUrl,
- webhookUrl,
- secret,
-}: {
+type RecordingJobLookup = {
videoId: string;
jobId: string;
+ generation?: string;
+ attemptId?: string;
+ inventorySha256?: string;
mediaServerUrl: string;
webhookUrl: string;
secret?: string;
-}): Promise<boolean> {
- if (!secret) return false;
+};
+
+export type DesktopRecordingRemoteObservation =
+ | { status: "unavailable"; delivered: false }
+ | { status: "active"; delivered: false }
+ | { status: "terminal"; delivered: boolean };
+
+export async function observeDesktopRecordingJob({
+ videoId,
+ jobId,
+ generation,
+ attemptId,
+ inventorySha256,
+ mediaServerUrl,
+ webhookUrl,
+ secret,
+}: RecordingJobLookup): Promise<DesktopRecordingRemoteObservation> {
+ const unavailable = { status: "unavailable", delivered: false } as const;
+ if (!secret) return unavailable;
try {
const headers = { "x-media-server-secret": secret };
const response = await fetch(
@@ -31,22 +58,39 @@ export async function reconcileDesktopRecordingJob({
signal: AbortSignal.timeout(10_000),
},
);
- if (!response.ok) return false;
- const job = terminalJobSchema.safeParse(await response.json());
+ if (!response.ok) return unavailable;
+ const job = jobSchema.safeParse(await response.json());
if (
!job.success ||
job.data.jobId !== jobId ||
- job.data.videoId !== videoId
+ job.data.videoId !== videoId ||
+ (generation !== undefined && job.data.generation !== generation) ||
+ (attemptId !== undefined && job.data.attemptId !== attemptId) ||
+ (inventorySha256 !== undefined &&
+ job.data.inventorySha256 !== inventorySha256)
)
- return false;
+ return unavailable;
+ if (
+ job.data.phase !== "complete" &&
+ job.data.phase !== "error" &&
+ job.data.phase !== "cancelled"
+ ) {
+ return { status: "active", delivered: false };
+ }
const delivered = await fetch(webhookUrl, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify(job.data),
signal: AbortSignal.timeout(30_000),
});
- return delivered.ok;
+ return { status: "terminal", delivered: delivered.ok };
} catch {
- return false;
+ return unavailable;
}
}
+
+export async function reconcileDesktopRecordingJob(
+ input: RecordingJobLookup,
+): Promise<boolean> {
+ return (await observeDesktopRecordingJob(input)).delivered;
+}
diff --git a/apps/web/lib/desktop-recording-jobs.ts b/apps/web/lib/desktop-recording-jobs.ts
new file mode 100644
index 000000000..66054a87b
--- /dev/null
+++ b/apps/web/lib/desktop-recording-jobs.ts
@@ -0,0 +1,844 @@
+import { randomUUID } from "node:crypto";
+import { db } from "@cap/database";
+import {
+ videoProcessingJobs,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
+import type { User, Video } from "@cap/web-domain";
+import {
+ and,
+ asc,
+ eq,
+ getTableColumns,
+ gt,
+ inArray,
+ isNull,
+ lte,
+ ne,
+ or,
+} from "drizzle-orm";
+import { z } from "zod";
+import type { DesktopRecordingSource } from "@/lib/desktop-recording-source";
+import {
+ type DesktopRecordingSourceCheckpoint,
+ desktopRecordingSourceCheckpointSchema,
+} from "@/lib/desktop-recording-source-checkpoint";
+import {
+ type RecordingVerification,
+ recordingVerificationSchema,
+} from "@/lib/desktop-recording-verification";
+
+export const DESKTOP_RECORDING_LEASE_MS = 5 * 60 * 1_000;
+export const DESKTOP_RECORDING_SOURCE_RETRY_MS = 60 * 60 * 1_000;
+export const DESKTOP_RECORDING_OUTPUT_REPLACED = "output-replaced";
+export const DESKTOP_RECORDING_DELETING = "video-deleting";
+
+const sourceSchema = z.object({
+ version: z.literal(1),
+ kind: z.enum(["segments", "mp4"]),
+ manifestSha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
+ inventorySha256: z.string().regex(/^[a-f0-9]{64}$/),
+ inventoryKey: z.string().min(1),
+ requiredAudio: z.boolean(),
+ mp4: z
+ .object({
+ fileSize: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
+ duration: z.number().finite().positive().optional(),
+ objectIdentity: z.string().min(1),
+ })
+ .optional(),
+});
+
+type StoredJob = typeof videoProcessingJobs.$inferSelect;
+
+export type DesktopRecordingJob = Omit<StoredJob, "source" | "verification"> & {
+ source: DesktopRecordingSource | null;
+ verification: RecordingVerification | null;
+};
+
+export type DesktopRecordingAttempt = DesktopRecordingJob & {
+ attemptId: string;
+};
+
+export type DesktopRecordingAttemptFence = {
+ videoId: Video.VideoId;
+ generation: string;
+ attemptId: string;
+};
+
+export class SourceCommitPendingError extends Error {
+ readonly code = "source-commit-pending";
+
+ constructor() {
+ super(
+ "Recording source is still being secured. Processing will continue automatically.",
+ );
+ this.name = "SourceCommitPendingError";
+ }
+}
+
+export class DesktopRecordingSourceBlockedError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ this.name = "DesktopRecordingSourceBlockedError";
+ }
+}
+
+export function parseDesktopRecordingJob(row: StoredJob): DesktopRecordingJob {
+ return {
+ ...row,
+ source: row.source === null ? null : sourceSchema.parse(row.source),
+ verification:
+ row.verification === null
+ ? null
+ : recordingVerificationSchema.parse(row.verification),
+ };
+}
+
+export function getDesktopRecordingRetryDelay(attemptCount: number) {
+ return Math.min(
+ 15_000 * 2 ** Math.min(Math.max(attemptCount - 1, 0), 8),
+ 3_600_000,
+ );
+}
+
+export function isDesktopRecordingJobRecoverable(
+ job: DesktopRecordingJob,
+ now: Date,
+) {
+ if (job.state === "verified") return false;
+ if (job.errorCode === DESKTOP_RECORDING_OUTPUT_REPLACED) return false;
+ if (job.errorCode === DESKTOP_RECORDING_DELETING) return false;
+ if (job.state === "source-blocked" && job.source) return false;
+ if (job.leaseExpiresAt && job.leaseExpiresAt > now) return false;
+ return job.nextRetryAt <= now;
+}
+
+function sameArtifact(
+ verification: RecordingVerification,
+ job: DesktopRecordingJob,
+) {
+ const previous = job.verification?.artifact;
+ const incoming = verification.artifact;
+ if (incoming.kind === "segments") {
+ return (
+ job.source?.kind !== "mp4" &&
+ (job.source?.manifestSha256 ??
+ job.manifestSha256 ??
+ (previous?.kind === "segments" ? previous.manifestSha256 : null)) ===
+ incoming.manifestSha256
+ );
+ }
+ const mp4 = job.source?.mp4 ?? (previous?.kind === "mp4" ? previous : null);
+ return (
+ job.source?.kind !== "segments" &&
+ mp4?.objectIdentity === incoming.objectIdentity &&
+ mp4.fileSize === incoming.fileSize &&
+ (mp4.duration === undefined || mp4.duration === incoming.duration)
+ );
+}
+
+function newJob({
+ videoId,
+ userId,
+ verification,
+ now,
+}: {
+ videoId: Video.VideoId;
+ userId: User.UserId;
+ verification?: RecordingVerification;
+ now: Date;
+}): DesktopRecordingJob {
+ return {
+ videoId,
+ ownerId: userId,
+ generation: randomUUID(),
+ manifestSha256:
+ verification?.artifact.kind === "segments"
+ ? verification.artifact.manifestSha256
+ : null,
+ state: "committing",
+ attemptId: null,
+ attemptCount: 0,
+ leaseExpiresAt: null,
+ nextRetryAt: now,
+ workflowRunId: null,
+ remoteJobId: null,
+ source: null,
+ verification: verification ?? null,
+ output: null,
+ errorCode: null,
+ errorMessage: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+}
+
+export async function ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification,
+ now = new Date(),
+}: {
+ videoId: Video.VideoId;
+ userId: User.UserId;
+ verification?: RecordingVerification;
+ now?: Date;
+}): Promise<{ job: DesktopRecordingJob; created: boolean }> {
+ const candidate = newJob({ videoId, userId, verification, now });
+ return db().transaction(async (tx) => {
+ // Locking a missing job before inserting it deadlocks concurrent completion requests under InnoDB gap locking.
+ await tx
+ .insert(videoProcessingJobs)
+ .values(candidate)
+ .onDuplicateKeyUpdate({ set: { videoId } });
+ const [stored] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(eq(videoProcessingJobs.videoId, videoId))
+ .for("update");
+ const [video] = await tx
+ .select({ ownerId: videos.ownerId, source: videos.source })
+ .from(videos)
+ .where(eq(videos.id, videoId))
+ .for("update");
+ if (!video || video.ownerId !== userId) {
+ throw new Error("Recording does not exist");
+ }
+ if (
+ video.source.type !== "desktopSegments" &&
+ video.source.type !== "desktopMP4"
+ ) {
+ throw new Error("Recording is not a desktop upload");
+ }
+ if (!stored) throw new Error("Recording job could not be created");
+ let job = parseDesktopRecordingJob(stored);
+ const created = job.generation === candidate.generation;
+ if (job.errorCode === DESKTOP_RECORDING_DELETING) {
+ throw new DesktopRecordingSourceBlockedError(
+ DESKTOP_RECORDING_DELETING,
+ "This recording is being deleted and will not be processed again.",
+ );
+ }
+ if (job.errorCode === DESKTOP_RECORDING_OUTPUT_REPLACED) {
+ throw new DesktopRecordingSourceBlockedError(
+ DESKTOP_RECORDING_OUTPUT_REPLACED,
+ "This recording was intentionally edited or replaced. Its original source is retained and will not replace the current video.",
+ );
+ }
+ const replacesArtifact =
+ verification !== undefined &&
+ (job.source !== null || job.verification !== null) &&
+ !sameArtifact(verification, job);
+ if (created || replacesArtifact) {
+ if (replacesArtifact) {
+ job = candidate;
+ await tx
+ .update(videoProcessingJobs)
+ .set(job)
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ }
+ const upload = {
+ phase: "processing" as const,
+ processingProgress: 0,
+ processingMessage: "Securing recording source...",
+ processingError: null,
+ updatedAt: now,
+ };
+ await tx
+ .insert(videoUploads)
+ .values({ videoId, ...upload })
+ .onDuplicateKeyUpdate({ set: upload });
+ return { job, created: true };
+ }
+ if (job.ownerId !== userId) throw new Error("Recording owner changed");
+ if (verification) {
+ const needsReverification =
+ job.state === "verified" &&
+ ((verification.artifact.kind === "mp4" && !job.verification) ||
+ (verification.requiredAudio && !job.verification?.requiredAudio));
+ const mergedVerification = {
+ ...verification,
+ requiredAudio:
+ verification.requiredAudio ||
+ job.verification?.requiredAudio === true,
+ };
+ job = { ...job, verification: mergedVerification, updatedAt: now };
+ await tx
+ .update(videoProcessingJobs)
+ .set({ verification: mergedVerification, updatedAt: now })
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ if (needsReverification) {
+ job = {
+ ...job,
+ state: "retry",
+ leaseExpiresAt: null,
+ nextRetryAt: now,
+ workflowRunId: null,
+ };
+ await tx
+ .update(videoProcessingJobs)
+ .set(job)
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ }
+ }
+ if (job.state === "source-blocked" && !job.source) {
+ job = {
+ ...job,
+ state: "committing",
+ output: null,
+ leaseExpiresAt: null,
+ nextRetryAt: now,
+ workflowRunId: null,
+ errorCode: null,
+ errorMessage: null,
+ updatedAt: now,
+ };
+ await tx
+ .update(videoProcessingJobs)
+ .set(job)
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ }
+ return { job, created: false };
+ });
+}
+
+export async function getProcessingState({
+ videoId,
+ generation,
+}: {
+ videoId: Video.VideoId;
+ generation?: string;
+}): Promise<DesktopRecordingJob | null> {
+ const [row] = await db()
+ .select()
+ .from(videoProcessingJobs)
+ .where(
+ and(
+ eq(videoProcessingJobs.videoId, videoId),
+ generation ? eq(videoProcessingJobs.generation, generation) : undefined,
+ ),
+ )
+ .limit(1);
+ return row ? parseDesktopRecordingJob(row) : null;
+}
+
+export async function claimProcessingAttempt({
+ videoId,
+ generation,
+ now = new Date(),
+}: {
+ videoId: Video.VideoId;
+ generation: string;
+ now?: Date;
+}): Promise<DesktopRecordingAttempt | null> {
+ return db().transaction(async (tx) => {
+ const [row] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(
+ and(
+ eq(videoProcessingJobs.videoId, videoId),
+ eq(videoProcessingJobs.generation, generation),
+ ),
+ )
+ .for("update");
+ if (!row) return null;
+ const job = parseDesktopRecordingJob(row);
+ if (!isDesktopRecordingJobRecoverable(job, now)) return null;
+ const attempt: DesktopRecordingAttempt = {
+ ...job,
+ state: job.source ? "processing" : "committing",
+ attemptId: randomUUID(),
+ attemptCount: job.attemptCount + 1,
+ leaseExpiresAt: new Date(now.getTime() + DESKTOP_RECORDING_LEASE_MS),
+ remoteJobId: null,
+ errorCode: null,
+ errorMessage: null,
+ updatedAt: now,
+ };
+ await tx
+ .update(videoProcessingJobs)
+ .set(attempt)
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ const upload = {
+ phase: "processing" as const,
+ processingProgress: 0,
+ processingMessage: job.source
+ ? "Verifying and processing recording..."
+ : "Securing recording source...",
+ processingError: null,
+ updatedAt: now,
+ };
+ await tx
+ .insert(videoUploads)
+ .values({ videoId, ...upload })
+ .onDuplicateKeyUpdate({ set: upload });
+ return attempt;
+ });
+}
+
+function attemptCondition(fence: DesktopRecordingAttemptFence) {
+ return and(
+ eq(videoProcessingJobs.videoId, fence.videoId),
+ eq(videoProcessingJobs.generation, fence.generation),
+ eq(videoProcessingJobs.attemptId, fence.attemptId),
+ inArray(videoProcessingJobs.state, ["committing", "queued", "processing"]),
+ );
+}
+
+function affectedRows(result: unknown) {
+ const item = Array.isArray(result) ? result[0] : result;
+ if (!item || typeof item !== "object" || !("affectedRows" in item)) return 0;
+ return typeof item.affectedRows === "number" ? item.affectedRows : 0;
+}
+
+export async function initializeSourceCommitCheckpoint(
+ fence: DesktopRecordingAttemptFence,
+): Promise<DesktopRecordingSourceCheckpoint | null> {
+ const now = new Date();
+ return db().transaction(async (tx) => {
+ const [row] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(and(attemptCondition(fence), isNull(videoProcessingJobs.source)))
+ .for("update");
+ if (!row || !row.leaseExpiresAt || row.leaseExpiresAt <= now) return null;
+ if (row.output !== null) {
+ const checkpoint = desktopRecordingSourceCheckpointSchema.parse(
+ row.output,
+ );
+ if (checkpoint.generation !== fence.generation) return null;
+ return checkpoint;
+ }
+ const checkpoint: DesktopRecordingSourceCheckpoint = {
+ kind: "desktop-recording-source-commit",
+ version: 1,
+ generation: fence.generation,
+ snapshotId: randomUUID(),
+ revision: 0,
+ phase: "plan",
+ cursor: 0,
+ planRoots: [],
+ receiptRoots: [],
+ };
+ await tx
+ .update(videoProcessingJobs)
+ .set({ output: checkpoint, updatedAt: now })
+ .where(attemptCondition(fence));
+ return checkpoint;
+ });
+}
+
+export async function persistSourceCommitCheckpoint(
+ fence: DesktopRecordingAttemptFence,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+): Promise<boolean> {
+ const parsed = desktopRecordingSourceCheckpointSchema.parse(checkpoint);
+ if (parsed.generation !== fence.generation) return false;
+ const now = new Date();
+ return db().transaction(async (tx) => {
+ const [row] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(and(attemptCondition(fence), isNull(videoProcessingJobs.source)))
+ .for("update");
+ if (!row || !row.leaseExpiresAt || row.leaseExpiresAt <= now) return false;
+ const previous = desktopRecordingSourceCheckpointSchema.parse(row.output);
+ if (
+ previous.generation !== parsed.generation ||
+ previous.snapshotId !== parsed.snapshotId ||
+ previous.revision + 1 !== parsed.revision
+ )
+ return false;
+ await tx
+ .update(videoProcessingJobs)
+ .set({
+ output: parsed,
+ leaseExpiresAt: new Date(now.getTime() + DESKTOP_RECORDING_LEASE_MS),
+ updatedAt: now,
+ })
+ .where(attemptCondition(fence));
+ return true;
+ });
+}
+
+export async function persistCommittedSource(
+ fence: DesktopRecordingAttemptFence,
+ source: DesktopRecordingSource,
+): Promise<boolean> {
+ let parsed = sourceSchema.parse(source);
+ const now = new Date();
+ return db().transaction(async (tx) => {
+ const [row] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(attemptCondition(fence))
+ .for("update");
+ if (!row || !row.leaseExpiresAt || row.leaseExpiresAt <= now) return false;
+ const current = parseDesktopRecordingJob(row);
+ if (current.source) {
+ return current.source.inventorySha256 === parsed.inventorySha256;
+ }
+ const verification = current.verification;
+ if (
+ verification &&
+ (!sameArtifact(verification, { ...current, source: parsed }) ||
+ (parsed.kind === "segments" &&
+ verification.requiredAudio &&
+ !parsed.requiredAudio))
+ ) {
+ await tx
+ .update(videoProcessingJobs)
+ .set({
+ state: "retry",
+ output: null,
+ leaseExpiresAt: null,
+ nextRetryAt: new Date(
+ now.getTime() + getDesktopRecordingRetryDelay(1),
+ ),
+ errorCode: "source-intent-changed",
+ errorMessage:
+ "The completed upload changed while its source was being secured. Retrying its snapshot.",
+ updatedAt: now,
+ })
+ .where(attemptCondition(fence));
+ return false;
+ }
+ if (
+ parsed.kind === "mp4" &&
+ parsed.mp4 &&
+ verification?.artifact.kind === "mp4"
+ ) {
+ parsed = {
+ ...parsed,
+ requiredAudio: parsed.requiredAudio || verification.requiredAudio,
+ mp4: { ...parsed.mp4, duration: verification.artifact.duration },
+ };
+ }
+ await tx
+ .update(videoProcessingJobs)
+ .set({
+ source: parsed,
+ output: null,
+ manifestSha256: parsed.manifestSha256 ?? null,
+ state: "processing",
+ leaseExpiresAt: new Date(now.getTime() + DESKTOP_RECORDING_LEASE_MS),
+ updatedAt: now,
+ })
+ .where(attemptCondition(fence));
+ return true;
+ });
+}
+
+export async function attachRemoteJob({
+ remoteJobId,
+ ...fence
+}: DesktopRecordingAttemptFence & { remoteJobId: string }): Promise<boolean> {
+ const now = new Date();
+ const result = await db()
+ .update(videoProcessingJobs)
+ .set({ remoteJobId, updatedAt: now })
+ .where(
+ and(
+ attemptCondition(fence),
+ gt(videoProcessingJobs.leaseExpiresAt, now),
+ or(
+ isNull(videoProcessingJobs.remoteJobId),
+ eq(videoProcessingJobs.remoteJobId, remoteJobId),
+ ),
+ ),
+ );
+ return affectedRows(result) > 0;
+}
+
+export async function heartbeatAttempt({
+ now = new Date(),
+ ...fence
+}: DesktopRecordingAttemptFence & { now?: Date }): Promise<boolean> {
+ const result = await db()
+ .update(videoProcessingJobs)
+ .set({
+ leaseExpiresAt: new Date(now.getTime() + DESKTOP_RECORDING_LEASE_MS),
+ updatedAt: now,
+ })
+ .where(
+ and(attemptCondition(fence), gt(videoProcessingJobs.leaseExpiresAt, now)),
+ );
+ return affectedRows(result) > 0;
+}
+
+export async function scheduleRetry({
+ errorCode,
+ errorMessage,
+ now = new Date(),
+ nextRetryAt,
+ ...fence
+}: DesktopRecordingAttemptFence & {
+ errorCode: string;
+ errorMessage: string;
+ now?: Date;
+ nextRetryAt?: Date;
+}): Promise<boolean> {
+ return db().transaction(async (tx) => {
+ const [row] = await tx
+ .select({ attemptCount: videoProcessingJobs.attemptCount })
+ .from(videoProcessingJobs)
+ .where(attemptCondition(fence))
+ .for("update");
+ if (!row) return false;
+ await tx
+ .update(videoProcessingJobs)
+ .set({
+ state: "retry",
+ leaseExpiresAt: null,
+ nextRetryAt:
+ nextRetryAt ??
+ new Date(
+ now.getTime() + getDesktopRecordingRetryDelay(row.attemptCount),
+ ),
+ errorCode,
+ errorMessage,
+ updatedAt: now,
+ })
+ .where(attemptCondition(fence));
+ await tx
+ .update(videoUploads)
+ .set({
+ phase: "processing",
+ processingMessage: "Processing interrupted. Retrying automatically...",
+ processingError: null,
+ updatedAt: now,
+ })
+ .where(eq(videoUploads.videoId, fence.videoId));
+ return true;
+ });
+}
+
+export async function markSourceBlocked({
+ errorCode,
+ errorMessage,
+ now = new Date(),
+ ...fence
+}: DesktopRecordingAttemptFence & {
+ errorCode: string;
+ errorMessage: string;
+ now?: Date;
+}): Promise<boolean> {
+ return db().transaction(async (tx) => {
+ const result = await tx
+ .update(videoProcessingJobs)
+ .set({
+ state: "source-blocked",
+ leaseExpiresAt: null,
+ nextRetryAt: new Date(
+ now.getTime() + DESKTOP_RECORDING_SOURCE_RETRY_MS,
+ ),
+ errorCode,
+ errorMessage,
+ updatedAt: now,
+ })
+ .where(attemptCondition(fence));
+ if (affectedRows(result) === 0) return false;
+ await tx
+ .update(videoUploads)
+ .set({
+ phase: "error",
+ processingMessage:
+ "Waiting for complete recording source. Uploaded files are retained.",
+ processingError: `${errorCode}: ${errorMessage}`,
+ updatedAt: now,
+ })
+ .where(eq(videoUploads.videoId, fence.videoId));
+ return true;
+ });
+}
+
+export async function attachWorkflowRun({
+ videoId,
+ generation,
+ workflowRunId,
+}: {
+ videoId: Video.VideoId;
+ generation: string;
+ workflowRunId: string;
+}): Promise<void> {
+ await db()
+ .update(videoProcessingJobs)
+ .set({ workflowRunId })
+ .where(
+ and(
+ eq(videoProcessingJobs.videoId, videoId),
+ eq(videoProcessingJobs.generation, generation),
+ ),
+ );
+}
+
+export async function recordWorkflowDispatchFailure({
+ videoId,
+ generation,
+ errorMessage,
+ now = new Date(),
+}: {
+ videoId: Video.VideoId;
+ generation: string;
+ errorMessage: string;
+ now?: Date;
+}): Promise<void> {
+ await db()
+ .update(videoProcessingJobs)
+ .set({
+ workflowRunId: null,
+ nextRetryAt: new Date(now.getTime() + getDesktopRecordingRetryDelay(1)),
+ errorCode: "workflow-dispatch-failed",
+ errorMessage,
+ updatedAt: now,
+ })
+ .where(
+ and(
+ eq(videoProcessingJobs.videoId, videoId),
+ eq(videoProcessingJobs.generation, generation),
+ inArray(videoProcessingJobs.state, ["committing", "queued", "retry"]),
+ or(
+ isNull(videoProcessingJobs.leaseExpiresAt),
+ lte(videoProcessingJobs.leaseExpiresAt, now),
+ ),
+ ),
+ );
+}
+
+export async function deferWithoutMediaServer(
+ fence: DesktopRecordingAttemptFence,
+): Promise<boolean> {
+ const now = new Date();
+ return db().transaction(async (tx) => {
+ const result = await tx
+ .update(videoProcessingJobs)
+ .set({
+ state: "queued",
+ leaseExpiresAt: null,
+ nextRetryAt: new Date(
+ now.getTime() + 24 * DESKTOP_RECORDING_SOURCE_RETRY_MS,
+ ),
+ errorCode: "media-server-unconfigured",
+ errorMessage:
+ "Source is retained; full output verification requires a media server.",
+ updatedAt: now,
+ })
+ .where(attemptCondition(fence));
+ if (affectedRows(result) === 0) return false;
+ await tx
+ .delete(videoUploads)
+ .where(eq(videoUploads.videoId, fence.videoId));
+ return true;
+ });
+}
+
+export async function retireDesktopRecordingJobForOutputReplacement(
+ tx: Parameters<Parameters<ReturnType<typeof db>["transaction"]>[0]>[0],
+ {
+ videoId,
+ userId,
+ now = new Date(),
+ }: { videoId: Video.VideoId; userId: User.UserId; now?: Date },
+): Promise<void> {
+ const retired = {
+ generation: randomUUID(),
+ state: "source-blocked" as const,
+ attemptId: null,
+ leaseExpiresAt: null,
+ nextRetryAt: now,
+ workflowRunId: null,
+ remoteJobId: null,
+ errorCode: DESKTOP_RECORDING_OUTPUT_REPLACED,
+ errorMessage:
+ "Original source retained after an intentional video edit or replacement.",
+ updatedAt: now,
+ };
+ await tx
+ .insert(videoProcessingJobs)
+ .values({ ...newJob({ videoId, userId, now }), ...retired })
+ .onDuplicateKeyUpdate({ set: retired });
+}
+
+export async function listRecoverableSegmentJobs({
+ now = new Date(),
+ limit = 20,
+}: {
+ now?: Date;
+ limit?: number;
+} = {}): Promise<DesktopRecordingJob[]> {
+ const batchSize = Math.max(1, Math.min(limit, 100));
+ const pending = await db()
+ .select(getTableColumns(videoProcessingJobs))
+ .from(videoProcessingJobs)
+ .innerJoin(videos, eq(videos.id, videoProcessingJobs.videoId))
+ .where(
+ and(
+ inArray(videoProcessingJobs.state, [
+ "committing",
+ "queued",
+ "retry",
+ "source-blocked",
+ ]),
+ or(
+ ne(videoProcessingJobs.state, "source-blocked"),
+ isNull(videoProcessingJobs.source),
+ ),
+ or(
+ isNull(videoProcessingJobs.errorCode),
+ and(
+ ne(
+ videoProcessingJobs.errorCode,
+ DESKTOP_RECORDING_OUTPUT_REPLACED,
+ ),
+ ne(videoProcessingJobs.errorCode, DESKTOP_RECORDING_DELETING),
+ ),
+ ),
+ lte(videoProcessingJobs.nextRetryAt, now),
+ or(
+ isNull(videoProcessingJobs.leaseExpiresAt),
+ lte(videoProcessingJobs.leaseExpiresAt, now),
+ ),
+ ),
+ )
+ .orderBy(
+ asc(videoProcessingJobs.nextRetryAt),
+ asc(videoProcessingJobs.videoId),
+ )
+ .limit(batchSize);
+ const expired = await db()
+ .select(getTableColumns(videoProcessingJobs))
+ .from(videoProcessingJobs)
+ .innerJoin(videos, eq(videos.id, videoProcessingJobs.videoId))
+ .where(
+ and(
+ eq(videoProcessingJobs.state, "processing"),
+ lte(videoProcessingJobs.leaseExpiresAt, now),
+ ),
+ )
+ .orderBy(
+ asc(videoProcessingJobs.leaseExpiresAt),
+ asc(videoProcessingJobs.videoId),
+ )
+ .limit(batchSize);
+ return [...pending, ...expired]
+ .map(parseDesktopRecordingJob)
+ .filter((job) => isDesktopRecordingJobRecoverable(job, now))
+ .sort((left, right) => {
+ const leftDue = left.leaseExpiresAt ?? left.nextRetryAt;
+ const rightDue = right.leaseExpiresAt ?? right.nextRetryAt;
+ return (
+ leftDue.getTime() - rightDue.getTime() ||
+ left.videoId.localeCompare(right.videoId)
+ );
+ })
+ .slice(0, batchSize);
+}
diff --git a/apps/web/lib/desktop-recording-publication.ts b/apps/web/lib/desktop-recording-publication.ts
new file mode 100644
index 000000000..818cc3bfc
--- /dev/null
+++ b/apps/web/lib/desktop-recording-publication.ts
@@ -0,0 +1,371 @@
+import { isDeepStrictEqual } from "node:util";
+import { db } from "@cap/database";
+import {
+ videoProcessingJobs,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
+import { Storage } from "@cap/web-backend/src/Storage/index";
+import { Video } from "@cap/web-domain";
+import { and, eq, sql } from "drizzle-orm";
+import { z } from "zod";
+import {
+ DESKTOP_RECORDING_LEASE_MS,
+ type DesktopRecordingJob,
+ getProcessingState,
+ markSourceBlocked,
+ parseDesktopRecordingJob,
+ scheduleRetry,
+} from "@/lib/desktop-recording-jobs";
+import { getDesktopRecordingOutputKey } from "@/lib/desktop-recording-source";
+import {
+ createVerifiedRecordingReceipt,
+ type RecordingReceiptOptions,
+} from "@/lib/desktop-recording-upload-status";
+import {
+ recordingObjectIdentitySchema,
+ recordingOutputSchema,
+ recordingOutputSha256Schema,
+ recordingSourceProofSchema,
+ recordingVerificationSchema,
+} from "@/lib/desktop-recording-verification";
+import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota-cache";
+import { decodeStorageVideo } from "@/lib/video-storage";
+import { runWorkflowPromise } from "@/lib/workflow-runtime";
+
+export const desktopRecordingProgressSchema = z.object({
+ jobId: z.string().min(1),
+ videoId: z.string().min(1),
+ generation: z.string().min(1),
+ attemptId: z.string().min(1),
+ phase: z.enum([
+ "queued",
+ "downloading",
+ "probing",
+ "processing",
+ "uploading",
+ "generating_thumbnail",
+ "complete",
+ "error",
+ "cancelled",
+ ]),
+ progress: z.number().finite().min(0).max(100),
+ message: z.string().optional(),
+ error: z.string().optional(),
+ errorCode: z.string().optional(),
+ metadata: recordingOutputSchema
+ .extend({ fps: z.number().finite().nonnegative() })
+ .optional(),
+ recordingVerification: z
+ .object({
+ request: recordingVerificationSchema,
+ fullDecode: z.literal(true),
+ objectIdentity: recordingObjectIdentitySchema,
+ outputKey: z.string().min(1),
+ outputSha256: recordingOutputSha256Schema,
+ sourceProof: recordingSourceProofSchema.optional(),
+ })
+ .optional(),
+});
+
+type RecordingProgress = z.infer<typeof desktopRecordingProgressSchema>;
+
+export function isCurrentDesktopRecordingAttempt(
+ job: DesktopRecordingJob,
+ payload: Pick<RecordingProgress, "generation" | "attemptId" | "jobId">,
+ now = new Date(),
+) {
+ return (
+ job.generation === payload.generation &&
+ job.attemptId === payload.attemptId &&
+ job.state === "processing" &&
+ (job.remoteJobId === null || job.remoteJobId === payload.jobId) &&
+ job.leaseExpiresAt !== null &&
+ job.leaseExpiresAt > now
+ );
+}
+
+export function validateDesktopRecordingCompletion(
+ job: DesktopRecordingJob,
+ payload: RecordingProgress,
+) {
+ const proof = payload.recordingVerification;
+ const source = job.source;
+ if (!proof || !source || !payload.metadata || !job.attemptId) {
+ throw new Error(
+ "Recording completion has no committed source or verified output",
+ );
+ }
+ const request = job.verification ?? proof.request;
+ if (!isDeepStrictEqual(request.artifact, proof.request.artifact)) {
+ throw new Error(
+ "Recording output does not match the current verification request",
+ );
+ }
+ const options: RecordingReceiptOptions = {
+ outputKey: proof.outputKey,
+ outputSha256: proof.outputSha256,
+ };
+ if (source.kind === "segments") {
+ const expectedKey = getDesktopRecordingOutputKey(
+ job.ownerId,
+ job.videoId,
+ job.generation,
+ job.attemptId,
+ );
+ if (
+ proof.outputKey !== expectedKey ||
+ request.artifact.kind !== "segments" ||
+ request.artifact.manifestSha256 !== source.manifestSha256 ||
+ proof.sourceProof?.manifestSha256 !== source.manifestSha256 ||
+ proof.sourceProof?.inventorySha256 !== source.inventorySha256 ||
+ !proof.sourceProof.sourcePreserved ||
+ (source.requiredAudio &&
+ (!proof.sourceProof.hasAudio || !proof.sourceProof.audioVerified))
+ ) {
+ throw new Error(
+ "Recording output is not a verified preservation of the committed source",
+ );
+ }
+ options.sourceProof = proof.sourceProof;
+ } else {
+ const expectedKey = source.inventoryKey.replace(
+ /inventory\.json$/,
+ "mp4/0.mp4",
+ );
+ if (
+ !source.mp4 ||
+ ((source.requiredAudio || request.requiredAudio) &&
+ !proof.request.requiredAudio) ||
+ request.artifact.kind !== "mp4" ||
+ proof.outputKey !== expectedKey ||
+ request.artifact.objectIdentity !== source.mp4.objectIdentity ||
+ request.artifact.fileSize !== source.mp4.fileSize ||
+ (source.mp4.duration !== undefined &&
+ request.artifact.duration !== source.mp4.duration)
+ ) {
+ throw new Error(
+ "Verified recording does not match its retained MP4 source",
+ );
+ }
+ options.sourceObjectIdentity = source.mp4.objectIdentity;
+ }
+ if (
+ (source.requiredAudio || request.requiredAudio) &&
+ !payload.metadata.audioCodec
+ ) {
+ throw new Error("Verified recording is missing required audio");
+ }
+ return { request, options, metadata: payload.metadata, proof };
+}
+
+async function findRecordingAssets(
+ video: typeof videos.$inferSelect,
+ outputKey: string,
+) {
+ const [bucket] = await runWorkflowPromise(
+ Storage.getAccessForVideo(decodeStorageVideo(video)),
+ );
+ const prefix = outputKey.replace(/\.mp4$/, "");
+ const thumbnailKey = `${prefix}/screenshot.jpg`;
+ const previewKey = `${prefix}/preview.gif`;
+ const present = await Promise.all([
+ runWorkflowPromise(bucket.headObject(thumbnailKey)).catch(() => null),
+ runWorkflowPromise(bucket.headObject(previewKey)).catch(() => null),
+ ]);
+ return {
+ ...(present[0]?.ContentLength ? { thumbnailKey } : {}),
+ ...(present[1]?.ContentLength ? { previewKey } : {}),
+ };
+}
+
+export async function applyDesktopRecordingProgress(input: unknown): Promise<{
+ handled: boolean;
+ allowLegacyProcessing?: boolean;
+ published?: boolean;
+ status?: 200 | 400 | 409 | 503;
+}> {
+ const envelope = desktopRecordingProgressSchema
+ .pick({ videoId: true, jobId: true, phase: true, progress: true })
+ .extend({
+ generation: z.string().min(1).optional(),
+ attemptId: z.string().min(1).optional(),
+ })
+ .safeParse(input);
+ if (
+ !envelope.success ||
+ Boolean(envelope.data.generation) !== Boolean(envelope.data.attemptId)
+ ) {
+ return { handled: true, status: 400 };
+ }
+ const videoId = Video.VideoId.make(envelope.data.videoId);
+ const job = await getProcessingState({ videoId });
+ if (!job) {
+ return envelope.data.generation
+ ? { handled: true, status: 409 }
+ : { handled: false };
+ }
+ if (!envelope.data.generation) {
+ const [upload] = await db()
+ .select({ rawFileKey: videoUploads.rawFileKey })
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId));
+ const recordingProof =
+ typeof input === "object" &&
+ input !== null &&
+ ("recordingVerification" in input || "manifestSha256" in input);
+ const allowLegacyProcessing =
+ (job.state === "verified" || job.errorCode === "output-replaced") &&
+ !recordingProof &&
+ Boolean(upload?.rawFileKey);
+ return {
+ handled: !allowLegacyProcessing,
+ ...(allowLegacyProcessing ? { allowLegacyProcessing: true } : {}),
+ status: 200,
+ };
+ }
+ const parsed = desktopRecordingProgressSchema.safeParse(input);
+ if (!parsed.success) return { handled: true, status: 400 };
+ const payload = parsed.data;
+ if (!isCurrentDesktopRecordingAttempt(job, payload)) {
+ return { handled: true, status: 200 };
+ }
+ const fence = {
+ videoId,
+ generation: payload.generation,
+ attemptId: payload.attemptId,
+ };
+ if (payload.phase === "error" || payload.phase === "cancelled") {
+ const errorCode = payload.errorCode ?? "processing-unavailable";
+ const errorMessage =
+ payload.error ??
+ payload.message ??
+ "Recording processing was interrupted";
+ if (
+ ["source-invalid", "source-missing", "source-changed"].includes(errorCode)
+ ) {
+ await markSourceBlocked({ ...fence, errorCode, errorMessage });
+ } else {
+ await scheduleRetry({ ...fence, errorCode, errorMessage });
+ }
+ return { handled: true, status: 200 };
+ }
+ if (payload.phase !== "complete") {
+ await db().transaction(async (tx) => {
+ const [current] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(eq(videoProcessingJobs.videoId, videoId))
+ .for("update");
+ if (
+ !current ||
+ !isCurrentDesktopRecordingAttempt(
+ parseDesktopRecordingJob(current),
+ payload,
+ )
+ )
+ return;
+ const now = new Date();
+ await tx
+ .update(videoProcessingJobs)
+ .set({
+ leaseExpiresAt: new Date(now.getTime() + DESKTOP_RECORDING_LEASE_MS),
+ updatedAt: now,
+ })
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ await tx
+ .update(videoUploads)
+ .set({
+ phase:
+ payload.phase === "generating_thumbnail"
+ ? "generating_thumbnail"
+ : "processing",
+ processingProgress: Math.round(payload.progress),
+ processingMessage:
+ payload.message ?? "Verifying and processing recording...",
+ processingError: null,
+ updatedAt: now,
+ })
+ .where(eq(videoUploads.videoId, videoId));
+ });
+ return { handled: true, status: 200 };
+ }
+ const completion = validateDesktopRecordingCompletion(job, payload);
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId));
+ if (!video || video.ownerId !== job.ownerId)
+ return { handled: true, status: 409 };
+ const receipt = await createVerifiedRecordingReceipt(
+ video,
+ completion.request,
+ completion.metadata,
+ true,
+ completion.proof.objectIdentity,
+ completion.options,
+ );
+ const outputKey = completion.proof.outputKey;
+ const assets =
+ job.source?.kind === "segments"
+ ? await findRecordingAssets(video, outputKey)
+ : {};
+ const published = await db().transaction(async (tx) => {
+ const [current] = await tx
+ .select()
+ .from(videoProcessingJobs)
+ .where(eq(videoProcessingJobs.videoId, videoId))
+ .for("update");
+ const currentJob = current ? parseDesktopRecordingJob(current) : null;
+ if (
+ !currentJob ||
+ !isCurrentDesktopRecordingAttempt(currentJob, payload) ||
+ !isDeepStrictEqual(currentJob.source, job.source) ||
+ !isDeepStrictEqual(currentJob.verification, job.verification)
+ )
+ return false;
+ const [currentVideo] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId))
+ .for("update");
+ if (
+ !currentVideo ||
+ currentVideo.ownerId !== job.ownerId ||
+ currentVideo.bucket !== video.bucket ||
+ currentVideo.storageIntegrationId !== video.storageIntegrationId ||
+ !isDeepStrictEqual(currentVideo.source, video.source)
+ )
+ return false;
+ const now = new Date();
+ await tx
+ .update(videos)
+ .set({
+ source: { type: "desktopMP4", outputKey, ...assets },
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.desktopRecordingUpload', JSON_EXTRACT(${JSON.stringify(receipt)}, '$'))`,
+ duration: completion.metadata.duration,
+ width: completion.metadata.width,
+ height: completion.metadata.height,
+ fps: Math.round(completion.metadata.fps),
+ })
+ .where(and(eq(videos.id, videoId), eq(videos.ownerId, job.ownerId)));
+ await tx
+ .update(videoProcessingJobs)
+ .set({
+ state: "verified",
+ output: { ...receipt, verifiedAt: now.toISOString() },
+ leaseExpiresAt: null,
+ errorCode: null,
+ errorMessage: null,
+ updatedAt: now,
+ })
+ .where(eq(videoProcessingJobs.videoId, videoId));
+ await tx.delete(videoUploads).where(eq(videoUploads.videoId, videoId));
+ return true;
+ });
+ if (!published) return { handled: true, status: 503 };
+ await invalidateGoogleDriveStorageQuotaCache(
+ video.storageIntegrationId,
+ ).catch(() => undefined);
+ return { handled: true, status: 200, published: true };
+}
diff --git a/apps/web/lib/desktop-recording-source-checkpoint.ts b/apps/web/lib/desktop-recording-source-checkpoint.ts
new file mode 100644
index 000000000..328a6d253
--- /dev/null
+++ b/apps/web/lib/desktop-recording-source-checkpoint.ts
@@ -0,0 +1,60 @@
+import { z } from "zod";
+
+export const SOURCE_COMMIT_PAGE_SIZE = 16;
+export const SOURCE_COMMIT_PART_BATCH_SIZE = 4;
+export const SOURCE_COMMIT_PART_PAGE_SIZE = 64;
+export const SOURCE_COMMIT_MAX_OBJECTS = 100_002;
+
+const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
+const identifier = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
+export const sourceCommitReferenceSchema = z.object({
+ key: z.string().min(1),
+ sha256,
+});
+export const sourceCommitPageReferenceSchema =
+ sourceCommitReferenceSchema.extend({
+ start: z.number().int().nonnegative().max(SOURCE_COMMIT_MAX_OBJECTS),
+ count: z.number().int().positive().max(SOURCE_COMMIT_MAX_OBJECTS),
+ level: z.number().int().nonnegative().max(17),
+ });
+export const sourceCommitPartSchema = z.object({
+ ETag: z.string().min(1),
+ PartNumber: z.number().int().min(1).max(10_000),
+});
+const forest = z.array(sourceCommitPageReferenceSchema).max(18);
+
+export const desktopRecordingSourceCheckpointSchema = z.object({
+ kind: z.literal("desktop-recording-source-commit"),
+ version: z.literal(1),
+ generation: identifier,
+ snapshotId: identifier,
+ revision: z.number().int().nonnegative(),
+ phase: z.enum(["plan", "enumerate", "copy", "verify", "finalize"]),
+ plan: sourceCommitReferenceSchema.optional(),
+ cursor: z.number().int().nonnegative().max(SOURCE_COMMIT_MAX_OBJECTS),
+ planRoots: forest,
+ receiptRoots: forest,
+ multipart: z
+ .object({
+ position: z.number().int().nonnegative().max(SOURCE_COMMIT_MAX_OBJECTS),
+ key: z.string().min(1),
+ originalIdentity: z.string().min(1),
+ size: z.number().int().positive().safe(),
+ uploadId: z.string().min(1),
+ partSize: z.number().int().positive().safe(),
+ nextPartNumber: z.number().int().min(1).max(10_001),
+ partRoots: forest,
+ pendingParts: z
+ .array(sourceCommitPartSchema)
+ .max(SOURCE_COMMIT_PART_PAGE_SIZE),
+ })
+ .optional(),
+});
+
+export type SourceCommitReference = z.infer<typeof sourceCommitReferenceSchema>;
+export type SourceCommitPageReference = z.infer<
+ typeof sourceCommitPageReferenceSchema
+>;
+export type DesktopRecordingSourceCheckpoint = z.infer<
+ typeof desktopRecordingSourceCheckpointSchema
+>;
diff --git a/apps/web/lib/desktop-recording-source.ts b/apps/web/lib/desktop-recording-source.ts
new file mode 100644
index 000000000..1da52b0f6
--- /dev/null
+++ b/apps/web/lib/desktop-recording-source.ts
@@ -0,0 +1,1397 @@
+import { createHash, randomUUID } from "node:crypto";
+import type { videos } from "@cap/database/schema";
+import { Storage } from "@cap/web-backend/src/Storage/index";
+import { getPublishedRecordingOutputKey } from "@cap/web-backend/src/Storage/recording-output";
+import { Video } from "@cap/web-domain";
+import { Effect, Option, Runtime } from "effect";
+import { z } from "zod";
+import {
+ type DesktopRecordingSourceCheckpoint,
+ desktopRecordingSourceCheckpointSchema,
+ SOURCE_COMMIT_MAX_OBJECTS,
+ SOURCE_COMMIT_PAGE_SIZE,
+ SOURCE_COMMIT_PART_BATCH_SIZE,
+ SOURCE_COMMIT_PART_PAGE_SIZE,
+ type SourceCommitPageReference,
+ type SourceCommitReference,
+ sourceCommitPageReferenceSchema,
+ sourceCommitPartSchema,
+} from "@/lib/desktop-recording-source-checkpoint";
+import {
+ type RecordingVerification,
+ readCompletedRecordingManifest,
+ recordingObjectIdentitySchema,
+ recordingVerificationSchema,
+} from "@/lib/desktop-recording-verification";
+import { decodeStorageVideo } from "@/lib/video-storage";
+import { runWorkflowPromise } from "@/lib/workflow-runtime";
+
+const sha256Schema = z.string().regex(/^[a-f0-9]{64}$/);
+const identifierSchema = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
+const sourceObjectSchema = z.object({
+ key: z.string().min(1),
+ originalKey: z.string().min(1),
+ originalIdentity: recordingObjectIdentitySchema,
+ objectIdentity: recordingObjectIdentitySchema,
+ size: z.number().int().positive().safe(),
+ track: z.enum(["video", "audio", "mp4"]),
+ index: z.number().int().nonnegative(),
+});
+
+export const desktopRecordingSourceSchema = z.object({
+ version: z.literal(1),
+ kind: z.enum(["segments", "mp4"]),
+ manifestSha256: sha256Schema.optional(),
+ inventorySha256: sha256Schema,
+ inventoryKey: z.string().min(1),
+ requiredAudio: z.boolean(),
+ mp4: z
+ .object({
+ fileSize: z.number().int().positive().safe(),
+ duration: z.number().finite().positive().optional(),
+ objectIdentity: z.string().min(1),
+ })
+ .optional(),
+});
+
+export type DesktopRecordingSource = z.infer<
+ typeof desktopRecordingSourceSchema
+>;
+type SourceObject = z.infer<typeof sourceObjectSchema>;
+type DbVideo = typeof videos.$inferSelect;
+type RecordingStorage = Effect.Effect.Success<
+ ReturnType<typeof Storage.getAccessForVideo>
+>[0];
+
+const sourceInventorySchema = z.object({
+ version: z.literal(1),
+ kind: z.enum(["segments", "mp4"]),
+ manifestSha256: sha256Schema.optional(),
+ objects: z.array(sourceObjectSchema).min(1).max(100_002),
+});
+
+export class DesktopRecordingSourceError extends Error {
+ constructor(
+ readonly code:
+ | "source-incomplete"
+ | "source-changed"
+ | "source-missing"
+ | "source-invalid",
+ message: string,
+ ) {
+ super(message);
+ this.name = "DesktopRecordingSourceError";
+ }
+}
+
+class SourceCopyExpiredError extends Error {}
+
+function hash(content: string) {
+ return createHash("sha256").update(content).digest("hex");
+}
+
+function sourceStorageError(error: unknown): unknown {
+ if (error instanceof DesktopRecordingSourceError) return error;
+ const pending = [error];
+ const visited = new Set<unknown>();
+ for (let index = 0; index < pending.length && index < 16; index++) {
+ const value = pending[index];
+ if (typeof value !== "object" || value === null || visited.has(value))
+ continue;
+ visited.add(value);
+ if (Runtime.isFiberFailure(value))
+ pending.push(value[Runtime.FiberFailureCauseId]);
+ const record = value as Record<string, unknown>;
+ if (record.name === "NoSuchUpload") {
+ return new SourceCopyExpiredError(
+ "Recording source multipart copy expired",
+ );
+ }
+ const metadata = record.$metadata;
+ const status =
+ record.name === "GoogleDriveRequestError"
+ ? record.status
+ : typeof metadata === "object" &&
+ metadata !== null &&
+ "httpStatusCode" in metadata
+ ? metadata.httpStatusCode
+ : undefined;
+ if (status === 412 || record.name === "PreconditionFailed") {
+ return new DesktopRecordingSourceError(
+ "source-changed",
+ "Recording source changed while its durable copy was being secured",
+ );
+ }
+ if (
+ status === 404 ||
+ record.name === "NoSuchKey" ||
+ record.name === "NotFound"
+ ) {
+ return new DesktopRecordingSourceError(
+ "source-missing",
+ "Recording source is missing or has not finished uploading; existing files are retained",
+ );
+ }
+ pending.push(record.cause, record.error);
+ }
+ return error;
+}
+
+function sourcePrefix(video: DbVideo) {
+ return `${video.ownerId}/${video.id}/.recording/sources/`;
+}
+
+function assertSourceKey(video: DbVideo, key: string) {
+ if (
+ !key.startsWith(sourcePrefix(video)) ||
+ key.includes("..") ||
+ !/^[a-zA-Z0-9_./-]+$/.test(key)
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-invalid",
+ "Recording source snapshot belongs to a different recording",
+ );
+ }
+}
+
+export function getDesktopRecordingOutputKey(
+ ownerId: string,
+ videoId: string,
+ generation: string,
+ attemptId: string,
+) {
+ identifierSchema.parse(ownerId);
+ identifierSchema.parse(videoId);
+ identifierSchema.parse(generation);
+ identifierSchema.parse(attemptId);
+ return `${ownerId}/${videoId}/.recording/outputs/${generation}/${attemptId}.mp4`;
+}
+
+async function readRequiredObject(bucket: RecordingStorage, key: string) {
+ const content = await runWorkflowPromise(bucket.getObject(key)).catch(
+ (error: unknown) => {
+ throw sourceStorageError(error);
+ },
+ );
+ if (Option.isNone(content)) {
+ throw new DesktopRecordingSourceError(
+ "source-missing",
+ "The recording source manifest has not finished uploading",
+ );
+ }
+ return content.value;
+}
+
+const originalObjectSchema = sourceObjectSchema.omit({
+ key: true,
+ objectIdentity: true,
+});
+type OriginalObject = z.infer<typeof originalObjectSchema>;
+type WorkflowContext = Effect.Effect.Context<
+ Parameters<typeof runWorkflowPromise>[0]
+>;
+type SourceRun = <A, E>(
+ operation: Effect.Effect<A, E, WorkflowContext>,
+) => Promise<A>;
+type SourceContext = {
+ video: DbVideo;
+ bucket: RecordingStorage;
+ prefix: string;
+ run: SourceRun;
+};
+type TreeKind = "plan" | "objects" | "parts";
+
+const sourcePlanSchema = z.object({
+ version: z.literal(1),
+ kind: z.enum(["segments", "mp4"]),
+ manifestSha256: sha256Schema.optional(),
+ manifestKey: z.string().optional(),
+ originalManifestKey: z.string().optional(),
+ requiredAudio: z.boolean(),
+ videoCount: z.number().int().nonnegative(),
+ audioCount: z.number().int().nonnegative(),
+ objectCount: z.number().int().positive().max(SOURCE_COMMIT_MAX_OBJECTS),
+ mp4: z
+ .object({
+ originalKey: z.string(),
+ duration: z.number().positive().finite().optional(),
+ })
+ .optional(),
+});
+type SourcePlan = z.infer<typeof sourcePlanSchema>;
+
+const treePageSchema = z.discriminatedUnion("type", [
+ z.object({
+ version: z.literal(1),
+ type: z.literal("leaf"),
+ kind: z.enum(["plan", "objects", "parts"]),
+ scope: z.string(),
+ start: z.number().int().nonnegative(),
+ entries: z.array(z.unknown()).min(1).max(SOURCE_COMMIT_PART_PAGE_SIZE),
+ }),
+ z.object({
+ version: z.literal(1),
+ type: z.literal("branch"),
+ kind: z.enum(["plan", "objects", "parts"]),
+ scope: z.string(),
+ children: z.tuple([
+ sourceCommitPageReferenceSchema,
+ sourceCommitPageReferenceSchema,
+ ]),
+ }),
+]);
+const pagedInventorySchema = z.object({
+ version: z.literal(2),
+ kind: z.literal("segments"),
+ manifestSha256: sha256Schema,
+ objectCount: z.number().int().positive().max(SOURCE_COMMIT_MAX_OBJECTS),
+ scope: sha256Schema,
+ roots: z.array(sourceCommitPageReferenceSchema).min(1).max(18),
+});
+const committedInventorySchema = z.union([
+ sourceInventorySchema,
+ pagedInventorySchema,
+]);
+const SOURCE_COMMIT_STEP_TIMEOUT_MS = 180_000;
+const SOURCE_COMMIT_IO_TIMEOUT_MS = 60_000;
+
+function invalidSource(message: string): never {
+ throw new DesktopRecordingSourceError("source-invalid", message);
+}
+
+function parseSourceJson(content: string): unknown {
+ try {
+ return JSON.parse(content) as unknown;
+ } catch {
+ return invalidSource("Recording source metadata is not valid JSON");
+ }
+}
+
+async function mapBounded<T, R>(
+ items: T[],
+ operation: (item: T) => Promise<R>,
+) {
+ const output = new Array<R>(items.length);
+ const entries = items.entries();
+ let failure: unknown;
+ await Promise.all(
+ Array.from({ length: Math.min(8, items.length) }, async () => {
+ while (failure === undefined) {
+ const next = entries.next();
+ if (next.done) return;
+ const [index, item] = next.value;
+ try {
+ output[index] = await operation(item);
+ } catch (error) {
+ failure = error;
+ }
+ }
+ }),
+ );
+ if (failure !== undefined) throw failure;
+ return output;
+}
+
+function assertContextKey(context: SourceContext, key: string) {
+ assertSourceKey(context.video, key);
+ if (!key.startsWith(`${context.prefix}/`))
+ invalidSource("Recording checkpoint points outside its snapshot");
+}
+
+async function readSourceText(context: SourceContext, key: string) {
+ const result = await context.run(context.bucket.getObject(key));
+ if (Option.isNone(result))
+ throw new DesktopRecordingSourceError(
+ "source-missing",
+ "A required recording source object is missing",
+ );
+ return result.value;
+}
+
+async function readReference(
+ context: SourceContext,
+ reference: SourceCommitReference,
+) {
+ assertContextKey(context, reference.key);
+ const content = await readSourceText(context, reference.key);
+ if (hash(content) !== reference.sha256)
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "A recording source checkpoint changed after it was saved",
+ );
+ return parseSourceJson(content);
+}
+
+async function writeSourceText(
+ context: SourceContext,
+ key: string,
+ content: string,
+) {
+ assertContextKey(context, key);
+ await context.run(
+ context.bucket.putObject(key, content, { contentType: "application/json" }),
+ );
+ if ((await readSourceText(context, key)) !== content)
+ throw new Error("Durable recording source readback did not match");
+ return { key, sha256: hash(content) };
+}
+
+async function writeReference(context: SourceContext, value: unknown) {
+ return writeSourceText(
+ context,
+ `${context.prefix}/pages/${randomUUID()}.json`,
+ JSON.stringify(value),
+ );
+}
+
+function treeCount(roots: SourceCommitPageReference[]) {
+ let next = 0;
+ let previousLevel = 18;
+ for (const root of roots) {
+ if (root.start !== next || root.level >= previousLevel)
+ invalidSource(
+ "Recording source pages have an incomplete or overlapping inventory",
+ );
+ next += root.count;
+ previousLevel = root.level;
+ }
+ return next;
+}
+
+async function appendTree(
+ context: SourceContext,
+ roots: SourceCommitPageReference[],
+ kind: TreeKind,
+ scope: string,
+ entries: unknown[],
+) {
+ if (entries.length === 0 || entries.length > SOURCE_COMMIT_PART_PAGE_SIZE)
+ invalidSource("Invalid source page size");
+ const start = treeCount(roots);
+ const leaf = await writeReference(context, {
+ version: 1,
+ type: "leaf",
+ kind,
+ scope,
+ start,
+ entries,
+ });
+ let next: SourceCommitPageReference = {
+ ...leaf,
+ start,
+ count: entries.length,
+ level: 0,
+ };
+ const result = [...roots];
+ while (result.at(-1)?.level === next.level) {
+ const previous = result.pop();
+ if (!previous || previous.start + previous.count !== next.start)
+ invalidSource("Recording source page order changed");
+ const branch = await writeReference(context, {
+ version: 1,
+ type: "branch",
+ kind,
+ scope,
+ children: [previous, next],
+ });
+ next = {
+ ...branch,
+ start: previous.start,
+ count: previous.count + next.count,
+ level: next.level + 1,
+ };
+ }
+ result.push(next);
+ return result;
+}
+
+async function readTree<T>(
+ context: SourceContext,
+ roots: SourceCommitPageReference[],
+ kind: TreeKind,
+ scope: string,
+ schema: z.ZodType<T>,
+ start = 0,
+ end = treeCount(roots),
+): Promise<T[]> {
+ const count = treeCount(roots);
+ if (start < 0 || end > count || end < start)
+ invalidSource("Recording source page range is invalid");
+ const overlaps = (ref: SourceCommitPageReference) =>
+ ref.start < end && ref.start + ref.count > start;
+ let pending = roots.filter(overlaps);
+ const leaves: { start: number; entries: T[] }[] = [];
+ while (pending.length > 0) {
+ const pages = await mapBounded(pending, async (reference) => {
+ const parsed = treePageSchema.safeParse(
+ await readReference(context, reference),
+ );
+ if (!parsed.success) invalidSource("Recording source page is invalid");
+ const page = parsed.data;
+ if (page.kind !== kind || page.scope !== scope)
+ invalidSource("Recording source page belongs to a different snapshot");
+ if (page.type === "leaf") {
+ if (
+ reference.level !== 0 ||
+ page.start !== reference.start ||
+ page.entries.length !== reference.count
+ )
+ invalidSource(
+ "Recording source leaf does not match its committed range",
+ );
+ return {
+ children: [],
+ leaf: {
+ start: page.start,
+ entries: page.entries.map((entry) => {
+ const parsed = schema.safeParse(entry);
+ if (!parsed.success)
+ invalidSource(
+ "Recording source page contains an invalid receipt",
+ );
+ return parsed.data;
+ }),
+ },
+ };
+ }
+ const [left, right] = page.children;
+ if (
+ left.start !== reference.start ||
+ left.start + left.count !== right.start ||
+ left.count + right.count !== reference.count ||
+ left.level + 1 !== reference.level ||
+ right.level !== left.level
+ )
+ invalidSource(
+ "Recording source branch does not match its committed range",
+ );
+ return { children: page.children.filter(overlaps), leaf: null };
+ });
+ pending = [];
+ for (const page of pages) {
+ pending.push(...page.children);
+ if (page.leaf) leaves.push(page.leaf);
+ }
+ }
+ leaves.sort((left, right) => left.start - right.start);
+ const result = leaves.flatMap((leaf) =>
+ leaf.entries.slice(
+ Math.max(0, start - leaf.start),
+ Math.min(leaf.entries.length, end - leaf.start),
+ ),
+ );
+ if (result.length !== end - start)
+ invalidSource("Recording source page inventory is incomplete");
+ return result;
+}
+
+async function createSourcePlan(
+ context: SourceContext,
+ verification?: RecordingVerification,
+): Promise<SourceCommitReference> {
+ const segmented =
+ context.video.source.type === "desktopSegments" ||
+ verification?.artifact.kind === "segments";
+ const directory = `${context.prefix}/plans/${randomUUID()}`;
+ let plan: SourcePlan;
+ if (segmented) {
+ const segments = new Video.SegmentsSource({
+ videoId: context.video.id,
+ ownerId: context.video.ownerId,
+ });
+ const originalManifestKey = segments.getManifestKey();
+ const content = await readSourceText(context, originalManifestKey);
+ let manifest: ReturnType<typeof readCompletedRecordingManifest>;
+ try {
+ manifest = readCompletedRecordingManifest(content);
+ } catch {
+ throw new DesktopRecordingSourceError(
+ "source-incomplete",
+ "The recording manifest is incomplete or invalid; the original is retained",
+ );
+ }
+ if (
+ verification?.artifact.kind === "mp4" ||
+ (verification?.artifact.kind === "segments" &&
+ verification.artifact.manifestSha256 !== manifest.manifestSha256) ||
+ (verification?.requiredAudio && !manifest.hasAudio)
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "The completed source does not match the recording verification request",
+ );
+ }
+ const videoCount = manifest.videoSegments.length + 1;
+ const audioCount = manifest.hasAudio
+ ? manifest.audioSegments.length + 1
+ : 0;
+ if (videoCount + audioCount > SOURCE_COMMIT_MAX_OBJECTS)
+ invalidSource(
+ "The recording source inventory exceeds the supported object count",
+ );
+ const manifestKey = `${directory}/manifest.json`;
+ await writeSourceText(context, manifestKey, content);
+ plan = {
+ version: 1,
+ kind: "segments",
+ manifestSha256: manifest.manifestSha256,
+ manifestKey,
+ originalManifestKey,
+ requiredAudio: manifest.hasAudio,
+ videoCount,
+ audioCount,
+ objectCount: videoCount + audioCount,
+ };
+ } else {
+ const video = context.video;
+ const publishedKey = getPublishedRecordingOutputKey(video);
+ if (
+ video.source.type === "desktopMP4" &&
+ video.source.outputKey &&
+ !publishedKey
+ )
+ invalidSource(
+ "Published recording source belongs to a different recording",
+ );
+ const artifact = verification?.artifact;
+ plan = {
+ version: 1,
+ kind: "mp4",
+ requiredAudio: verification?.requiredAudio ?? false,
+ videoCount: 0,
+ audioCount: 0,
+ objectCount: 1,
+ mp4: {
+ originalKey:
+ artifact?.kind === "mp4"
+ ? `${video.ownerId}/${video.id}/result.mp4`
+ : (publishedKey ?? `${video.ownerId}/${video.id}/result.mp4`),
+ ...(artifact?.kind === "mp4" ? { duration: artifact.duration } : {}),
+ },
+ };
+ }
+ return writeSourceText(
+ context,
+ `${directory}/plan.json`,
+ JSON.stringify(plan),
+ );
+}
+
+function originalAt(video: DbVideo, plan: SourcePlan, position: number) {
+ if (position < 0 || position >= plan.objectCount)
+ invalidSource("Recording source position is invalid");
+ if (plan.kind === "mp4") {
+ if (!plan.mp4 || plan.objectCount !== 1)
+ invalidSource("Recording MP4 plan is incomplete");
+ return {
+ originalKey: plan.mp4.originalKey,
+ track: "mp4" as const,
+ index: 0,
+ };
+ }
+ const segments = new Video.SegmentsSource({
+ videoId: video.id,
+ ownerId: video.ownerId,
+ });
+ const track =
+ position < plan.videoCount ? ("video" as const) : ("audio" as const);
+ const index = track === "video" ? position : position - plan.videoCount;
+ const originalKey =
+ track === "video"
+ ? index === 0
+ ? segments.getVideoInitKey()
+ : segments.getVideoSegmentKey(index)
+ : index === 0
+ ? segments.getAudioInitKey()
+ : segments.getAudioSegmentKey(index);
+ return { originalKey, track, index };
+}
+
+async function captureOriginal(
+ context: SourceContext,
+ original: ReturnType<typeof originalAt>,
+ verification?: RecordingVerification,
+): Promise<OriginalObject> {
+ const head = await context.run(
+ context.bucket.headObject(original.originalKey),
+ );
+ if (
+ !head.ETag ||
+ !recordingObjectIdentitySchema.safeParse(head.ETag).success ||
+ !head.ContentLength ||
+ !Number.isSafeInteger(head.ContentLength) ||
+ head.ContentLength < 0
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-missing",
+ `Recording ${original.track} fragment ${original.index} is missing or incomplete`,
+ );
+ }
+ if (
+ original.track === "mp4" &&
+ verification?.artifact.kind === "mp4" &&
+ (verification.artifact.fileSize !== head.ContentLength ||
+ verification.artifact.objectIdentity !== head.ETag)
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "Uploaded recording does not match its original object identity",
+ );
+ }
+ return { ...original, originalIdentity: head.ETag, size: head.ContentLength };
+}
+
+function copyMetadata(original: OriginalObject) {
+ return {
+ "cap-source-identity": hash(original.originalIdentity),
+ "cap-source-size": String(original.size),
+ "cap-source-key": hash(original.originalKey),
+ };
+}
+
+async function checkOriginal(context: SourceContext, original: OriginalObject) {
+ const head = await context.run(
+ context.bucket.headObject(original.originalKey),
+ );
+ if (
+ head.ETag !== original.originalIdentity ||
+ head.ContentLength !== original.size
+ )
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "Recording source changed while its durable snapshot was being saved",
+ );
+}
+
+async function checkCopy(
+ context: SourceContext,
+ original: OriginalObject,
+ key: string,
+ expectedIdentity?: string,
+): Promise<SourceObject> {
+ assertContextKey(context, key);
+ const [head] = await Promise.all([
+ context.run(context.bucket.headObject(key)),
+ checkOriginal(context, original),
+ ]);
+ if (
+ !head.ETag ||
+ !recordingObjectIdentitySchema.safeParse(head.ETag).success ||
+ head.ContentLength !== original.size ||
+ (expectedIdentity !== undefined && head.ETag !== expectedIdentity)
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "Recording snapshot does not match its durable copy receipt",
+ );
+ }
+ if (
+ context.bucket.provider === "s3" &&
+ Object.entries(copyMetadata(original)).some(
+ ([name, value]) => head.Metadata?.[name] !== value,
+ )
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "Recording snapshot is missing its original source identity",
+ );
+ }
+ return { ...original, key, objectIdentity: head.ETag };
+}
+
+function objectDirectory(key: string) {
+ return key.slice(0, key.lastIndexOf("/", key.lastIndexOf("/") - 1));
+}
+
+async function saveObjectReceipt(context: SourceContext, object: SourceObject) {
+ await writeSourceText(
+ context,
+ `${objectDirectory(object.key)}/receipt.json`,
+ JSON.stringify(object),
+ );
+ return object;
+}
+
+async function reusableCopy(
+ context: SourceContext,
+ original: OriginalObject,
+ position: number,
+) {
+ await checkOriginal(context, original);
+ let continuationToken: string | undefined;
+ for (let page = 0; page < 4; page++) {
+ const listing = await context.run(
+ context.bucket.listObjects({
+ prefix: `${context.prefix}/copies/${position}/`,
+ maxKeys: 32,
+ continuationToken,
+ }),
+ );
+ for (const candidate of listing.Contents ?? []) {
+ const key = candidate.Key;
+ if (!key || !/\.(mp4|m4s)$/.test(key)) continue;
+ assertContextKey(context, key);
+ const receiptKey = `${objectDirectory(key)}/receipt.json`;
+ const content = await context.run(context.bucket.getObject(receiptKey));
+ if (Option.isSome(content)) {
+ const receipt = sourceObjectSchema.safeParse(JSON.parse(content.value));
+ if (
+ receipt.success &&
+ receipt.data.key === key &&
+ receipt.data.originalKey === original.originalKey &&
+ receipt.data.originalIdentity === original.originalIdentity &&
+ receipt.data.size === original.size &&
+ receipt.data.track === original.track &&
+ receipt.data.index === original.index
+ ) {
+ return checkCopy(context, original, key, receipt.data.objectIdentity);
+ }
+ } else if (context.bucket.provider === "s3") {
+ const head = await context.run(context.bucket.headObject(key));
+ if (
+ head.ContentLength === original.size &&
+ Object.entries(copyMetadata(original)).every(
+ ([name, value]) => head.Metadata?.[name] === value,
+ )
+ ) {
+ return saveObjectReceipt(
+ context,
+ await checkCopy(context, original, key),
+ );
+ }
+ }
+ }
+ if (!listing.IsTruncated || !listing.NextContinuationToken) return null;
+ continuationToken = listing.NextContinuationToken;
+ }
+ return null;
+}
+
+function newCopyKey(
+ context: SourceContext,
+ original: OriginalObject,
+ position: number,
+) {
+ return `${context.prefix}/copies/${position}/${randomUUID()}/${original.track}/${original.index}${original.index === 0 ? ".mp4" : ".m4s"}`;
+}
+
+async function copySmallObject(
+ context: SourceContext,
+ original: OriginalObject,
+ position: number,
+) {
+ const existing = await reusableCopy(context, original, position);
+ if (existing) return existing;
+ const key = newCopyKey(context, original, position);
+ await context.run(
+ context.bucket.copyObject(
+ `${context.bucket.bucketName}/${original.originalKey}`,
+ key,
+ {
+ CopySourceIfMatch: original.originalIdentity,
+ IfNoneMatch: "*",
+ MetadataDirective: "REPLACE",
+ Metadata: copyMetadata(original),
+ ContentType: original.track === "audio" ? "audio/mp4" : "video/mp4",
+ },
+ ),
+ );
+ return saveObjectReceipt(context, await checkCopy(context, original, key));
+}
+
+async function advanceMultipartCopy(
+ context: SourceContext,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+ original: OriginalObject,
+ scope: string,
+): Promise<
+ | { multipart: NonNullable<DesktopRecordingSourceCheckpoint["multipart"]> }
+ | { object: SourceObject }
+ | { reset: true }
+> {
+ try {
+ return await copyMultipartPartBatch(context, checkpoint, original, scope);
+ } catch (error) {
+ const classified = sourceStorageError(error);
+ if (
+ !(classified instanceof SourceCopyExpiredError) &&
+ !(
+ classified instanceof DesktopRecordingSourceError &&
+ classified.code === "source-missing"
+ )
+ )
+ throw error;
+ const completed = await reusableCopy(context, original, checkpoint.cursor);
+ return completed ? { object: completed } : { reset: true };
+ }
+}
+
+async function copyMultipartPartBatch(
+ context: SourceContext,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+ original: OriginalObject,
+ scope: string,
+): Promise<
+ | { multipart: NonNullable<DesktopRecordingSourceCheckpoint["multipart"]> }
+ | { object: SourceObject }
+> {
+ const existing = await reusableCopy(context, original, checkpoint.cursor);
+ if (existing) return { object: existing };
+ const multipart = checkpoint.multipart;
+ if (!multipart) {
+ const key = newCopyKey(context, original, checkpoint.cursor);
+ const partSize = Math.max(
+ 128 * 1024 ** 2,
+ Math.ceil(original.size / 9_999 / 1024 ** 2) * 1024 ** 2,
+ );
+ if (partSize > 5 * 1024 ** 3)
+ invalidSource(
+ "Recording exceeds the supported multipart source copy size",
+ );
+ const upload = await context.run(
+ context.bucket.multipart.create(key, {
+ Metadata: copyMetadata(original),
+ ContentType: original.track === "audio" ? "audio/mp4" : "video/mp4",
+ }),
+ );
+ if (!upload.UploadId)
+ throw new Error("Source copy did not create an upload");
+ return {
+ multipart: {
+ position: checkpoint.cursor,
+ key,
+ originalIdentity: original.originalIdentity,
+ size: original.size,
+ uploadId: upload.UploadId,
+ partSize,
+ nextPartNumber: 1,
+ partRoots: [],
+ pendingParts: [],
+ },
+ };
+ }
+ assertContextKey(context, multipart.key);
+ if (
+ multipart.position !== checkpoint.cursor ||
+ multipart.originalIdentity !== original.originalIdentity ||
+ multipart.size !== original.size
+ )
+ invalidSource("Multipart source checkpoint does not match its source plan");
+ const partScope = `${scope}:${multipart.uploadId}`;
+ const partCount = Math.ceil(original.size / multipart.partSize);
+ if (multipart.nextPartNumber <= partCount) {
+ const copyPart = context.bucket.multipart.copyPart;
+ if (!copyPart) throw new Error("Multipart source copy is unavailable");
+ const numbers = Array.from(
+ {
+ length: Math.min(
+ SOURCE_COMMIT_PART_BATCH_SIZE,
+ partCount - multipart.nextPartNumber + 1,
+ ),
+ },
+ (_, index) => multipart.nextPartNumber + index,
+ );
+ const parts = await mapBounded(numbers, async (PartNumber) => {
+ const offset = (PartNumber - 1) * multipart.partSize;
+ const copied = await context.run(
+ copyPart(multipart.key, multipart.uploadId, PartNumber, {
+ CopySource: `${context.bucket.bucketName}/${original.originalKey}`,
+ CopySourceIfMatch: original.originalIdentity,
+ CopySourceRange: `bytes=${offset}-${Math.min(original.size - 1, offset + multipart.partSize - 1)}`,
+ }),
+ );
+ if (!copied.CopyPartResult?.ETag)
+ throw new Error("Source copy part has no object identity");
+ return { ETag: copied.CopyPartResult.ETag, PartNumber };
+ });
+ let pendingParts = [...multipart.pendingParts, ...parts];
+ let partRoots = multipart.partRoots;
+ if (pendingParts.length >= SOURCE_COMMIT_PART_PAGE_SIZE) {
+ partRoots = await appendTree(
+ context,
+ partRoots,
+ "parts",
+ partScope,
+ pendingParts.slice(0, SOURCE_COMMIT_PART_PAGE_SIZE),
+ );
+ pendingParts = pendingParts.slice(SOURCE_COMMIT_PART_PAGE_SIZE);
+ }
+ return {
+ multipart: {
+ ...multipart,
+ partRoots,
+ pendingParts,
+ nextPartNumber: multipart.nextPartNumber + parts.length,
+ },
+ };
+ }
+ const parts = [
+ ...(await readTree(
+ context,
+ multipart.partRoots,
+ "parts",
+ partScope,
+ sourceCommitPartSchema,
+ )),
+ ...multipart.pendingParts,
+ ];
+ if (
+ parts.length !== partCount ||
+ parts.some((part, index) => part.PartNumber !== index + 1)
+ )
+ invalidSource("Multipart recording source is missing a copied range");
+ await context.run(
+ context.bucket.multipart.complete(multipart.key, multipart.uploadId, {
+ MultipartUpload: { Parts: parts },
+ IfNoneMatch: "*",
+ }),
+ );
+ return {
+ object: await saveObjectReceipt(
+ context,
+ await checkCopy(context, original, multipart.key),
+ ),
+ };
+}
+
+async function advanceSourceSnapshot(
+ context: SourceContext,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+ verification?: RecordingVerification,
+) {
+ const next = { ...checkpoint, revision: checkpoint.revision + 1 };
+ if (checkpoint.phase === "plan") {
+ return {
+ checkpoint: {
+ ...next,
+ phase: "enumerate" as const,
+ plan: await createSourcePlan(context, verification),
+ },
+ };
+ }
+ if (!checkpoint.plan)
+ invalidSource("Recording source checkpoint has no committed plan");
+ const parsedPlan = sourcePlanSchema.safeParse(
+ await readReference(context, checkpoint.plan),
+ );
+ if (!parsedPlan.success) invalidSource("Recording source plan is invalid");
+ const plan = parsedPlan.data;
+ const scope = checkpoint.plan.sha256;
+ if (checkpoint.phase === "enumerate") {
+ if (treeCount(checkpoint.planRoots) !== checkpoint.cursor)
+ invalidSource("Recording source plan cursor is incomplete");
+ const end = Math.min(
+ plan.objectCount,
+ checkpoint.cursor + SOURCE_COMMIT_PAGE_SIZE,
+ );
+ const originals = await mapBounded(
+ Array.from(
+ { length: end - checkpoint.cursor },
+ (_, index) => checkpoint.cursor + index,
+ ),
+ (position) =>
+ captureOriginal(
+ context,
+ originalAt(context.video, plan, position),
+ verification,
+ ),
+ );
+ const planRoots = await appendTree(
+ context,
+ checkpoint.planRoots,
+ "plan",
+ scope,
+ originals,
+ );
+ return {
+ checkpoint: {
+ ...next,
+ planRoots,
+ cursor: end === plan.objectCount ? 0 : end,
+ phase:
+ end === plan.objectCount ? ("copy" as const) : ("enumerate" as const),
+ },
+ };
+ }
+ if (treeCount(checkpoint.planRoots) !== plan.objectCount)
+ invalidSource("Recording source plan omits required fragments");
+ if (checkpoint.phase === "copy") {
+ if (treeCount(checkpoint.receiptRoots) !== checkpoint.cursor)
+ invalidSource(
+ "Recording copy receipts do not match their checkpoint cursor",
+ );
+ let originals = await readTree(
+ context,
+ checkpoint.planRoots,
+ "plan",
+ scope,
+ originalObjectSchema,
+ checkpoint.cursor,
+ Math.min(plan.objectCount, checkpoint.cursor + SOURCE_COMMIT_PAGE_SIZE),
+ );
+ const large =
+ context.bucket.provider === "s3"
+ ? originals.findIndex((original) => original.size > 5 * 1024 ** 3)
+ : -1;
+ let objects: SourceObject[];
+ if (large === 0) {
+ const original = originals[0];
+ if (!original) invalidSource("Multipart recording source is missing");
+ const result = await advanceMultipartCopy(
+ context,
+ checkpoint,
+ original,
+ scope,
+ );
+ if ("multipart" in result)
+ return { checkpoint: { ...next, multipart: result.multipart } };
+ if ("reset" in result)
+ return { checkpoint: { ...next, multipart: undefined } };
+ objects = [result.object];
+ } else {
+ if (checkpoint.multipart)
+ invalidSource("Multipart checkpoint changed source type");
+ if (large > 0) originals = originals.slice(0, large);
+ objects = await mapBounded(
+ originals.map((original, index) => ({
+ original,
+ position: checkpoint.cursor + index,
+ })),
+ ({ original, position }) =>
+ copySmallObject(context, original, position),
+ );
+ }
+ const receiptRoots = await appendTree(
+ context,
+ checkpoint.receiptRoots,
+ "objects",
+ scope,
+ objects,
+ );
+ const cursor = checkpoint.cursor + objects.length;
+ return {
+ checkpoint: {
+ ...next,
+ receiptRoots,
+ multipart: undefined,
+ cursor: cursor === plan.objectCount ? 0 : cursor,
+ phase:
+ cursor === plan.objectCount ? ("verify" as const) : ("copy" as const),
+ },
+ };
+ }
+ if (treeCount(checkpoint.receiptRoots) !== plan.objectCount)
+ invalidSource("Recording snapshot is missing required copy receipts");
+ if (checkpoint.phase === "verify") {
+ const end = Math.min(
+ plan.objectCount,
+ checkpoint.cursor + SOURCE_COMMIT_PAGE_SIZE,
+ );
+ const [originals, objects] = await Promise.all([
+ readTree(
+ context,
+ checkpoint.planRoots,
+ "plan",
+ scope,
+ originalObjectSchema,
+ checkpoint.cursor,
+ end,
+ ),
+ readTree(
+ context,
+ checkpoint.receiptRoots,
+ "objects",
+ scope,
+ sourceObjectSchema,
+ checkpoint.cursor,
+ end,
+ ),
+ ]);
+ await mapBounded(
+ objects.map((object, index) => ({ object, original: originals[index] })),
+ async ({ object, original }) => {
+ if (
+ !original ||
+ object.originalKey !== original.originalKey ||
+ object.originalIdentity !== original.originalIdentity ||
+ object.size !== original.size ||
+ object.index !== original.index ||
+ object.track !== original.track
+ )
+ invalidSource(
+ "Recording copy receipt does not match its source plan",
+ );
+ await checkCopy(context, original, object.key, object.objectIdentity);
+ },
+ );
+ return {
+ checkpoint: {
+ ...next,
+ cursor: end,
+ phase:
+ end === plan.objectCount
+ ? ("finalize" as const)
+ : ("verify" as const),
+ },
+ };
+ }
+ if (checkpoint.cursor !== plan.objectCount)
+ invalidSource("Recording source has not completed verification");
+ let inventoryKey: string;
+ let inventory: unknown;
+ let mp4: DesktopRecordingSource["mp4"];
+ if (plan.kind === "mp4") {
+ const [object] = await readTree(
+ context,
+ checkpoint.receiptRoots,
+ "objects",
+ scope,
+ sourceObjectSchema,
+ );
+ if (!object || object.track !== "mp4" || !plan.mp4)
+ invalidSource("Recording MP4 inventory is incomplete");
+ await checkCopy(context, object, object.key, object.objectIdentity);
+ inventoryKey = `${objectDirectory(object.key)}/inventory.json`;
+ inventory = { version: 1, kind: "mp4", objects: [object] };
+ mp4 = {
+ fileSize: object.size,
+ objectIdentity: object.originalIdentity,
+ ...(plan.mp4.duration === undefined
+ ? {}
+ : { duration: plan.mp4.duration }),
+ };
+ } else {
+ if (!plan.manifestKey || !plan.originalManifestKey || !plan.manifestSha256)
+ invalidSource("Recording manifest is missing from its source plan");
+ assertContextKey(context, plan.manifestKey);
+ const [saved, current] = await Promise.all([
+ readSourceText(context, plan.manifestKey),
+ readSourceText(context, plan.originalManifestKey),
+ ]);
+ if (saved !== current || hash(saved) !== plan.manifestSha256)
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "Recording manifest changed while its durable snapshot was being saved",
+ );
+ const directory = `${context.prefix}/commits/${randomUUID()}`;
+ await writeSourceText(context, `${directory}/manifest.json`, saved);
+ inventoryKey = `${directory}/inventory.json`;
+ inventory = {
+ version: 2,
+ kind: "segments",
+ manifestSha256: plan.manifestSha256,
+ objectCount: plan.objectCount,
+ scope,
+ roots: checkpoint.receiptRoots,
+ };
+ }
+ const saved = await writeSourceText(
+ context,
+ inventoryKey,
+ JSON.stringify(inventory),
+ );
+ return {
+ source: desktopRecordingSourceSchema.parse({
+ version: 1,
+ kind: plan.kind,
+ manifestSha256: plan.manifestSha256,
+ inventorySha256: saved.sha256,
+ inventoryKey,
+ requiredAudio: plan.requiredAudio,
+ mp4,
+ }),
+ };
+}
+
+export async function advanceDesktopRecordingSourceCommit(
+ video: DbVideo,
+ checkpoint: DesktopRecordingSourceCheckpoint,
+ verification?: RecordingVerification,
+ onProgress?: () => Promise<void>,
+): Promise<
+ | { checkpoint: DesktopRecordingSourceCheckpoint }
+ | { source: DesktopRecordingSource }
+> {
+ const parsed = desktopRecordingSourceCheckpointSchema.parse(checkpoint);
+ if (verification) recordingVerificationSchema.parse(verification);
+ identifierSchema.parse(video.ownerId);
+ identifierSchema.parse(video.id);
+ const deadline = Date.now() + SOURCE_COMMIT_STEP_TIMEOUT_MS;
+ let heartbeatFailure: unknown;
+ let heartbeat: Promise<void> | undefined;
+ const pulse = () => {
+ if (!onProgress || heartbeat || heartbeatFailure !== undefined) return;
+ heartbeat = onProgress()
+ .catch((error: unknown) => {
+ heartbeatFailure = error;
+ })
+ .finally(() => {
+ heartbeat = undefined;
+ });
+ };
+ await onProgress?.();
+ const timer = onProgress ? setInterval(pulse, 30_000) : undefined;
+ const run: SourceRun = async (operation) => {
+ if (heartbeatFailure !== undefined) throw heartbeatFailure;
+ const remaining = deadline - Date.now();
+ if (remaining <= 0)
+ throw new Error("Recording source checkpoint step timed out");
+ return runWorkflowPromise(
+ operation.pipe(
+ Effect.timeout(Math.min(SOURCE_COMMIT_IO_TIMEOUT_MS, remaining)),
+ ),
+ );
+ };
+ try {
+ const [bucket] = await run(
+ Storage.getAccessForVideo(decodeStorageVideo(video), {
+ resolvePublishedOutput: false,
+ }),
+ );
+ const result = await advanceSourceSnapshot(
+ {
+ video,
+ bucket,
+ run,
+ prefix: `${sourcePrefix(video)}${parsed.generation}/${parsed.snapshotId}`,
+ },
+ parsed,
+ verification,
+ );
+ await heartbeat;
+ if (heartbeatFailure !== undefined) throw heartbeatFailure;
+ await onProgress?.();
+ return result;
+ } catch (error) {
+ throw sourceStorageError(error);
+ } finally {
+ if (timer !== undefined) clearInterval(timer);
+ await heartbeat;
+ }
+}
+
+export async function commitDesktopRecordingSource(
+ video: DbVideo,
+ generation: string,
+ verification?: RecordingVerification,
+ onProgress?: () => Promise<void>,
+): Promise<DesktopRecordingSource> {
+ let checkpoint: DesktopRecordingSourceCheckpoint = {
+ kind: "desktop-recording-source-commit",
+ version: 1,
+ generation,
+ snapshotId: randomUUID(),
+ revision: 0,
+ phase: "plan",
+ cursor: 0,
+ planRoots: [],
+ receiptRoots: [],
+ };
+ for (;;) {
+ const result = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ verification,
+ onProgress,
+ );
+ if ("source" in result) return result.source;
+ checkpoint = result.checkpoint;
+ }
+}
+
+export async function buildDesktopRecordingSourceUrls(
+ video: DbVideo,
+ source: DesktopRecordingSource,
+) {
+ assertSourceKey(video, source.inventoryKey);
+ const [bucket] = await runWorkflowPromise(
+ Storage.getAccessForVideo(decodeStorageVideo(video)),
+ );
+ const content = await readRequiredObject(bucket, source.inventoryKey);
+ if (hash(content) !== source.inventorySha256) {
+ throw new DesktopRecordingSourceError(
+ "source-changed",
+ "The committed recording inventory has changed",
+ );
+ }
+ const parsed = committedInventorySchema.safeParse(parseSourceJson(content));
+ if (!parsed.success) invalidSource("Recording inventory is invalid");
+ const inventory = parsed.data;
+ if (
+ inventory.kind !== source.kind ||
+ inventory.manifestSha256 !== source.manifestSha256
+ ) {
+ throw new DesktopRecordingSourceError(
+ "source-invalid",
+ "Recording inventory does not match its committed source",
+ );
+ }
+ if (
+ inventory.version === 2 &&
+ treeCount(inventory.roots) !== inventory.objectCount
+ ) {
+ invalidSource(
+ "Recording inventory page ranges do not cover its complete source",
+ );
+ }
+ const run: SourceRun = async (operation) => {
+ try {
+ return await runWorkflowPromise(operation);
+ } catch (error) {
+ throw sourceStorageError(error);
+ }
+ };
+ const objects =
+ inventory.version === 1
+ ? inventory.objects
+ : await readTree(
+ {
+ video,
+ bucket,
+ run,
+ prefix: sourcePrefix(video).slice(0, -1),
+ },
+ inventory.roots,
+ "objects",
+ inventory.scope,
+ sourceObjectSchema,
+ );
+ if (inventory.version === 2 && objects.length !== inventory.objectCount)
+ invalidSource("Recording inventory omits required fragments");
+ const sourceObjects = await mapBounded(objects, async (object) => {
+ assertSourceKey(video, object.key);
+ const url = await runWorkflowPromise(
+ bucket.getInternalSignedObjectUrl(object.key, { expiresIn: 6 * 60 * 60 }),
+ );
+ return { ...object, url };
+ });
+ const videoObjects = sourceObjects.filter(
+ (object) => object.track === "video",
+ );
+ const audioObjects = sourceObjects.filter(
+ (object) => object.track === "audio",
+ );
+ const mp4 = sourceObjects.find((object) => object.track === "mp4");
+ return {
+ manifestSha256: source.manifestSha256,
+ inventorySha256: source.inventorySha256,
+ sourceObjects: sourceObjects.map(({ url, objectIdentity, size }) => ({
+ url,
+ objectIdentity,
+ size,
+ })),
+ videoInitUrl: videoObjects.find((object) => object.index === 0)?.url,
+ videoSegmentUrls: videoObjects
+ .filter((object) => object.index > 0)
+ .map((object) => object.url),
+ audioInitUrl: audioObjects.find((object) => object.index === 0)?.url,
+ audioSegmentUrls: audioObjects
+ .filter((object) => object.index > 0)
+ .map((object) => object.url),
+ videoUrl: mp4?.url,
+ sourceObjectIdentity: mp4?.objectIdentity,
+ sourceFileSize: mp4?.size,
+ sourceOutputKey: mp4?.key,
+ outputKey: mp4?.key,
+ };
+}
diff --git a/apps/web/lib/desktop-recording-upload-status.ts b/apps/web/lib/desktop-recording-upload-status.ts
index 2feb5ef31..f975ba309 100644
--- a/apps/web/lib/desktop-recording-upload-status.ts
+++ b/apps/web/lib/desktop-recording-upload-status.ts
@@ -5,27 +5,40 @@ import { Effect, Option } from "effect";
import {
assertRecordingObjectIdentity,
type RecordingOutput,
+ type RecordingSourceProof,
type RecordingUploadReceipt,
type RecordingVerification,
readCompletedRecordingManifest,
+ recordingObjectIdentitySchema,
+ recordingOutputKeySchema,
+ recordingOutputSha256Schema,
+ recordingSourceProofSchema,
recordingUploadReceiptSchema,
+ recordingVerificationSchema,
validateRecordingOutput,
} from "@/lib/desktop-recording-verification";
import * as EffectRuntime from "@/lib/server";
import { decodeStorageVideo } from "@/lib/video-storage";
-export async function validateDesktopRecordingRequest(
- video: typeof videos.$inferSelect,
- request: RecordingVerification,
-) {
+async function getRecordingStorage(video: typeof videos.$inferSelect) {
const [bucket] = await EffectRuntime.runPromise(
Effect.gen(function* () {
return yield* Storage.getAccessForVideo(decodeStorageVideo(video));
}),
);
+ return bucket;
+}
+
+export async function validateDesktopRecordingRequest(
+ video: typeof videos.$inferSelect,
+ request: RecordingVerification,
+) {
+ recordingVerificationSchema.parse(request);
+ const bucket = await getRecordingStorage(video);
if (request.artifact.kind === "mp4") {
return {
bucket,
+ manifest: null,
expected: {
fileSize: request.artifact.fileSize,
duration: request.artifact.duration,
@@ -51,79 +64,172 @@ export async function validateDesktopRecordingRequest(
}
return {
bucket,
+ manifest,
expected: {
fileSize: undefined,
- duration: manifest.duration,
+ duration: undefined,
requiredAudio: request.requiredAudio || manifest.hasAudio,
},
};
}
+export type RecordingReceiptOptions = {
+ outputKey?: string;
+ outputSha256?: string;
+ sourceProof?: RecordingSourceProof;
+ sourceObjectIdentity?: string;
+};
+
+function resolveRecordingOutputKey(
+ video: typeof videos.$inferSelect,
+ request: RecordingVerification,
+ outputKey?: string,
+) {
+ const prefix = `${video.ownerId}/${video.id}/`;
+ const key = recordingOutputKeySchema.parse(
+ outputKey ??
+ (request.artifact.kind === "mp4" ? `${prefix}result.mp4` : undefined),
+ );
+ if (!key.startsWith(prefix)) {
+ throw new Error("Recording output key does not belong to this recording");
+ }
+ return key;
+}
+
export async function createVerifiedRecordingReceipt(
video: typeof videos.$inferSelect,
request: RecordingVerification,
output: RecordingOutput,
fullDecode: boolean,
objectIdentity?: string,
+ options: RecordingReceiptOptions = {},
): Promise<RecordingUploadReceipt> {
+ recordingVerificationSchema.parse(request);
if (!fullDecode || !objectIdentity)
throw new Error("Recording content and identity were not fully verified");
+ const sourceObjectIdentity = recordingObjectIdentitySchema
+ .optional()
+ .parse(options.sourceObjectIdentity);
if (
request.artifact.kind === "mp4" &&
- request.artifact.objectIdentity !== objectIdentity
+ request.artifact.objectIdentity !== (sourceObjectIdentity ?? objectIdentity)
)
throw new Error("Verified recording does not match its upload receipt");
- const { bucket, expected } = await validateDesktopRecordingRequest(
+ const outputKey = resolveRecordingOutputKey(
video,
request,
+ options.outputKey,
);
- validateRecordingOutput(output, expected);
- const head = await EffectRuntime.runPromise(
- bucket.headObject(`${video.ownerId}/${video.id}/result.mp4`),
- );
+ const outputSha256 = recordingOutputSha256Schema
+ .optional()
+ .parse(options.outputSha256);
+ const sourceProof = recordingSourceProofSchema
+ .optional()
+ .parse(options.sourceProof);
+ if (
+ sourceObjectIdentity !== undefined &&
+ (request.artifact.kind !== "mp4" || !options.outputKey || !outputSha256)
+ ) {
+ throw new Error(
+ "Source upload identity requires an immutable verified output",
+ );
+ }
+ let requiredAudioVerified = request.requiredAudio;
+ if (request.artifact.kind === "segments") {
+ if (
+ !sourceProof ||
+ !outputSha256 ||
+ sourceProof.manifestSha256 !== request.artifact.manifestSha256 ||
+ sourceProof.hasAudio !== Boolean(output.audioCodec) ||
+ ((request.requiredAudio || sourceProof.hasAudio) &&
+ !sourceProof.audioVerified)
+ ) {
+ throw new Error("Recording source preservation was not fully verified");
+ }
+ validateRecordingOutput(output, {
+ duration: sourceProof.videoDuration,
+ requiredAudio: request.requiredAudio || sourceProof.hasAudio,
+ });
+ requiredAudioVerified = sourceProof.audioVerified;
+ } else {
+ if (sourceProof) {
+ throw new Error(
+ "MP4 upload cannot use segmented source preservation proof",
+ );
+ }
+ validateRecordingOutput(output, {
+ fileSize: request.artifact.fileSize,
+ duration: request.artifact.duration,
+ requiredAudio: request.requiredAudio,
+ });
+ }
+ const bucket = await getRecordingStorage(video);
+ const head = await EffectRuntime.runPromise(bucket.headObject(outputKey));
if (!head.ETag || head.ContentLength !== output.fileSize) {
throw new Error("Final recording object is not fully uploaded");
}
if (head.ETag !== objectIdentity) {
throw new Error("Recording changed while its content was verified");
}
- return {
+ return recordingUploadReceiptSchema.parse({
version: 1,
artifact: request.artifact,
fileSize: output.fileSize,
duration: output.duration,
hasAudio: Boolean(output.audioCodec),
fullDecode: true,
- requiredAudioVerified: request.requiredAudio,
+ requiredAudioVerified,
objectIdentity: head.ETag,
- };
+ outputKey,
+ ...(outputSha256 === undefined ? {} : { outputSha256 }),
+ ...(sourceProof === undefined ? {} : { sourceProof }),
+ ...(sourceObjectIdentity === undefined ? {} : { sourceObjectIdentity }),
+ });
}
export async function verifyDesktopRecordingUpload(
video: typeof videos.$inferSelect,
request: RecordingVerification,
) {
+ const verification = recordingVerificationSchema.parse(request);
const receipt = recordingUploadReceiptSchema.safeParse(
video.metadata?.desktopRecordingUpload,
);
if (
!receipt.success ||
- JSON.stringify(receipt.data.artifact) !== JSON.stringify(request.artifact)
+ JSON.stringify(receipt.data.artifact) !==
+ JSON.stringify(verification.artifact)
) {
return null;
}
- const { bucket, expected } = await validateDesktopRecordingRequest(
- video,
- request,
- );
if (
- expected.requiredAudio &&
+ (verification.requiredAudio || receipt.data.sourceProof?.hasAudio) &&
(!receipt.data.hasAudio || !receipt.data.requiredAudioVerified)
)
return null;
- const head = await EffectRuntime.runPromise(
- bucket.headObject(`${video.ownerId}/${video.id}/result.mp4`),
- );
+ let outputKey: string;
+ try {
+ outputKey = resolveRecordingOutputKey(
+ video,
+ verification,
+ receipt.data.outputKey,
+ );
+ } catch {
+ return null;
+ }
+ if (
+ ((verification.artifact.kind === "segments" ||
+ receipt.data.sourceObjectIdentity !== undefined) &&
+ (video.source?.type !== "desktopMP4" ||
+ video.source.outputKey !== outputKey)) ||
+ (video.source?.type === "desktopMP4" &&
+ video.source.outputKey !== undefined &&
+ video.source.outputKey !== outputKey)
+ ) {
+ return null;
+ }
+ const bucket = await getRecordingStorage(video);
+ const head = await EffectRuntime.runPromise(bucket.headObject(outputKey));
try {
assertRecordingObjectIdentity(head, receipt.data);
} catch {
@@ -132,7 +238,7 @@ export async function verifyDesktopRecordingUpload(
return {
version: 1 as const,
videoId: video.id,
- artifact: request.artifact,
+ artifact: verification.artifact,
fileSize: receipt.data.fileSize,
duration: receipt.data.duration,
hasAudio: receipt.data.hasAudio,
diff --git a/apps/web/lib/desktop-recording-verification.ts b/apps/web/lib/desktop-recording-verification.ts
index ec0ff297a..bd89c1443 100644
--- a/apps/web/lib/desktop-recording-verification.ts
+++ b/apps/web/lib/desktop-recording-verification.ts
@@ -3,22 +3,42 @@ import { z } from "zod";
const positiveNumber = z.number().finite().positive();
const positiveSize = positiveNumber.int().max(Number.MAX_SAFE_INTEGER);
+const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
+export const recordingObjectIdentitySchema = z
+ .string()
+ .max(1_024)
+ .regex(/^"[\x21\x23-\x7E\x80-\xFF]+"$/);
+
+export const recordingOutputKeySchema = z
+ .string()
+ .min(1)
+ .max(1_024)
+ .refine(
+ (key) =>
+ !key.includes("\\") &&
+ !key.includes("%") &&
+ !Array.from(key).some((character) => {
+ const code = character.charCodeAt(0);
+ return code < 32 || code === 127;
+ }) &&
+ key
+ .split("/")
+ .every((part) => part.length > 0 && part !== "." && part !== ".."),
+ "Recording output key is invalid",
+ );
export const recordingVerificationSchema = z.object({
version: z.literal(1),
artifact: z.discriminatedUnion("kind", [
z.object({
kind: z.literal("segments"),
- manifestSha256: z.string().regex(/^[a-f0-9]{64}$/),
+ manifestSha256: sha256,
}),
z.object({
kind: z.literal("mp4"),
fileSize: positiveSize,
duration: positiveNumber,
- objectIdentity: z
- .string()
- .max(1_024)
- .regex(/^"[\x21\x23-\x7E\x80-\xFF]+"$/),
+ objectIdentity: recordingObjectIdentitySchema,
}),
]),
requiredAudio: z.boolean(),
@@ -26,6 +46,25 @@ export const recordingVerificationSchema = z.object({
export type RecordingVerification = z.infer<typeof recordingVerificationSchema>;
+export const recordingSourceProofSchema = z
+ .object({
+ version: z.literal(1),
+ manifestSha256: sha256,
+ inventorySha256: sha256,
+ sourcePreserved: z.literal(true),
+ videoDuration: positiveNumber,
+ hasAudio: z.boolean(),
+ audioVerified: z.boolean(),
+ })
+ .refine(
+ (proof) => !proof.audioVerified || proof.hasAudio,
+ "Audio preservation requires a source audio track",
+ );
+
+export type RecordingSourceProof = z.infer<typeof recordingSourceProofSchema>;
+
+export const recordingOutputSha256Schema = sha256;
+
const segmentSchema = z.union([
z.number().int().positive(),
z.object({ index: z.number().int().positive(), duration: positiveNumber }),
@@ -43,11 +82,11 @@ const completedManifestSchema = z.object({
export function readCompletedRecordingManifest(json: string) {
const manifest = completedManifestSchema.parse(JSON.parse(json));
const normalize = (entry: z.infer<typeof segmentSchema>) =>
- typeof entry === "number" ? { index: entry, duration: 3 } : entry;
+ typeof entry === "number" ? entry : entry.index;
const video = manifest.video_segments.map(normalize);
const audio = manifest.audio_segments.map(normalize);
for (const segments of [video, audio]) {
- if (segments.some((segment, index) => segment.index !== index + 1)) {
+ if (segments.some((segment, index) => segment !== index + 1)) {
throw new Error(
"Recording manifest contains missing or unordered segments",
);
@@ -58,8 +97,9 @@ export function readCompletedRecordingManifest(json: string) {
}
return {
manifestSha256: createHash("sha256").update(json).digest("hex"),
- duration: video.reduce((total, segment) => total + segment.duration, 0),
hasAudio: audio.length > 0,
+ videoSegments: video,
+ audioSegments: audio,
};
}
@@ -74,19 +114,21 @@ export const recordingOutputSchema = z.object({
export type RecordingOutput = z.infer<typeof recordingOutputSchema>;
+function recordingDurationMatches(duration: number, expected: number) {
+ return (
+ Number.isFinite(expected) &&
+ expected > 0 &&
+ Math.abs(duration - expected) <= Math.max(0.5, Math.min(5, expected * 0.01))
+ );
+}
+
export function validateRecordingOutput(
output: RecordingOutput,
expected: { fileSize?: number; duration: number; requiredAudio: boolean },
) {
recordingOutputSchema.parse(output);
- const durationTolerance = Math.max(
- 0.5,
- Math.min(5, expected.duration * 0.01),
- );
if (
- !Number.isFinite(expected.duration) ||
- expected.duration <= 0 ||
- Math.abs(output.duration - expected.duration) > durationTolerance ||
+ !recordingDurationMatches(output.duration, expected.duration) ||
(expected.fileSize !== undefined &&
output.fileSize !== expected.fileSize) ||
(expected.requiredAudio && !output.audioCodec)
@@ -104,14 +146,53 @@ export const recordingUploadReceiptSchema = z
hasAudio: z.boolean(),
fullDecode: z.literal(true),
requiredAudioVerified: z.boolean().default(false),
- objectIdentity: z.string().min(1),
+ objectIdentity: recordingObjectIdentitySchema,
+ sourceObjectIdentity: recordingObjectIdentitySchema.optional(),
+ outputKey: recordingOutputKeySchema.optional(),
+ outputSha256: sha256.optional(),
+ sourceProof: recordingSourceProofSchema.optional(),
})
- .refine(
- (receipt) =>
- receipt.artifact.kind !== "mp4" ||
- receipt.artifact.objectIdentity === receipt.objectIdentity,
- "Receipt does not match the completed upload identity",
- );
+ .superRefine((receipt, context) => {
+ if (receipt.artifact.kind === "mp4") {
+ if (
+ receipt.artifact.objectIdentity !==
+ (receipt.sourceObjectIdentity ?? receipt.objectIdentity) ||
+ receipt.artifact.fileSize !== receipt.fileSize ||
+ !recordingDurationMatches(
+ receipt.duration,
+ receipt.artifact.duration,
+ ) ||
+ receipt.sourceProof !== undefined ||
+ (receipt.sourceObjectIdentity !== undefined &&
+ (!receipt.outputKey || !receipt.outputSha256))
+ ) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Receipt does not match the completed upload identity",
+ });
+ }
+ return;
+ }
+ const proof = receipt.sourceProof;
+ if (
+ !proof ||
+ !receipt.outputKey ||
+ !receipt.outputSha256 ||
+ receipt.sourceObjectIdentity !== undefined ||
+ proof.manifestSha256 !== receipt.artifact.manifestSha256 ||
+ !recordingDurationMatches(receipt.duration, proof.videoDuration) ||
+ proof.hasAudio !== receipt.hasAudio ||
+ (proof.hasAudio &&
+ (!proof.audioVerified || !receipt.requiredAudioVerified)) ||
+ (receipt.requiredAudioVerified && !proof.audioVerified)
+ ) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "Receipt is missing matching recording source preservation proof",
+ });
+ }
+ });
export type RecordingUploadReceipt = z.infer<
typeof recordingUploadReceiptSchema
diff --git a/apps/web/lib/desktop-segments-finalization.ts b/apps/web/lib/desktop-segments-finalization.ts
index f0d5d768f..ef9911e55 100644
--- a/apps/web/lib/desktop-segments-finalization.ts
+++ b/apps/web/lib/desktop-segments-finalization.ts
@@ -1,9 +1,18 @@
import { db } from "@cap/database";
-import { users, videos, videoUploads } from "@cap/database/schema";
+import { users, videos } from "@cap/database/schema";
import type { User, Video } from "@cap/web-domain";
-import { and, eq, notInArray } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { start } from "workflow/api";
import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";
+import {
+ attachWorkflowRun,
+ DesktopRecordingSourceBlockedError,
+ ensureSegmentProcessingJob,
+ getProcessingState,
+ isDesktopRecordingJobRecoverable,
+ recordWorkflowDispatchFailure,
+ SourceCommitPendingError,
+} from "@/lib/desktop-recording-jobs";
import type { RecordingVerification } from "@/lib/desktop-recording-verification";
import { transcribeVideo } from "@/lib/transcribe";
import { finalizeDesktopRecordingWorkflow } from "@/workflows/finalize-desktop-recording";
@@ -12,18 +21,6 @@ export { isRetryableDesktopSegmentsFinalizationError } from "@/lib/desktop-segme
export type DesktopSegmentsFinalizationStatus = "queued" | "already-processing";
-const PROCESSING_MESSAGE = "Muxing segments into MP4...";
-
-const getAffectedRows = (result: unknown) => {
- if (Array.isArray(result)) {
- return (
- (result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0
- );
- }
-
- return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
-};
-
async function queueEarlySegmentsTranscription({
videoId,
userId,
@@ -77,82 +74,56 @@ export async function queueDesktopSegmentsFinalization({
userId: User.UserId;
verification?: RecordingVerification;
}): Promise<DesktopSegmentsFinalizationStatus> {
- const processingMessage =
- verification?.artifact.kind === "mp4"
- ? "Verifying uploaded recording..."
- : PROCESSING_MESSAGE;
- const result = await db()
- .update(videoUploads)
- .set({
- phase: "processing",
- processingProgress: 0,
- processingMessage,
- processingError: null,
- updatedAt: new Date(),
- })
- .where(
- and(
- eq(videoUploads.videoId, videoId),
- notInArray(videoUploads.phase, ["processing", "generating_thumbnail"]),
- ),
- );
-
- if (getAffectedRows(result) === 0) {
- const [existing] = await db()
- .select({ phase: videoUploads.phase })
- .from(videoUploads)
- .where(eq(videoUploads.videoId, videoId));
-
- if (existing) {
- return "already-processing";
- }
-
+ const { job, created } = await ensureSegmentProcessingJob({
+ videoId,
+ userId,
+ verification,
+ });
+ let dispatched = false;
+ if (created || isDesktopRecordingJobRecoverable(job, new Date())) {
try {
- await db().insert(videoUploads).values({
+ const run = await start(finalizeDesktopRecordingWorkflow, [
+ { videoId, userId, generation: job.generation },
+ ]);
+ dispatched = true;
+ await attachWorkflowRun({
+ videoId,
+ generation: job.generation,
+ workflowRunId: run.runId,
+ });
+ } catch (error) {
+ await recordWorkflowDispatchFailure({
videoId,
- phase: "processing",
- processingProgress: 0,
- processingMessage,
+ generation: job.generation,
+ errorMessage: error instanceof Error ? error.message : String(error),
});
- } catch {
- return "already-processing";
+ console.error(
+ "[queueDesktopSegmentsFinalization] Durable job is waiting for workflow dispatch",
+ { videoId, generation: job.generation, error },
+ );
}
}
-
- try {
- await start(finalizeDesktopRecordingWorkflow, [
- {
- videoId,
- userId,
- verification,
+ const current = await getProcessingState({
+ videoId,
+ generation: job.generation,
+ });
+ if (current?.state === "source-blocked") {
+ throw new DesktopRecordingSourceBlockedError(
+ current.errorCode ?? "source-incomplete",
+ current.errorMessage ??
+ "Recording source is incomplete; uploaded files are retained.",
+ );
+ }
+ if (!current?.source) throw new SourceCommitPendingError();
+ if (dispatched && current.source.kind === "segments") {
+ await queueEarlySegmentsTranscription({ videoId, userId }).catch(
+ (error) => {
+ console.warn(
+ `[queueDesktopSegmentsFinalization] Early transcription queue failed for ${videoId}`,
+ error,
+ );
},
- ]);
- // The segments are fully uploaded at this point, so transcription can
- // start right away from the segment audio instead of waiting for the mux
- // into result.mp4. Failures here never block finalization: the workflow
- // re-queues transcription after the mux exactly as before.
- if (verification?.artifact.kind !== "mp4")
- await queueEarlySegmentsTranscription({ videoId, userId }).catch(
- (error) => {
- console.warn(
- `[queueDesktopSegmentsFinalization] Early transcription queue failed for ${videoId}`,
- error,
- );
- },
- );
- return "queued";
- } catch (error) {
- await db()
- .update(videoUploads)
- .set({
- phase: "error",
- processingProgress: 0,
- processingMessage: "Failed to queue segment muxing",
- processingError: error instanceof Error ? error.message : String(error),
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, videoId));
-
- throw error;
+ );
}
+ return dispatched ? "queued" : "already-processing";
}
diff --git a/apps/web/lib/desktop-segments-recovery.ts b/apps/web/lib/desktop-segments-recovery.ts
index 4f2f08889..ee098a341 100644
--- a/apps/web/lib/desktop-segments-recovery.ts
+++ b/apps/web/lib/desktop-segments-recovery.ts
@@ -1,55 +1,40 @@
import { db } from "@cap/database";
-import { videos, videoUploads } from "@cap/database/schema";
+import {
+ videoProcessingJobs,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
import { Storage } from "@cap/web-backend";
import { type User, Video } from "@cap/web-domain";
-import {
- and,
- asc,
- desc,
- eq,
- gte,
- inArray,
- isNull,
- like,
- lte,
- notLike,
- or,
- sql,
-} from "drizzle-orm";
+import { and, asc, eq, inArray, isNull, lte, sql } from "drizzle-orm";
import { Effect, Option, Schema } from "effect";
+import {
+ DesktopRecordingSourceBlockedError,
+ listRecoverableSegmentJobs,
+ SourceCommitPendingError,
+} from "@/lib/desktop-recording-jobs";
import {
type DesktopSegmentsFinalizationStatus,
queueDesktopSegmentsFinalization,
} from "@/lib/desktop-segments-finalization";
-import {
- buildDesktopSegmentsRecoveryMarker,
- DESKTOP_SEGMENTS_RECOVERY_MARKER_PREFIX,
- getDesktopSegmentsManifestSignature,
- parseDesktopSegmentsRecoveryMarker,
-} from "@/lib/desktop-segments-recovery-marker";
+import { getDesktopSegmentsManifestSignature } from "@/lib/desktop-segments-recovery-marker";
import { runPromise } from "@/lib/server";
import { decodeStorageVideo } from "@/lib/video-storage";
-import { WORKFLOW_UPGRADE_ERROR_FRAGMENT } from "@/lib/workflow-recovery";
-
-const MINUTE = 60 * 1000;
-export const DESKTOP_SEGMENTS_RECOVERY_MIN_AGE_MS = 60 * MINUTE;
-export const DESKTOP_SEGMENTS_RECOVERY_STABILITY_MS = 15 * MINUTE;
+export const DESKTOP_SEGMENTS_RECOVERY_MIN_AGE_MS = 60 * 60 * 1_000;
export const DESKTOP_SEGMENTS_RECOVERY_BATCH_SIZE = 20;
-const RECOVERABLE_UPLOAD_PHASES = ["uploading", "error"] as const;
-
-// After this many consecutive scans where a candidate is unrecoverable
-// (missing manifest, no segments, ...), it is retired from the scan queue so
-// dead rows can't permanently clog the head of the updatedAt-ordered scan.
-export const DESKTOP_SEGMENTS_RECOVERY_MAX_DEAD_ATTEMPTS = 3;
-const DEAD_MARKER_SIGNATURE = "dead";
-const RECOVERY_ABANDONED_PREFIX = "recovery-abandoned:";
+const RECOVERABLE_UPLOAD_PHASES = [
+ "uploading",
+ "processing",
+ "generating_thumbnail",
+ "error",
+] as const;
type DesktopSegmentsRecoveryResult =
| {
status: DesktopSegmentsFinalizationStatus;
- manifestCompleted: boolean;
+ manifestCompleted: false;
videoSegments: number;
audioSegments: number;
}
@@ -59,12 +44,12 @@ type DesktopSegmentsRecoveryResult =
| { status: "missing-manifest" }
| { status: "invalid-manifest"; error: string }
| { status: "no-video-segments" }
- | { status: "manifest-changed" };
+ | { status: "manifest-changed" }
+ | { status: "source-incomplete" }
+ | { status: "source-committing" };
export type StaleDesktopSegmentsRecoveryStatus =
| DesktopSegmentsRecoveryResult["status"]
- | "observing"
- | "waiting-for-stability"
| "failed";
export type StaleDesktopSegmentsRecoverySummary = {
@@ -76,23 +61,11 @@ export type StaleDesktopSegmentsRecoverySummary = {
}>;
};
-type DesktopSegmentsVideo = typeof videos.$inferSelect;
-
type LoadedDesktopSegmentsManifest =
| {
status: "loaded";
- video: DesktopSegmentsVideo;
- manifestKey: string;
+ video: typeof videos.$inferSelect;
manifest: Video.SegmentManifestType;
- bucket: Awaited<
- ReturnType<typeof Storage.getAccessForVideo> extends Effect.Effect<
- infer A,
- unknown,
- unknown
- >
- ? Promise<A>
- : never
- >[0];
}
| { status: "already-finalized" }
| { status: "not-found" }
@@ -104,30 +77,6 @@ function getErrorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error);
}
-async function decodeSegmentManifest(
- manifestJson: string,
-): Promise<
- | { status: "loaded"; manifest: Video.SegmentManifestType }
- | { status: "invalid-manifest"; error: string }
-> {
- let parsed: unknown;
- try {
- parsed = JSON.parse(manifestJson);
- } catch (error) {
- return { status: "invalid-manifest", error: getErrorMessage(error) };
- }
-
- try {
- const manifest = await Schema.decodeUnknown(Video.SegmentManifest)(parsed)
- .pipe(Effect.mapError(getErrorMessage))
- .pipe(runPromise);
-
- return { status: "loaded", manifest };
- } catch (error) {
- return { status: "invalid-manifest", error: getErrorMessage(error) };
- }
-}
-
async function loadDesktopSegmentsManifest({
videoId,
userId,
@@ -135,41 +84,40 @@ async function loadDesktopSegmentsManifest({
videoId: Video.VideoId;
userId?: User.UserId;
}): Promise<LoadedDesktopSegmentsManifest> {
- const where = userId
- ? and(eq(videos.id, videoId), eq(videos.ownerId, userId))
- : eq(videos.id, videoId);
-
- const [video] = await db().select().from(videos).where(where).limit(1);
-
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(
+ and(
+ eq(videos.id, videoId),
+ userId ? eq(videos.ownerId, userId) : undefined,
+ ),
+ )
+ .limit(1);
if (!video) return { status: "not-found" };
- if (video.source?.type === "desktopMP4")
+ if (video.source.type === "desktopMP4")
return { status: "already-finalized" };
- if (video.source?.type !== "desktopSegments")
+ if (video.source.type !== "desktopSegments")
return { status: "not-segmented" };
-
const [bucket] = await Storage.getAccessForVideo(
decodeStorageVideo(video),
).pipe(runPromise);
- const segSource = new Video.SegmentsSource({
- videoId,
- ownerId: video.ownerId,
- });
- const manifestKey = segSource.getManifestKey();
- const manifestContent = await bucket.getObject(manifestKey).pipe(runPromise);
- const manifestJson = Option.getOrNull(manifestContent);
-
- if (!manifestJson) return { status: "missing-manifest" };
-
- const decoded = await decodeSegmentManifest(manifestJson);
- if (decoded.status !== "loaded") return decoded;
-
- return {
- status: "loaded",
- video,
- manifestKey,
- manifest: decoded.manifest,
- bucket,
- };
+ const source = new Video.SegmentsSource({ videoId, ownerId: video.ownerId });
+ const content = await bucket
+ .getObject(source.getManifestKey())
+ .pipe(runPromise);
+ const json = Option.getOrNull(content);
+ if (!json) return { status: "missing-manifest" };
+ try {
+ const manifest = await Schema.decodeUnknown(Video.SegmentManifest)(
+ JSON.parse(json),
+ )
+ .pipe(Effect.mapError(getErrorMessage))
+ .pipe(runPromise);
+ return { status: "loaded", video, manifest };
+ } catch (error) {
+ return { status: "invalid-manifest", error: getErrorMessage(error) };
+ }
}
export async function completeDesktopSegmentsManifestAndQueue({
@@ -182,214 +130,64 @@ export async function completeDesktopSegmentsManifestAndQueue({
expectedManifestSignature?: string;
}): Promise<DesktopSegmentsRecoveryResult> {
const loaded = await loadDesktopSegmentsManifest({ videoId, userId });
-
if (loaded.status !== "loaded") return loaded;
-
if (
!loaded.manifest.video_init_uploaded ||
loaded.manifest.video_segments.length === 0
) {
return { status: "no-video-segments" };
}
-
- const signature = getDesktopSegmentsManifestSignature(loaded.manifest);
- if (expectedManifestSignature && signature !== expectedManifestSignature) {
+ if (
+ expectedManifestSignature &&
+ getDesktopSegmentsManifestSignature(loaded.manifest) !==
+ expectedManifestSignature
+ ) {
return { status: "manifest-changed" };
}
-
- let manifestCompleted = false;
- if (!loaded.manifest.is_complete) {
- const completedManifest = {
- ...loaded.manifest,
- is_complete: true,
+ if (!loaded.manifest.is_complete) return { status: "source-incomplete" };
+ try {
+ const status = await queueDesktopSegmentsFinalization({
+ videoId,
+ userId: loaded.video.ownerId,
+ });
+ return {
+ status,
+ manifestCompleted: false,
+ videoSegments: loaded.manifest.video_segments.length,
+ audioSegments: loaded.manifest.audio_segments.length,
};
- const body = JSON.stringify(completedManifest, null, 2);
- await loaded.bucket
- .putObject(loaded.manifestKey, body, {
- contentType: "application/json",
- contentLength: Buffer.byteLength(body),
- })
- .pipe(runPromise);
- manifestCompleted = true;
- }
-
- const status = await queueDesktopSegmentsFinalization({
- videoId,
- userId: loaded.video.ownerId,
- });
-
- return {
- status,
- manifestCompleted,
- videoSegments: loaded.manifest.video_segments.length,
- audioSegments: loaded.manifest.audio_segments.length,
- };
-}
-
-async function markCandidateObserved({
- videoId,
- signature,
- now,
-}: {
- videoId: Video.VideoId;
- signature: string;
- now: Date;
-}) {
- await db()
- .update(videoUploads)
- .set({
- updatedAt: now,
- processingMessage: buildDesktopSegmentsRecoveryMarker(
- signature,
- now.getTime(),
- ),
- })
- .where(
- and(
- eq(videoUploads.videoId, videoId),
- inArray(videoUploads.phase, RECOVERABLE_UPLOAD_PHASES),
- ),
- );
-}
-
-async function retireCandidate({
- videoId,
- status,
- now,
-}: {
- videoId: Video.VideoId;
- status: StaleDesktopSegmentsRecoveryStatus;
- now: Date;
-}) {
- await db()
- .update(videoUploads)
- .set({
- updatedAt: now,
- // Terminal phase so viewers stop seeing an eternal "uploading" state;
- // the desktop can still revive it by re-uploading and re-queueing.
- phase: "error",
- processingError: `${RECOVERY_ABANDONED_PREFIX} ${status} — the upload was interrupted and could not be recovered automatically. Reopen Cap on the recording device to retry, or record again.`,
- })
- .where(
- and(
- eq(videoUploads.videoId, videoId),
- inArray(videoUploads.phase, RECOVERABLE_UPLOAD_PHASES),
- ),
- );
-}
-
-async function recordDeadCandidateObservation({
- videoId,
- status,
- marker,
- now,
-}: {
- videoId: Video.VideoId;
- status: StaleDesktopSegmentsRecoveryStatus;
- marker: ReturnType<typeof parseDesktopSegmentsRecoveryMarker>;
- now: Date;
-}) {
- const attempts =
- (marker?.signature === DEAD_MARKER_SIGNATURE ? marker.attempts : 0) + 1;
-
- if (attempts >= DESKTOP_SEGMENTS_RECOVERY_MAX_DEAD_ATTEMPTS) {
- await retireCandidate({ videoId, status, now });
- return;
+ } catch (error) {
+ if (error instanceof SourceCommitPendingError)
+ return { status: "source-committing" };
+ if (error instanceof DesktopRecordingSourceBlockedError)
+ return { status: "source-incomplete" };
+ throw error;
}
-
- // Bump updatedAt so the candidate rotates to the back of the
- // updatedAt-ordered scan instead of blocking the queue head.
- await db()
- .update(videoUploads)
- .set({
- updatedAt: now,
- processingMessage: buildDesktopSegmentsRecoveryMarker(
- DEAD_MARKER_SIGNATURE,
- now.getTime(),
- attempts,
- ),
- })
- .where(
- and(
- eq(videoUploads.videoId, videoId),
- inArray(videoUploads.phase, RECOVERABLE_UPLOAD_PHASES),
- ),
- );
}
-async function recoverStaleDesktopSegmentsCandidate({
+async function recoverRecording({
videoId,
- processingMessage,
- now,
-}: {
- videoId: Video.VideoId;
- processingMessage: string | null;
- now: Date;
-}): Promise<StaleDesktopSegmentsRecoveryStatus> {
- const marker = parseDesktopSegmentsRecoveryMarker(processingMessage);
- const loaded = await loadDesktopSegmentsManifest({ videoId });
-
- if (loaded.status === "already-finalized") {
- // The upload row outlived finalization; retire it immediately so it
- // stops occupying the scan queue.
- await retireCandidate({ videoId, status: loaded.status, now });
- return loaded.status;
- }
-
- if (loaded.status !== "loaded") {
- await recordDeadCandidateObservation({
- videoId,
- status: loaded.status,
- marker,
- now,
- });
- return loaded.status;
- }
-
- if (
- !loaded.manifest.video_init_uploaded ||
- loaded.manifest.video_segments.length === 0
- ) {
- await recordDeadCandidateObservation({
+ userId,
+ verification,
+}: Parameters<
+ typeof queueDesktopSegmentsFinalization
+>[0]): Promise<StaleDesktopSegmentsRecoveryStatus> {
+ try {
+ return await queueDesktopSegmentsFinalization({
videoId,
- status: "no-video-segments",
- marker,
- now,
+ userId,
+ verification,
});
- return "no-video-segments";
- }
-
- if (loaded.manifest.is_complete) {
- return (
- await completeDesktopSegmentsManifestAndQueue({
- videoId,
- expectedManifestSignature: getDesktopSegmentsManifestSignature(
- loaded.manifest,
- ),
- })
- ).status;
- }
-
- const signature = getDesktopSegmentsManifestSignature(loaded.manifest);
-
- if (marker?.signature !== signature) {
- await markCandidateObserved({ videoId, signature, now });
- return "observing";
- }
-
- if (
- now.getTime() - marker.observedAtMs <
- DESKTOP_SEGMENTS_RECOVERY_STABILITY_MS
- ) {
- return "waiting-for-stability";
+ } catch (error) {
+ if (error instanceof SourceCommitPendingError) return "source-committing";
+ if (error instanceof DesktopRecordingSourceBlockedError)
+ return "source-incomplete";
+ console.error(
+ "[desktop-segments-recovery] Durable recovery dispatch failed",
+ { videoId, error },
+ );
+ return "failed";
}
-
- return (
- await completeDesktopSegmentsManifestAndQueue({
- videoId,
- expectedManifestSignature: signature,
- })
- ).status;
}
export async function recoverStaleDesktopSegments({
@@ -399,94 +197,67 @@ export async function recoverStaleDesktopSegments({
now?: Date;
limit?: number;
} = {}): Promise<StaleDesktopSegmentsRecoverySummary> {
+ const batchSize = Math.max(1, Math.min(limit, 100));
+ const legacyReserve =
+ batchSize > 1 ? Math.max(1, Math.floor(batchSize / 4)) : 0;
+ const jobs = await listRecoverableSegmentJobs({
+ now,
+ limit: batchSize - legacyReserve,
+ });
+ const summary: StaleDesktopSegmentsRecoverySummary = {
+ checked: 0,
+ statuses: {},
+ results: [],
+ };
+ const record = (
+ videoId: Video.VideoId,
+ status: StaleDesktopSegmentsRecoveryStatus,
+ ) => {
+ summary.checked++;
+ summary.statuses[status] = (summary.statuses[status] ?? 0) + 1;
+ summary.results.push({ videoId, status });
+ };
+ for (const job of jobs) {
+ record(
+ job.videoId,
+ await recoverRecording({
+ videoId: job.videoId,
+ userId: job.ownerId,
+ verification: job.verification ?? undefined,
+ }),
+ );
+ }
+ const remaining = batchSize - jobs.length;
+ if (remaining <= 0) return summary;
const staleBefore = new Date(
now.getTime() - DESKTOP_SEGMENTS_RECOVERY_MIN_AGE_MS,
);
- const stabilityBefore = new Date(
- now.getTime() - DESKTOP_SEGMENTS_RECOVERY_STABILITY_MS,
- );
- const candidates = await db()
- .select({
- videoId: videos.id,
- processingMessage: videoUploads.processingMessage,
- })
- .from(videos)
- .innerJoin(videoUploads, eq(videos.id, videoUploads.videoId))
+ const legacy = await db()
+ .select({ videoId: videos.id, ownerId: videos.ownerId })
+ .from(videoUploads)
+ .innerJoin(videos, eq(videoUploads.videoId, videos.id))
+ .leftJoin(
+ videoProcessingJobs,
+ eq(videoUploads.videoId, videoProcessingJobs.videoId),
+ )
.where(
and(
- sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.source}, '$.type')) = 'desktopSegments'`,
- gte(videoUploads.startedAt, sql`UTC_TIMESTAMP() - INTERVAL 28 HOUR`),
- lte(videos.createdAt, staleBefore),
- or(
- lte(videoUploads.updatedAt, staleBefore),
- and(
- like(
- videoUploads.processingMessage,
- `${DESKTOP_SEGMENTS_RECOVERY_MARKER_PREFIX}%`,
- ),
- lte(videoUploads.updatedAt, stabilityBefore),
- ),
- ),
inArray(videoUploads.phase, RECOVERABLE_UPLOAD_PHASES),
- or(
- isNull(videoUploads.processingError),
- notLike(
- videoUploads.processingError,
- `${RECOVERY_ABANDONED_PREFIX}%`,
- ),
- ),
- ),
- )
- .orderBy(
- desc(
- sql<number>`CASE WHEN ${videoUploads.processingError} LIKE ${`%${WORKFLOW_UPGRADE_ERROR_FRAGMENT}%`} THEN 1 ELSE 0 END`,
+ lte(videoUploads.updatedAt, staleBefore),
+ isNull(videoProcessingJobs.videoId),
+ sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.source}, '$.type')) = 'desktopSegments'`,
),
- asc(videoUploads.updatedAt),
)
- .limit(limit);
-
- const summary: StaleDesktopSegmentsRecoverySummary = {
- checked: candidates.length,
- statuses: {},
- results: [],
- };
-
- for (const candidate of candidates) {
- let status: StaleDesktopSegmentsRecoveryStatus;
- try {
- status = await recoverStaleDesktopSegmentsCandidate({
+ .orderBy(asc(videoUploads.updatedAt), asc(videoUploads.videoId))
+ .limit(remaining);
+ for (const candidate of legacy) {
+ record(
+ candidate.videoId,
+ await recoverRecording({
videoId: candidate.videoId,
- processingMessage: candidate.processingMessage,
- now,
- });
- } catch (error) {
- status = "failed";
- console.error(
- `[desktop-segments-recovery] Failed to recover ${candidate.videoId}:`,
- error,
- );
- // A candidate that keeps throwing must still rotate/retire, or it
- // blocks the queue head forever.
- try {
- await recordDeadCandidateObservation({
- videoId: Video.VideoId.make(candidate.videoId),
- status: "failed",
- marker: parseDesktopSegmentsRecoveryMarker(
- candidate.processingMessage,
- ),
- now,
- });
- } catch (markError) {
- console.error(
- `[desktop-segments-recovery] Failed to mark ${candidate.videoId}:`,
- markError,
- );
- }
- }
-
- summary.statuses[status] = (summary.statuses[status] ?? 0) + 1;
- summary.results.push({ videoId: candidate.videoId, status });
+ userId: candidate.ownerId,
+ }),
+ );
}
-
return summary;
}
diff --git a/apps/web/workflows/admin-reprocess-video.ts b/apps/web/workflows/admin-reprocess-video.ts
index 5de92c580..73d8fa860 100644
--- a/apps/web/workflows/admin-reprocess-video.ts
+++ b/apps/web/workflows/admin-reprocess-video.ts
@@ -11,6 +11,7 @@ import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { Effect } from "effect";
import { FatalError, sleep } from "workflow";
+import { retireDesktopRecordingJobForOutputReplacement } from "@/lib/desktop-recording-jobs";
import {
createMediaServerCapacityError,
isMediaServerCapacityError,
@@ -376,27 +377,62 @@ async function processExistingResultOnMediaServer(
};
}
-async function saveMetadataAndComplete(
+export async function saveMetadataAndComplete(
videoId: string,
metadata: { duration: number; width: number; height: number; fps: number },
): Promise<void> {
"use step";
const duration = getValidDuration(metadata.duration);
-
- await db()
- .update(videos)
- .set({
- width: metadata.width,
- height: metadata.height,
- fps: metadata.fps,
- ...(duration === undefined ? {} : { duration }),
- })
- .where(eq(videos.id, videoId as Video.VideoId));
-
- await db()
- .delete(videoUploads)
- .where(eq(videoUploads.videoId, videoId as Video.VideoId));
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, Video.VideoId.make(videoId)));
+ if (!video) throw new Error("Video does not exist");
+ const [bucket] = await Storage.getAccessForVideo(decodeStorageVideo(video), {
+ resolvePublishedOutput: false,
+ }).pipe(runWorkflowPromise);
+ const head = await bucket
+ .headObject(`${video.ownerId}/${video.id}/result.mp4`)
+ .pipe(runWorkflowPromise);
+ if (!head.ETag || !head.ContentLength || head.ContentLength <= 0) {
+ throw new Error("Reprocessed recording output is missing or empty");
+ }
+ await db().transaction(async (tx) => {
+ await retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId: video.id,
+ userId: video.ownerId,
+ });
+ const [lockedVideo] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, video.id))
+ .for("update");
+ if (
+ !lockedVideo ||
+ lockedVideo.ownerId !== video.ownerId ||
+ lockedVideo.bucket !== video.bucket ||
+ lockedVideo.storageIntegrationId !== video.storageIntegrationId
+ ) {
+ throw new Error("Recording storage changed during reprocessing");
+ }
+ const nextMetadata = { ...(lockedVideo.metadata ?? {}) };
+ delete nextMetadata.desktopRecordingUpload;
+ await tx
+ .update(videos)
+ .set({
+ width: metadata.width,
+ height: metadata.height,
+ fps: metadata.fps,
+ metadata: nextMetadata,
+ ...(lockedVideo.source.type === "desktopMP4"
+ ? { source: { type: "desktopMP4" as const } }
+ : {}),
+ ...(duration === undefined ? {} : { duration }),
+ })
+ .where(eq(videos.id, video.id));
+ await tx.delete(videoUploads).where(eq(videoUploads.videoId, video.id));
+ });
}
async function invalidateResultCache(
diff --git a/apps/web/workflows/edit-video.ts b/apps/web/workflows/edit-video.ts
index 40ac1492d..37a1df012 100644
--- a/apps/web/workflows/edit-video.ts
+++ b/apps/web/workflows/edit-video.ts
@@ -22,6 +22,7 @@ import { Video } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { FatalError, sleep } from "workflow";
+import { retireDesktopRecordingJobForOutputReplacement } from "@/lib/desktop-recording-jobs";
import {
type EditTranscript,
editTranscriptWordsToCaptionVtt,
@@ -330,7 +331,11 @@ async function renderVideoEditOnMediaServer(
)
.pipe(runWorkflowPromise);
- const outputVerificationUrl = await bucket
+ const [outputBucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
+ { resolvePublishedOutput: false },
+ ).pipe(runWorkflowPromise);
+ const outputVerificationUrl = await outputBucket
.getInternalSignedObjectUrl(outputKey, {
expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
})
@@ -475,7 +480,7 @@ async function probeVideoOnMediaServer(
return metadata;
}
-async function verifyRenderedEditOutput(
+export async function verifyRenderedEditOutput(
videoId: string,
userId: string,
editSpec: VideoEditSpec,
@@ -504,9 +509,9 @@ async function verifyRenderedEditOutput(
throw new FatalError("Video does not exist");
}
- const [bucket] = await Storage.getAccessForVideo(
- decodeStorageVideo(video),
- ).pipe(runWorkflowPromise);
+ const [bucket] = await Storage.getAccessForVideo(decodeStorageVideo(video), {
+ resolvePublishedOutput: false,
+ }).pipe(runWorkflowPromise);
const outputKey = `${userId}/${videoId}/result.mp4`;
const outputUrl = await bucket
.getInternalSignedObjectUrl(outputKey, {
@@ -810,7 +815,7 @@ async function invalidateEditedVideoCache(
}
}
-async function saveEditResultAndComplete(
+export async function saveEditResultAndComplete(
videoId: string,
sourceKey: string,
previousSpec: VideoEditSpec,
@@ -829,7 +834,6 @@ async function saveEditResultAndComplete(
throw new FatalError("Video does not exist");
}
- const nextMetadata = clearAiMetadata(video.metadata as VideoMetadata | null);
let originalTranscript: EditTranscript | null = null;
try {
originalTranscript = await loadOriginalEditTranscript(video, editSpec);
@@ -841,6 +845,25 @@ async function saveEditResultAndComplete(
}
await db().transaction(async (tx) => {
+ await retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId: video.id,
+ userId: video.ownerId,
+ });
+ const [lockedVideo] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, video.id))
+ .for("update");
+ if (
+ !lockedVideo ||
+ lockedVideo.ownerId !== video.ownerId ||
+ lockedVideo.bucket !== video.bucket ||
+ lockedVideo.storageIntegrationId !== video.storageIntegrationId
+ ) {
+ throw new Error("Recording storage changed while the edit was rendering");
+ }
+ const nextMetadata = clearAiMetadata(lockedVideo.metadata);
+ delete nextMetadata.desktopRecordingUpload;
await tx
.update(videos)
.set({
@@ -848,6 +871,9 @@ async function saveEditResultAndComplete(
height: metadata.height,
fps: metadata.fps,
metadata: nextMetadata,
+ ...(lockedVideo.source.type === "desktopMP4"
+ ? { source: { type: "desktopMP4" as const } }
+ : {}),
// Derivable captions keep the transcription COMPLETE; only legacy
// videos without a stored word transcript get re-transcribed.
...(originalTranscript ? {} : { transcriptionStatus: null }),
diff --git a/apps/web/workflows/finalize-desktop-recording.ts b/apps/web/workflows/finalize-desktop-recording.ts
index 9a81d4c79..59c28615c 100644
--- a/apps/web/workflows/finalize-desktop-recording.ts
+++ b/apps/web/workflows/finalize-desktop-recording.ts
@@ -1,22 +1,35 @@
import { db } from "@cap/database";
-import { users, videos, videoUploads } from "@cap/database/schema";
+import { users, videos } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import { Storage } from "@cap/web-backend/src/Storage/index";
import { type User, Video } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
-import { Effect, Option, Schema } from "effect";
-import { FatalError, sleep } from "workflow";
+import { sleep } from "workflow";
+import { z } from "zod";
import { isAiGenerationEnabledForUser } from "@/lib/ai-generation-entitlement";
-import { reconcileDesktopRecordingJob } from "@/lib/desktop-recording-job-status";
+import { observeDesktopRecordingJob } from "@/lib/desktop-recording-job-status";
import {
- type RecordingVerification,
- readCompletedRecordingManifest,
-} from "@/lib/desktop-recording-verification";
-import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota-cache";
+ attachRemoteJob,
+ claimProcessingAttempt,
+ type DesktopRecordingAttempt,
+ type DesktopRecordingAttemptFence,
+ deferWithoutMediaServer,
+ ensureSegmentProcessingJob,
+ getProcessingState,
+ heartbeatAttempt,
+ initializeSourceCommitCheckpoint,
+ markSourceBlocked,
+ persistCommittedSource,
+ persistSourceCommitCheckpoint,
+ scheduleRetry,
+} from "@/lib/desktop-recording-jobs";
import {
- createMediaServerCapacityError,
- isMediaServerCapacityError,
-} from "@/lib/media-server-backpressure";
+ advanceDesktopRecordingSourceCommit,
+ buildDesktopRecordingSourceUrls,
+ getDesktopRecordingOutputKey,
+} from "@/lib/desktop-recording-source";
+import type { RecordingVerification } from "@/lib/desktop-recording-verification";
+import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota-cache";
import { transcribeVideo } from "@/lib/transcribe";
import { decodeStorageVideo } from "@/lib/video-storage";
import { runWorkflowPromise } from "@/lib/workflow-runtime";
@@ -24,17 +37,27 @@ import { runWorkflowPromise } from "@/lib/workflow-runtime";
interface FinalizeDesktopRecordingWorkflowPayload {
videoId: string;
userId: User.UserId;
+ generation?: string;
verification?: RecordingVerification;
}
+type WorkflowResult = {
+ success: boolean;
+ jobId?: string;
+ reason?:
+ | "source-blocked"
+ | "superseded"
+ | "already-processing"
+ | "media-server-unconfigured";
+};
+
type DesktopSegmentsOutputUpload =
- | {
- type: "put";
- url: string;
- }
+ | { type: "put"; url: string; ifNoneMatch: "*" }
| {
type: "multipart";
videoId: string;
+ generation: string;
+ attemptId: string;
key: string;
uploadId: string;
partSize: number;
@@ -44,744 +67,583 @@ type DesktopSegmentsOutputUpload =
webhookSecret?: string;
};
-interface DesktopSegmentsMuxBody {
- manifestSha256?: string;
- expectedDuration?: number;
- outputVerificationUrl: string;
- videoId: string;
- userId: string;
- outputPresignedUrl: string;
- outputUpload: DesktopSegmentsOutputUpload;
- thumbnailPresignedUrl: string;
- previewGifPresignedUrl: string;
- videoInitUrl: string;
- videoSegmentUrls: string[];
- audioInitUrl?: string;
- audioSegmentUrls?: string[];
- webhookUrl: string;
- webhookSecret?: string;
-}
-
-const MEDIA_SERVER_START_MAX_ATTEMPTS = 8;
-const MEDIA_SERVER_START_RETRY_BASE_MS = 15_000;
-const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 1_440;
-const MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS = 5_000;
-const MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS = 3 * 60 * 60;
-const MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS = 3 * 60 * 60;
-const MEDIA_SERVER_MULTIPART_OUTPUT_PART_SIZE_BYTES = 64 * 1024 * 1024;
-
-function getRetryDelay(attempt: number) {
- return Math.min(
- MEDIA_SERVER_START_RETRY_BASE_MS * 2 ** attempt,
- 5 * 60 * 1000,
- );
-}
-
-async function waitForRetry(delayMs: number): Promise<void> {
- await new Promise((resolve) => setTimeout(resolve, delayMs));
-}
+const COMPLETION_POLL_INTERVAL_MS = 15_000;
+const ATTEMPT_MAX_DURATION_MS = 6 * 60 * 60 * 1_000;
+const PRESIGNED_EXPIRES_SECONDS = 6 * 60 * 60;
+const MULTIPART_OUTPUT_PART_SIZE_BYTES = 64 * 1024 * 1024;
function getErrorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error);
}
-function getMediaServerWebhookUrl(baseUrl: string, path: string) {
- const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
- return new URL(path.replace(/^\//, ""), normalizedBaseUrl).toString();
-}
-
-async function abortDesktopSegmentsOutputUpload(
- outputUpload: DesktopSegmentsOutputUpload,
-): Promise<void> {
- if (outputUpload.type === "put") return;
-
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- };
- if (outputUpload.webhookSecret) {
- headers["x-media-server-secret"] = outputUpload.webhookSecret;
- }
-
- const response = await fetch(outputUpload.abortUrl, {
- method: "POST",
- headers,
- body: JSON.stringify({
- videoId: outputUpload.videoId,
- key: outputUpload.key,
- uploadId: outputUpload.uploadId,
- }),
- signal: AbortSignal.timeout(30_000),
- });
-
- if (!response.ok) {
- throw new Error(`Failed to abort output upload: ${response.status}`);
+function getSourceErrorCode(error: unknown) {
+ if (error && typeof error === "object" && "code" in error) {
+ const code = error.code;
+ if (
+ code === "source-incomplete" ||
+ code === "source-missing" ||
+ code === "source-changed" ||
+ code === "source-invalid"
+ ) {
+ return code;
+ }
}
+ return null;
}
-function isRetryableMuxError(error: unknown) {
- const message = getErrorMessage(error);
-
- return (
- message.includes("500") ||
- message.includes("502") ||
- message.includes("503") ||
- message.includes("504") ||
- message.includes("429") ||
- message.includes("Application failed to respond") ||
- message.includes("SERVER_BUSY") ||
- message.includes("Server is at capacity") ||
- message.includes("fetch failed") ||
- message.includes("Segment manifest not found") ||
- message.includes("Segment manifest is not marked as complete") ||
- message.includes("timed out") ||
- message.includes("timeout")
- );
+function getMediaServerWebhookUrl(baseUrl: string, path: string) {
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
+ return new URL(path.replace(/^\//, ""), normalizedBaseUrl).toString();
}
export async function finalizeDesktopRecordingWorkflow(
payload: FinalizeDesktopRecordingWorkflowPayload,
-): Promise<{ success: true; jobId?: string }> {
+): Promise<WorkflowResult> {
"use workflow";
- const { videoId, userId, verification } = payload;
-
- try {
- await validateDesktopSegmentsRecording(videoId, userId);
-
- if (await completeWithoutMediaServerIfUnavailable(videoId)) {
- await queueFinalizedRecordingTranscription(videoId, userId);
- return { success: true };
+ const generation = await ensureWorkflowJob(payload);
+ let completedJobId: string | undefined;
+ let mediaServerUnavailable = false;
+ processing: for (;;) {
+ const next = await acquireDesktopRecordingAttempt({
+ ...payload,
+ generation,
+ });
+ if (next.status === "verified") break;
+ if (next.status === "wait") {
+ await sleep(next.until);
+ continue;
}
-
- for (let attempt = 0; ; attempt++) {
- try {
- await markMuxProcessing(videoId);
- const jobId =
- verification?.artifact.kind === "mp4"
- ? await startDesktopMp4VerificationJob(
- videoId,
- userId,
- verification,
- )
- : await startDesktopSegmentsMuxJob(videoId, userId);
- await waitForDesktopSegmentsMuxCompletion(videoId, jobId);
- await queueFinalizedRecordingTranscription(videoId, userId);
- return { success: true, jobId };
- } catch (error) {
- if (
- !isRetryableMuxError(error) ||
- (attempt >= MEDIA_SERVER_START_MAX_ATTEMPTS - 1 &&
- !isMediaServerCapacityError(error))
- ) {
- throw error;
- }
-
- await markMuxRetrying(videoId, getErrorMessage(error));
- await sleep(getRetryDelay(attempt));
-
- if (await isDesktopRecordingFinalized(videoId)) {
- await queueFinalizedRecordingTranscription(videoId, userId);
- return { success: true };
+ if (next.status !== "attempt") {
+ return { success: false, reason: next.status };
+ }
+ const attempt = next.attempt;
+ try {
+ let committed = await commitDesktopRecordingAttempt(attempt);
+ while (committed === "progress") {
+ committed = await commitDesktopRecordingAttempt(attempt);
+ }
+ if (committed !== "ready") {
+ return { success: false, reason: committed };
+ }
+ if (await completeWithoutMediaServerIfUnavailable(attempt)) {
+ mediaServerUnavailable = true;
+ break;
+ }
+ const jobId = await startDesktopRecordingJob(attempt);
+ for (;;) {
+ await sleep(COMPLETION_POLL_INTERVAL_MS);
+ const status = await pollDesktopRecordingAttempt({
+ videoId: attempt.videoId,
+ generation: attempt.generation,
+ attemptId: attempt.attemptId,
+ jobId,
+ deadline: new Date(
+ attempt.updatedAt.getTime() + ATTEMPT_MAX_DURATION_MS,
+ ),
+ });
+ if (status === "verified") {
+ completedJobId = jobId;
+ break processing;
}
+ if (status === "waiting") continue;
+ if (status === "retry") break;
+ return { success: false, jobId, reason: status };
}
+ } catch (error) {
+ const retained = await retryDesktopRecordingAttempt(
+ attempt,
+ getErrorMessage(error),
+ getSourceErrorCode(error),
+ );
+ if (retained !== "retry") return { success: false, reason: retained };
}
- } catch (error) {
- const errorMessage = getErrorMessage(error);
- await markMuxError(videoId, errorMessage);
- throw new FatalError(errorMessage);
- }
-}
-
-async function validateDesktopSegmentsRecording(
- videoId: string,
- userId: User.UserId,
-): Promise<void> {
- "use step";
-
- const [video] = await db()
- .select()
- .from(videos)
- .where(
- and(
- eq(videos.id, Video.VideoId.make(videoId)),
- eq(videos.ownerId, userId),
- ),
- );
-
- if (!video) {
- throw new FatalError("Video does not exist");
- }
-
- if (video.source?.type === "desktopMP4") {
- return;
}
-
- if (video.source?.type !== "desktopSegments") {
- throw new FatalError("Video is not a segmented recording");
- }
-}
-
-async function completeWithoutMediaServerIfUnavailable(
- videoId: string,
-): Promise<boolean> {
- "use step";
-
- if (serverEnv().MEDIA_SERVER_URL) {
- return false;
+ for (let attempt = 0; ; attempt++) {
+ let queued: boolean;
+ try {
+ queued = await queueFinalizedRecordingTranscription(
+ payload.videoId,
+ payload.userId,
+ );
+ } catch {
+ queued = false;
+ }
+ if (queued) break;
+ await sleep(Math.min(15_000 * 2 ** Math.min(attempt, 5), 300_000));
}
-
- const [video] = await db()
- .select()
- .from(videos)
- .where(eq(videos.id, Video.VideoId.make(videoId)));
-
- await db()
- .delete(videoUploads)
- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));
-
- await invalidateGoogleDriveStorageQuotaCache(video?.storageIntegrationId);
-
- return true;
+ return mediaServerUnavailable
+ ? { success: false, reason: "media-server-unconfigured" }
+ : { success: true, ...(completedJobId ? { jobId: completedJobId } : {}) };
}
-async function markMuxProcessing(videoId: string): Promise<void> {
- "use step";
-
- await db()
- .update(videoUploads)
- .set({
- phase: "processing",
- processingProgress: 0,
- processingMessage: "Muxing segments into MP4...",
- processingError: null,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));
-}
-
-async function markMuxRetrying(
- videoId: string,
- errorMessage: string,
-): Promise<void> {
+async function ensureWorkflowJob(
+ payload: FinalizeDesktopRecordingWorkflowPayload,
+): Promise<string> {
"use step";
- await db()
- .update(videoUploads)
- .set({
- phase: "processing",
- processingProgress: 0,
- processingMessage: "Retrying segment muxing...",
- processingError: errorMessage,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));
+ if (payload.generation) return payload.generation;
+ const { job } = await ensureSegmentProcessingJob({
+ videoId: Video.VideoId.make(payload.videoId),
+ userId: payload.userId,
+ verification: payload.verification,
+ });
+ return job.generation;
}
-async function markMuxError(
- videoId: string,
- errorMessage: string,
-): Promise<void> {
+export async function acquireDesktopRecordingAttempt({
+ videoId,
+ userId,
+ generation,
+}: {
+ videoId: string;
+ userId: User.UserId;
+ generation: string;
+}): Promise<
+ | { status: "attempt"; attempt: DesktopRecordingAttempt }
+ | { status: "wait"; until: Date }
+ | {
+ status:
+ | "verified"
+ | "source-blocked"
+ | "superseded"
+ | "already-processing";
+ }
+> {
"use step";
- await db()
- .update(videoUploads)
- .set({
- phase: "error",
- processingProgress: 0,
- processingMessage: "Segment muxing failed",
- processingError: errorMessage,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));
+ const id = Video.VideoId.make(videoId);
+ const job = await getProcessingState({ videoId: id, generation });
+ if (!job || job.ownerId !== userId) return { status: "superseded" };
+ if (job.state === "verified") return { status: "verified" };
+ if (job.state === "source-blocked") return { status: "source-blocked" };
+ const now = new Date();
+ if (job.leaseExpiresAt && job.leaseExpiresAt > now) {
+ return { status: "already-processing" };
+ }
+ if (job.nextRetryAt > now) return { status: "wait", until: job.nextRetryAt };
+ const attempt = await claimProcessingAttempt({
+ videoId: id,
+ generation,
+ now,
+ });
+ return attempt
+ ? { status: "attempt", attempt }
+ : { status: "already-processing" };
}
-async function isDesktopRecordingFinalized(videoId: string): Promise<boolean> {
+export async function commitDesktopRecordingAttempt(
+ attempt: DesktopRecordingAttempt,
+): Promise<"progress" | "ready" | "source-blocked" | "superseded"> {
"use step";
- const [video] = await db()
- .select({ source: videos.source })
- .from(videos)
- .where(eq(videos.id, Video.VideoId.make(videoId)));
- const [upload] = await db()
- .select({ videoId: videoUploads.videoId })
- .from(videoUploads)
- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));
-
- return video?.source?.type === "desktopMP4" && !upload;
-}
-
-async function buildDesktopSegmentsMuxBody(
- videoId: string,
- userId: User.UserId,
-): Promise<DesktopSegmentsMuxBody> {
+ const current = await getProcessingState(attempt);
+ if (!current || current.attemptId !== attempt.attemptId) return "superseded";
+ if (current.source) return "ready";
const [video] = await db()
.select()
.from(videos)
.where(
- and(
- eq(videos.id, Video.VideoId.make(videoId)),
- eq(videos.ownerId, userId),
- ),
+ and(eq(videos.id, attempt.videoId), eq(videos.ownerId, attempt.ownerId)),
);
-
- if (!video) {
- throw new FatalError("Video does not exist");
- }
-
- const [bucket] = await Storage.getAccessForVideo(
- decodeStorageVideo(video),
- ).pipe(runWorkflowPromise);
-
- const segSource = new Video.SegmentsSource({
- videoId,
- ownerId: userId,
- });
-
- const manifestContent = await bucket
- .getObject(segSource.getManifestKey())
- .pipe(runWorkflowPromise);
- const manifestJson = Option.getOrNull(manifestContent);
-
- if (!manifestJson) {
- throw new Error("Segment manifest not found");
- }
-
- let parsed: unknown;
+ if (!video) return "superseded";
try {
- parsed = JSON.parse(manifestJson);
- } catch {
- throw new Error("Invalid segment manifest JSON");
+ const checkpoint = await initializeSourceCommitCheckpoint(attempt);
+ if (!checkpoint) return "superseded";
+ const result = await advanceDesktopRecordingSourceCommit(
+ video,
+ checkpoint,
+ current.verification ?? undefined,
+ async () => {
+ if (!(await heartbeatAttempt(attempt))) {
+ throw new Error("Recording source commit lease was superseded");
+ }
+ },
+ );
+ if ("checkpoint" in result) {
+ return (await persistSourceCommitCheckpoint(attempt, result.checkpoint))
+ ? "progress"
+ : "superseded";
+ }
+ return (await persistCommittedSource(attempt, result.source))
+ ? "ready"
+ : "superseded";
+ } catch (error) {
+ const code = getSourceErrorCode(error);
+ if (!code) throw error;
+ const marked = await markSourceBlocked({
+ ...attempt,
+ errorCode: code,
+ errorMessage: getErrorMessage(error),
+ });
+ return marked ? "source-blocked" : "superseded";
}
+}
- const manifest = await Schema.decodeUnknown(Video.SegmentManifest)(parsed)
- .pipe(Effect.mapError(() => new Error("Invalid segment manifest format")))
- .pipe(runWorkflowPromise);
-
- if (!manifest.video_init_uploaded || manifest.video_segments.length === 0) {
- throw new Error("No video segments found in manifest");
- }
+async function completeWithoutMediaServerIfUnavailable(
+ attempt: DesktopRecordingAttempt,
+): Promise<boolean> {
+ "use step";
- if (!manifest.is_complete) {
- throw new Error("Segment manifest is not marked as complete");
+ if (serverEnv().MEDIA_SERVER_URL) return false;
+ const deferred = await deferWithoutMediaServer(attempt);
+ if (deferred) {
+ const [video] = await db()
+ .select({ storageIntegrationId: videos.storageIntegrationId })
+ .from(videos)
+ .where(eq(videos.id, attempt.videoId));
+ await invalidateGoogleDriveStorageQuotaCache(video?.storageIntegrationId);
}
- const completedManifest = [
- ...manifest.video_segments,
- ...manifest.audio_segments,
- ].every((entry) => typeof entry !== "number")
- ? readCompletedRecordingManifest(manifestJson)
- : undefined;
-
- const videoInitUrl = await bucket
- .getSignedObjectUrl(segSource.getVideoInitKey(), {
- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
- })
- .pipe(runWorkflowPromise);
+ return true;
+}
- const videoSegmentUrls = await Effect.all(
- manifest.video_segments.map((seg) => {
- const entry = Video.normalizeSegmentEntry(seg);
- return bucket.getSignedObjectUrl(
- segSource.getVideoSegmentKey(entry.index),
- {
- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
- },
- );
- }),
- { concurrency: "unbounded" },
+async function buildDesktopSegmentsOutput({
+ video,
+ attempt,
+}: {
+ video: typeof videos.$inferSelect;
+ attempt: DesktopRecordingAttemptFence;
+}) {
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
).pipe(runWorkflowPromise);
-
- let audioInitUrl: string | undefined;
- let audioSegmentUrls: string[] | undefined;
-
- if (manifest.audio_init_uploaded && manifest.audio_segments.length > 0) {
- audioInitUrl = await bucket
- .getSignedObjectUrl(segSource.getAudioInitKey(), {
- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
- })
- .pipe(runWorkflowPromise);
- audioSegmentUrls = await Effect.all(
- manifest.audio_segments.map((seg) => {
- const entry = Video.normalizeSegmentEntry(seg);
- return bucket.getSignedObjectUrl(
- segSource.getAudioSegmentKey(entry.index),
- {
- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
- },
- );
- }),
- { concurrency: "unbounded" },
- ).pipe(runWorkflowPromise);
- }
-
- const outputKey = `${userId}/${videoId}/result.mp4`;
+ const outputKey = getDesktopRecordingOutputKey(
+ video.ownerId,
+ video.id,
+ attempt.generation,
+ attempt.attemptId,
+ );
+ const candidateDirectory = outputKey.slice(0, -4);
+ const env = serverEnv();
+ const webhookBaseUrl = env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL;
+ const webhookSecret = env.MEDIA_SERVER_WEBHOOK_SECRET;
const outputVerificationUrl = await bucket
.getInternalSignedObjectUrl(outputKey, {
- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
+ expiresIn: PRESIGNED_EXPIRES_SECONDS,
})
.pipe(runWorkflowPromise);
- const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
- const previewGifKey = `${userId}/${videoId}/preview/animated-preview.gif`;
- const env = serverEnv();
- const webhookBaseUrl = env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL;
- const webhookSecret = env.MEDIA_SERVER_WEBHOOK_SECRET;
-
const outputPresignedUrl = await bucket
.getInternalPresignedPutUrl(
outputKey,
- {
- ContentType: "video/mp4",
- },
- { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },
+ { ContentType: "video/mp4" },
+ { expiresIn: PRESIGNED_EXPIRES_SECONDS },
)
.pipe(runWorkflowPromise);
let outputUpload: DesktopSegmentsOutputUpload = {
type: "put",
url: outputPresignedUrl,
+ ifNoneMatch: "*",
};
+ if (bucket.provider === "s3" && webhookSecret) {
+ const multipart = await bucket.multipart
+ .create(outputKey, { ContentType: "video/mp4" })
+ .pipe(runWorkflowPromise);
+ if (!multipart.UploadId)
+ throw new Error("Storage did not return a multipart upload id");
+ outputUpload = {
+ type: "multipart",
+ videoId: video.id,
+ generation: attempt.generation,
+ attemptId: attempt.attemptId,
+ key: outputKey,
+ uploadId: multipart.UploadId,
+ partSize: MULTIPART_OUTPUT_PART_SIZE_BYTES,
+ signPartUrl: getMediaServerWebhookUrl(
+ webhookBaseUrl,
+ "/api/webhooks/media-server/multipart/sign-part",
+ ),
+ completeUrl: getMediaServerWebhookUrl(
+ webhookBaseUrl,
+ "/api/webhooks/media-server/multipart/complete",
+ ),
+ abortUrl: getMediaServerWebhookUrl(
+ webhookBaseUrl,
+ "/api/webhooks/media-server/multipart/abort",
+ ),
+ webhookSecret,
+ };
+ }
const thumbnailPresignedUrl = await bucket
.getInternalPresignedPutUrl(
- thumbnailKey,
- {
- ContentType: "image/jpeg",
- },
- { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },
+ `${candidateDirectory}/screenshot.jpg`,
+ { ContentType: "image/jpeg" },
+ { expiresIn: PRESIGNED_EXPIRES_SECONDS },
)
.pipe(runWorkflowPromise);
const previewGifPresignedUrl = await bucket
.getInternalPresignedPutUrl(
- previewGifKey,
+ `${candidateDirectory}/preview.gif`,
{
ContentType: "image/gif",
CacheControl: "public, max-age=31536000, immutable",
},
- { expiresIn: MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS },
+ { expiresIn: PRESIGNED_EXPIRES_SECONDS },
)
.pipe(runWorkflowPromise);
-
- if (bucket.provider === "s3" && webhookSecret) {
- try {
- const signPartUrl = getMediaServerWebhookUrl(
- webhookBaseUrl,
- "/api/webhooks/media-server/multipart/sign-part",
- );
- const completeUrl = getMediaServerWebhookUrl(
- webhookBaseUrl,
- "/api/webhooks/media-server/multipart/complete",
- );
- const abortUrl = getMediaServerWebhookUrl(
- webhookBaseUrl,
- "/api/webhooks/media-server/multipart/abort",
- );
- const multipartUpload = await bucket.multipart
- .create(outputKey, { ContentType: "video/mp4" })
- .pipe(runWorkflowPromise);
- if (!multipartUpload.UploadId) {
- throw new Error("Storage did not return a multipart upload id");
- }
- outputUpload = {
- type: "multipart",
- videoId,
- key: outputKey,
- uploadId: multipartUpload.UploadId,
- partSize: MEDIA_SERVER_MULTIPART_OUTPUT_PART_SIZE_BYTES,
- signPartUrl,
- completeUrl,
- abortUrl,
- webhookSecret: webhookSecret || undefined,
- };
- } catch (error) {
- console.warn(
- `[finalizeDesktopRecordingWorkflow] Failed to create multipart output upload for ${videoId}:`,
- error,
- );
- }
- }
-
return {
- manifestSha256: completedManifest?.manifestSha256,
- expectedDuration: completedManifest?.duration,
+ outputKey,
outputVerificationUrl,
- videoId,
- userId,
outputPresignedUrl,
outputUpload,
thumbnailPresignedUrl,
previewGifPresignedUrl,
- videoInitUrl,
- videoSegmentUrls,
- audioInitUrl,
- audioSegmentUrls,
- webhookUrl: `${webhookBaseUrl}/api/webhooks/media-server/progress?retryable=true`,
- webhookSecret: webhookSecret || undefined,
};
}
-async function startDesktopMp4VerificationJob(
- videoId: string,
- userId: User.UserId,
- verification: RecordingVerification,
+export async function startDesktopRecordingJob(
+ attempt: DesktopRecordingAttempt,
): Promise<string> {
"use step";
- if (verification.artifact.kind !== "mp4") {
- throw new FatalError("An MP4 verification identity is required");
+ const current = await getProcessingState(attempt);
+ if (!current || current.attemptId !== attempt.attemptId || !current.source) {
+ throw new Error("Recording processing attempt was superseded");
}
+ if (current.remoteJobId) return current.remoteJobId;
const [video] = await db()
.select()
.from(videos)
.where(
- and(
- eq(videos.id, Video.VideoId.make(videoId)),
- eq(videos.ownerId, userId),
- ),
- );
- if (!video || video.source.type !== "desktopMP4") {
- throw new FatalError("Completed desktop recording does not exist");
- }
- const [bucket] = await Storage.getAccessForVideo(
- decodeStorageVideo(video),
- ).pipe(runWorkflowPromise);
- const key = `${userId}/${videoId}/result.mp4`;
- const head = await bucket.headObject(key).pipe(runWorkflowPromise);
- if (
- head.ETag !== verification.artifact.objectIdentity ||
- head.ContentLength !== verification.artifact.fileSize
- ) {
- throw new Error(
- "Uploaded recording does not match the completed local file",
+ and(eq(videos.id, current.videoId), eq(videos.ownerId, current.ownerId)),
);
- }
- const videoUrl = await bucket
- .getInternalSignedObjectUrl(key, {
- expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
- })
- .pipe(runWorkflowPromise);
+ if (!video) throw new Error("Recording does not exist");
const env = serverEnv();
if (!env.MEDIA_SERVER_URL || !env.MEDIA_SERVER_WEBHOOK_SECRET) {
throw new Error("Recording content verification is not configured");
}
+ const urls = await buildDesktopRecordingSourceUrls(
+ video,
+ current.source,
+ ).catch(async (error: unknown) => {
+ const code = getSourceErrorCode(error);
+ if (code) {
+ await markSourceBlocked({
+ ...attempt,
+ errorCode: code,
+ errorMessage: getErrorMessage(error),
+ });
+ }
+ throw error;
+ });
const webhookBaseUrl = env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL;
+ const context = {
+ videoId: current.videoId,
+ userId: current.ownerId,
+ generation: current.generation,
+ attemptId: attempt.attemptId,
+ inventorySha256: current.source.inventorySha256,
+ requiredAudio:
+ current.source.requiredAudio ||
+ current.verification?.requiredAudio === true,
+ webhookUrl: getMediaServerWebhookUrl(
+ webhookBaseUrl,
+ "/api/webhooks/media-server/progress?retryable=true",
+ ),
+ webhookSecret: env.MEDIA_SERVER_WEBHOOK_SECRET,
+ };
+ let path: string;
+ let body: Record<string, unknown>;
+ if (current.source.kind === "mp4") {
+ const mp4 = current.source.mp4;
+ if (
+ !mp4 ||
+ !urls.videoUrl ||
+ !urls.sourceObjectIdentity ||
+ !urls.outputKey
+ ) {
+ throw new Error("Committed MP4 source is missing its immutable identity");
+ }
+ path = "/video/verify-recording";
+ body = {
+ ...context,
+ ...urls,
+ fileSize: mp4.fileSize,
+ duration:
+ current.verification?.artifact.kind === "mp4"
+ ? current.verification.artifact.duration
+ : mp4.duration,
+ objectIdentity: mp4.objectIdentity,
+ originalObjectIdentity: mp4.objectIdentity,
+ outputKey: urls.outputKey,
+ };
+ } else {
+ if (!urls.videoInitUrl || !urls.videoSegmentUrls?.length) {
+ throw new Error(
+ "Committed segmented source is missing its video inventory",
+ );
+ }
+ path = "/video/mux-segments";
+ body = {
+ ...context,
+ ...urls,
+ ...(await buildDesktopSegmentsOutput({ video, attempt })),
+ manifestSha256: current.source.manifestSha256,
+ };
+ }
const response = await fetch(
- `${env.MEDIA_SERVER_URL}/video/verify-recording`,
+ `${env.MEDIA_SERVER_URL.replace(/\/$/, "")}${path}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"x-media-server-secret": env.MEDIA_SERVER_WEBHOOK_SECRET,
},
- body: JSON.stringify({
- videoId,
- userId,
- videoUrl,
- fileSize: verification.artifact.fileSize,
- duration: verification.artifact.duration,
- requiredAudio: verification.requiredAudio,
- objectIdentity: verification.artifact.objectIdentity,
- webhookUrl: getMediaServerWebhookUrl(
- webhookBaseUrl,
- "/api/webhooks/media-server/progress?retryable=true",
- ),
- webhookSecret: env.MEDIA_SERVER_WEBHOOK_SECRET,
- }),
+ body: JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
},
);
if (!response.ok) {
+ const detail = await response.text().catch(() => "");
throw new Error(
- `Failed to start recording verification: ${response.status}`,
+ `Failed to start recording processing: ${response.status} ${detail}`,
+ );
+ }
+ const result = z
+ .object({ jobId: z.string().min(1) })
+ .parse(await response.json());
+ if (!(await attachRemoteJob({ ...attempt, remoteJobId: result.jobId }))) {
+ throw new Error(
+ "Recording processing attempt expired before the worker was attached",
);
}
- const result: { jobId?: string } = await response.json();
- if (!result.jobId)
- throw new Error("Media server did not return a verification job id");
return result.jobId;
}
-async function startDesktopSegmentsMuxJob(
- videoId: string,
- userId: User.UserId,
-): Promise<string> {
+export async function pollDesktopRecordingAttempt({
+ jobId,
+ deadline,
+ ...fence
+}: DesktopRecordingAttemptFence & {
+ jobId: string;
+ deadline: Date;
+}): Promise<
+ "waiting" | "verified" | "retry" | "source-blocked" | "superseded"
+> {
"use step";
- const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
- if (!mediaServerUrl) {
- throw new FatalError("MEDIA_SERVER_URL is not configured");
- }
-
- const body = await buildDesktopSegmentsMuxBody(videoId, userId);
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- };
- if (body.webhookSecret) {
- headers["x-media-server-secret"] = body.webhookSecret;
+ let current = await getProcessingState(fence);
+ if (!current) return "superseded";
+ if (current.state === "verified") return "verified";
+ if (current.attemptId !== fence.attemptId) return "superseded";
+ if (current.state === "source-blocked") return "source-blocked";
+ if (current.state === "retry") return "retry";
+ const now = new Date();
+ if (now >= deadline) {
+ return (await scheduleRetry({
+ ...fence,
+ errorCode: "processing-timeout",
+ errorMessage:
+ "Processing did not finish within its attempt lease; source files are retained.",
+ now,
+ }))
+ ? "retry"
+ : "superseded";
}
-
- let response: Response;
- try {
- response = await fetch(`${mediaServerUrl}/video/mux-segments`, {
- method: "POST",
- headers,
- body: JSON.stringify(body),
- signal: AbortSignal.timeout(30_000),
+ const env = serverEnv();
+ if (env.MEDIA_SERVER_URL && current.source) {
+ const observation = await observeDesktopRecordingJob({
+ ...fence,
+ jobId,
+ inventorySha256: current.source.inventorySha256,
+ mediaServerUrl: env.MEDIA_SERVER_URL,
+ webhookUrl: getMediaServerWebhookUrl(
+ env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL,
+ "/api/webhooks/media-server/progress?retryable=true",
+ ),
+ secret: env.MEDIA_SERVER_WEBHOOK_SECRET,
});
- } catch (error) {
- await abortDesktopSegmentsOutputUpload(body.outputUpload).catch(
- (abortError) => {
- console.warn(
- `[finalizeDesktopRecordingWorkflow] Failed to abort output upload for ${videoId}:`,
- abortError,
- );
- },
- );
- throw error;
- }
-
- if (!response.ok) {
- await abortDesktopSegmentsOutputUpload(body.outputUpload).catch(
- (abortError) => {
- console.warn(
- `[finalizeDesktopRecordingWorkflow] Failed to abort output upload for ${videoId}:`,
- abortError,
- );
- },
- );
- const errorText = await response.text().catch(() => "");
- const message = `Failed to start segment muxing: ${response.status} ${errorText}`;
- if (response.status === 503 && isMediaServerCapacityError(message)) {
- throw createMediaServerCapacityError({
- response,
- message,
- videoId,
- });
- }
- throw new Error(message);
+ if (observation.status === "active") await heartbeatAttempt(fence);
}
-
- const result = (await response.json()) as { jobId?: string };
- if (!result.jobId) {
- throw new Error("Media server did not return a mux job id");
+ current = await getProcessingState(fence);
+ if (!current) return "superseded";
+ if (current.state === "verified") return "verified";
+ if (current.attemptId !== fence.attemptId) return "superseded";
+ if (current.state === "source-blocked") return "source-blocked";
+ if (current.state === "retry") return "retry";
+ if (!current.leaseExpiresAt || current.leaseExpiresAt <= new Date()) {
+ return (await scheduleRetry({
+ ...fence,
+ errorCode: "worker-lease-expired",
+ errorMessage:
+ "Processing worker is unavailable. Retrying from the retained recording source.",
+ }))
+ ? "retry"
+ : "superseded";
}
-
- return result.jobId;
+ return "waiting";
}
-async function waitForDesktopSegmentsMuxCompletion(
- videoId: string,
- jobId: string,
-): Promise<void> {
+async function retryDesktopRecordingAttempt(
+ attempt: DesktopRecordingAttemptFence,
+ errorMessage: string,
+ sourceErrorCode: ReturnType<typeof getSourceErrorCode>,
+): Promise<"retry" | "source-blocked" | "superseded"> {
"use step";
- let lastStatus = "processing";
-
- for (
- let attempt = 0;
- attempt < MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS;
- attempt++
- ) {
- await waitForRetry(MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS);
-
- const [video] = await db()
- .select({ source: videos.source })
- .from(videos)
- .where(eq(videos.id, Video.VideoId.make(videoId)));
- const [upload] = await db()
- .select({
- phase: videoUploads.phase,
- processingProgress: videoUploads.processingProgress,
- processingMessage: videoUploads.processingMessage,
- processingError: videoUploads.processingError,
- })
- .from(videoUploads)
- .where(eq(videoUploads.videoId, Video.VideoId.make(videoId)));
-
- if (video?.source?.type === "desktopMP4" && !upload) {
- return;
- }
-
- if (!upload) {
- const [currentVideo] = await db()
- .select({ source: videos.source })
- .from(videos)
- .where(eq(videos.id, Video.VideoId.make(videoId)));
-
- if (currentVideo?.source?.type === "desktopMP4") {
- return;
- }
-
- throw new Error("Segment muxing state disappeared before completion");
- }
-
- if (upload.processingError) {
- throw new Error(upload.processingError);
- }
-
- if (upload.phase === "error") {
- throw new Error(upload.processingMessage || "Segment muxing failed");
- }
-
- if (upload.phase === "complete") {
- return;
- }
-
- lastStatus = [
- upload.phase,
- typeof upload.processingProgress === "number"
- ? `${upload.processingProgress}%`
- : null,
- upload.processingMessage,
- ]
- .filter(Boolean)
- .join(" ");
-
- const env = serverEnv();
- const mediaServerUrl = env.MEDIA_SERVER_URL;
- if (mediaServerUrl && attempt % 3 === 0) {
- await reconcileDesktopRecordingJob({
- videoId,
- jobId,
- mediaServerUrl,
- webhookUrl: getMediaServerWebhookUrl(
- env.MEDIA_SERVER_WEBHOOK_URL || env.WEB_URL,
- "/api/webhooks/media-server/progress?retryable=true",
- ),
- secret: env.MEDIA_SERVER_WEBHOOK_SECRET,
- });
- }
+ const current = await getProcessingState(attempt);
+ if (!current || current.attemptId !== attempt.attemptId) return "superseded";
+ if (current.state === "source-blocked") return "source-blocked";
+ if (sourceErrorCode) {
+ return (await markSourceBlocked({
+ ...attempt,
+ errorCode: sourceErrorCode,
+ errorMessage,
+ }))
+ ? "source-blocked"
+ : "superseded";
}
-
- throw new Error(`Segment muxing timed out while ${lastStatus}`);
+ return (await scheduleRetry({
+ ...attempt,
+ errorCode: "processing-interrupted",
+ errorMessage,
+ }))
+ ? "retry"
+ : "superseded";
}
async function queueFinalizedRecordingTranscription(
videoId: string,
userId: User.UserId,
-): Promise<void> {
+): Promise<boolean> {
"use step";
- const [owner] = await db()
- .select({
- email: users.email,
- stripeSubscriptionStatus: users.stripeSubscriptionStatus,
- thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,
- })
- .from(users)
- .where(eq(users.id, userId));
-
- const aiGenerationEnabled = isAiGenerationEnabledForUser(owner);
-
- const result = await transcribeVideo(
- Video.VideoId.make(videoId),
- userId,
- aiGenerationEnabled,
- );
-
- if (!result.success) {
+ if (!serverEnv().ASSEMBLY_API_KEY) return true;
+ try {
+ const [[owner], [video]] = await Promise.all([
+ db()
+ .select({
+ email: users.email,
+ stripeSubscriptionStatus: users.stripeSubscriptionStatus,
+ thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,
+ })
+ .from(users)
+ .where(eq(users.id, userId)),
+ db()
+ .select({ id: videos.id })
+ .from(videos)
+ .where(
+ and(
+ eq(videos.id, Video.VideoId.make(videoId)),
+ eq(videos.ownerId, userId),
+ ),
+ ),
+ ]);
+ if (!owner || !video) return true;
+ const result = await transcribeVideo(
+ Video.VideoId.make(videoId),
+ userId,
+ isAiGenerationEnabledForUser(owner),
+ );
+ if (result.success) return true;
console.warn(
- "[finalizeDesktopRecordingWorkflow] Failed to queue transcription",
- {
- videoId,
- message: result.message,
- },
+ "[finalizeDesktopRecordingWorkflow] Transcription enqueue will retry",
+ { videoId, message: result.message },
+ );
+ } catch (error) {
+ console.warn(
+ "[finalizeDesktopRecordingWorkflow] Transcription enqueue interrupted",
+ { videoId, error: getErrorMessage(error) },
);
}
+ return false;
}
diff --git a/packages/database/migrations/0040_recording_jobs.sql b/packages/database/migrations/0040_recording_jobs.sql
new file mode 100644
index 000000000..f745081d9
--- /dev/null
+++ b/packages/database/migrations/0040_recording_jobs.sql
@@ -0,0 +1,24 @@
+CREATE TABLE `video_processing_jobs` (
+ `video_id` varchar(15) NOT NULL,
+ `owner_id` varchar(15) NOT NULL,
+ `generation` varchar(64) NOT NULL,
+ `manifest_sha256` varchar(64),
+ `state` varchar(32) NOT NULL DEFAULT 'committing',
+ `attempt_id` varchar(64),
+ `attempt_count` int NOT NULL DEFAULT 0,
+ `lease_expires_at` datetime(3),
+ `next_retry_at` datetime(3) NOT NULL,
+ `workflow_run_id` varchar(255),
+ `remote_job_id` varchar(255),
+ `source` json,
+ `verification` json,
+ `output` json,
+ `error_code` varchar(64),
+ `error_message` text,
+ `created_at` datetime(3) NOT NULL,
+ `updated_at` datetime(3) NOT NULL,
+ CONSTRAINT `video_processing_jobs_video_id` PRIMARY KEY(`video_id`)
+);
+--> statement-breakpoint
+CREATE INDEX `processing_state_retry_video_idx` ON `video_processing_jobs` (`state`,`next_retry_at`,`video_id`);--> statement-breakpoint
+CREATE INDEX `processing_state_lease_video_idx` ON `video_processing_jobs` (`state`,`lease_expires_at`,`video_id`);
\ No newline at end of file
diff --git a/packages/database/migrations/meta/0040_snapshot.json b/packages/database/migrations/meta/0040_snapshot.json
new file mode 100644
index 000000000..a449505e8
--- /dev/null
+++ b/packages/database/migrations/meta/0040_snapshot.json
@@ -0,0 +1,4250 @@
+{
+ "version": "5",
+ "dialect": "mysql",
+ "id": "d3819b61-0792-4202-be07-391cea1c820d",
+ "prevId": "c95c8755-4ef8-4c51-ad10-5bd19717d269",
+ "tables": {
+ "accounts": {
+ "name": "accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_in": {
+ "name": "expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_in": {
+ "name": "refresh_token_expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "tempColumn": {
+ "name": "tempColumn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ },
+ "provider_account_id_idx": {
+ "name": "provider_account_id_idx",
+ "columns": ["providerAccountId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "accounts_id": {
+ "name": "accounts_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_authorization_codes": {
+ "name": "agent_api_authorization_codes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "codeHash": {
+ "name": "codeHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "codeChallenge": {
+ "name": "codeChallenge",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirectUri": {
+ "name": "redirectUri",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "code_hash_idx": {
+ "name": "code_hash_idx",
+ "columns": ["codeHash"],
+ "isUnique": true
+ },
+ "expires_at_idx": {
+ "name": "expires_at_idx",
+ "columns": ["expiresAt"],
+ "isUnique": false
+ },
+ "user_created_at_idx": {
+ "name": "user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_authorization_codes_id": {
+ "name": "agent_api_authorization_codes_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_idempotency": {
+ "name": "agent_api_idempotency",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "operation": {
+ "name": "operation",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyHash": {
+ "name": "keyHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "requestHash": {
+ "name": "requestHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "statusCode": {
+ "name": "statusCode",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "response": {
+ "name": "response",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_operation_key_idx": {
+ "name": "user_operation_key_idx",
+ "columns": ["userId", "operation", "keyHash"],
+ "isUnique": true
+ },
+ "expires_at_idx": {
+ "name": "expires_at_idx",
+ "columns": ["expiresAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_idempotency_id": {
+ "name": "agent_api_idempotency_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_keys": {
+ "name": "agent_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(100)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Cap CLI'"
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "token_hash_idx": {
+ "name": "token_hash_idx",
+ "columns": ["tokenHash"],
+ "isUnique": true
+ },
+ "user_created_at_idx": {
+ "name": "user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ },
+ "expires_at_idx": {
+ "name": "expires_at_idx",
+ "columns": ["expiresAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_keys_id": {
+ "name": "agent_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "agent_api_operations": {
+ "name": "agent_api_operations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "resultResourceId": {
+ "name": "resultResourceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "errorCode": {
+ "name": "errorCode",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "errorMessage": {
+ "name": "errorMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "completedAt": {
+ "name": "completedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_created_at_idx": {
+ "name": "user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ },
+ "state_updated_at_idx": {
+ "name": "state_updated_at_idx",
+ "columns": ["state", "updatedAt"],
+ "isUnique": false
+ },
+ "resource_id_idx": {
+ "name": "resource_id_idx",
+ "columns": ["resourceId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "agent_api_operations_id": {
+ "name": "agent_api_operations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "auth_api_keys": {
+ "name": "auth_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(36)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_id_created_at_idx": {
+ "name": "user_id_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "auth_api_keys_id": {
+ "name": "auth_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "comments": {
+ "name": "comments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(6)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "authorId": {
+ "name": "authorId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "parentCommentId": {
+ "name": "parentCommentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mediaKey": {
+ "name": "mediaKey",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mediaDuration": {
+ "name": "mediaDuration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "mediaMeta": {
+ "name": "mediaMeta",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "video_type_created_idx": {
+ "name": "video_type_created_idx",
+ "columns": ["videoId", "type", "createdAt", "id"],
+ "isUnique": false
+ },
+ "author_id_idx": {
+ "name": "author_id_idx",
+ "columns": ["authorId"],
+ "isUnique": false
+ },
+ "parent_comment_id_idx": {
+ "name": "parent_comment_id_idx",
+ "columns": ["parentCommentId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "comments_id": {
+ "name": "comments_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_api_keys": {
+ "name": "developer_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyType": {
+ "name": "keyType",
+ "type": "varchar(8)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyPrefix": {
+ "name": "keyPrefix",
+ "type": "varchar(12)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "keyHash": {
+ "name": "keyHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "encryptedKey": {
+ "name": "encryptedKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "key_hash_idx": {
+ "name": "key_hash_idx",
+ "columns": ["keyHash"],
+ "isUnique": true
+ },
+ "app_key_type_idx": {
+ "name": "app_key_type_idx",
+ "columns": ["appId", "keyType"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "developer_api_keys_appId_developer_apps_id_fk": {
+ "name": "developer_api_keys_appId_developer_apps_id_fk",
+ "tableFrom": "developer_api_keys",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_api_keys_id": {
+ "name": "developer_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_app_domains": {
+ "name": "developer_app_domains",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "varchar(253)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "developer_app_domains_appId_developer_apps_id_fk": {
+ "name": "developer_app_domains_appId_developer_apps_id_fk",
+ "tableFrom": "developer_app_domains",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_app_domains_id": {
+ "name": "developer_app_domains_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "app_domain_unique": {
+ "name": "app_domain_unique",
+ "columns": ["appId", "domain"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "developer_apps": {
+ "name": "developer_apps",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "logoUrl": {
+ "name": "logoUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deletedAt": {
+ "name": "deletedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "owner_deleted_idx": {
+ "name": "owner_deleted_idx",
+ "columns": ["ownerId", "deletedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "developer_apps_id": {
+ "name": "developer_apps_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_credit_accounts": {
+ "name": "developer_credit_accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "balanceMicroCredits": {
+ "name": "balanceMicroCredits",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripePaymentMethodId": {
+ "name": "stripePaymentMethodId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "autoTopUpEnabled": {
+ "name": "autoTopUpEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "autoTopUpThresholdMicroCredits": {
+ "name": "autoTopUpThresholdMicroCredits",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "autoTopUpAmountCents": {
+ "name": "autoTopUpAmountCents",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "app_id_unique": {
+ "name": "app_id_unique",
+ "columns": ["appId"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "developer_credit_accounts_appId_developer_apps_id_fk": {
+ "name": "developer_credit_accounts_appId_developer_apps_id_fk",
+ "tableFrom": "developer_credit_accounts",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_credit_accounts_id": {
+ "name": "developer_credit_accounts_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_credit_transactions": {
+ "name": "developer_credit_transactions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "amountMicroCredits": {
+ "name": "amountMicroCredits",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "balanceAfterMicroCredits": {
+ "name": "balanceAfterMicroCredits",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "referenceType": {
+ "name": "referenceType",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "account_type_created_idx": {
+ "name": "account_type_created_idx",
+ "columns": ["accountId", "type", "createdAt"],
+ "isUnique": false
+ },
+ "account_ref_dedup_idx": {
+ "name": "account_ref_dedup_idx",
+ "columns": ["accountId", "referenceId", "referenceType"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "dev_credit_txn_account_fk": {
+ "name": "dev_credit_txn_account_fk",
+ "tableFrom": "developer_credit_transactions",
+ "tableTo": "developer_credit_accounts",
+ "columnsFrom": ["accountId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_credit_transactions_id": {
+ "name": "developer_credit_transactions_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "developer_daily_storage_snapshots": {
+ "name": "developer_daily_storage_snapshots",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshotDate": {
+ "name": "snapshotDate",
+ "type": "varchar(10)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "totalDurationMinutes": {
+ "name": "totalDurationMinutes",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "videoCount": {
+ "name": "videoCount",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "microCreditsCharged": {
+ "name": "microCreditsCharged",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "processedAt": {
+ "name": "processedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "developer_daily_storage_snapshots_appId_developer_apps_id_fk": {
+ "name": "developer_daily_storage_snapshots_appId_developer_apps_id_fk",
+ "tableFrom": "developer_daily_storage_snapshots",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_daily_storage_snapshots_id": {
+ "name": "developer_daily_storage_snapshots_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "app_date_unique": {
+ "name": "app_date_unique",
+ "columns": ["appId", "snapshotDate"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "developer_videos": {
+ "name": "developer_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "appId": {
+ "name": "appId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "externalUserId": {
+ "name": "externalUserId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Untitled'"
+ },
+ "duration": {
+ "name": "duration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "width": {
+ "name": "width",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fps": {
+ "name": "fps",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "s3Key": {
+ "name": "s3Key",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "transcriptionStatus": {
+ "name": "transcriptionStatus",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deletedAt": {
+ "name": "deletedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "app_created_idx": {
+ "name": "app_created_idx",
+ "columns": ["appId", "createdAt"],
+ "isUnique": false
+ },
+ "app_user_idx": {
+ "name": "app_user_idx",
+ "columns": ["appId", "externalUserId"],
+ "isUnique": false
+ },
+ "app_deleted_idx": {
+ "name": "app_deleted_idx",
+ "columns": ["appId", "deletedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "developer_videos_appId_developer_apps_id_fk": {
+ "name": "developer_videos_appId_developer_apps_id_fk",
+ "tableFrom": "developer_videos",
+ "tableTo": "developer_apps",
+ "columnsFrom": ["appId"],
+ "columnsTo": ["id"],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "developer_videos_id": {
+ "name": "developer_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "folders": {
+ "name": "folders",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "created_by_id_idx": {
+ "name": "created_by_id_idx",
+ "columns": ["createdById"],
+ "isUnique": false
+ },
+ "parent_id_idx": {
+ "name": "parent_id_idx",
+ "columns": ["parentId"],
+ "isUnique": false
+ },
+ "space_id_idx": {
+ "name": "space_id_idx",
+ "columns": ["spaceId"],
+ "isUnique": false
+ },
+ "public_parent_id_idx": {
+ "name": "public_parent_id_idx",
+ "columns": ["public", "parentId"],
+ "isUnique": false
+ },
+ "public_space_parent_id_idx": {
+ "name": "public_space_parent_id_idx",
+ "columns": ["public", "spaceId", "parentId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "folders_id": {
+ "name": "folders_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "imported_videos": {
+ "name": "imported_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "imported_videos_orgId_source_source_id_pk": {
+ "name": "imported_videos_orgId_source_source_id_pk",
+ "columns": ["orgId", "source", "source_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "integration_installations": {
+ "name": "integration_installations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "externalId": {
+ "name": "externalId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "displayName": {
+ "name": "displayName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "installedByUserId": {
+ "name": "installedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "encryptedCredentials": {
+ "name": "encryptedCredentials",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "provider_external_id_idx": {
+ "name": "provider_external_id_idx",
+ "columns": ["provider", "externalId"],
+ "isUnique": true
+ },
+ "organization_provider_display_name_idx": {
+ "name": "organization_provider_display_name_idx",
+ "columns": ["organizationId", "provider", "displayName"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "integration_installations_id": {
+ "name": "integration_installations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "messenger_conversations": {
+ "name": "messenger_conversations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent": {
+ "name": "agent",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'agent'"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "anonymousId": {
+ "name": "anonymousId",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "takeoverByUserId": {
+ "name": "takeoverByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "takeoverAt": {
+ "name": "takeoverAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "lastMessageAt": {
+ "name": "lastMessageAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_last_message_idx": {
+ "name": "user_last_message_idx",
+ "columns": ["userId", "lastMessageAt"],
+ "isUnique": false
+ },
+ "anonymous_last_message_idx": {
+ "name": "anonymous_last_message_idx",
+ "columns": ["anonymousId", "lastMessageAt"],
+ "isUnique": false
+ },
+ "mode_last_message_idx": {
+ "name": "mode_last_message_idx",
+ "columns": ["mode", "lastMessageAt"],
+ "isUnique": false
+ },
+ "updated_at_idx": {
+ "name": "updated_at_idx",
+ "columns": ["updatedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "messenger_conversations_id": {
+ "name": "messenger_conversations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "messenger_messages": {
+ "name": "messenger_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "anonymousId": {
+ "name": "anonymousId",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "conversation_created_at_idx": {
+ "name": "conversation_created_at_idx",
+ "columns": ["conversationId", "createdAt"],
+ "isUnique": false
+ },
+ "role_created_at_idx": {
+ "name": "role_created_at_idx",
+ "columns": ["role", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "messenger_messages_conversationId_messenger_conversations_id_fk": {
+ "name": "messenger_messages_conversationId_messenger_conversations_id_fk",
+ "tableFrom": "messenger_messages",
+ "tableTo": "messenger_conversations",
+ "columnsFrom": ["conversationId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "messenger_messages_id": {
+ "name": "messenger_messages_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "messenger_support_emails": {
+ "name": "messenger_support_emails",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userEmail": {
+ "name": "userEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subject": {
+ "name": "subject",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "support_email_user_created_at_idx": {
+ "name": "support_email_user_created_at_idx",
+ "columns": ["userId", "createdAt"],
+ "isUnique": false
+ },
+ "support_email_conversation_created_at_idx": {
+ "name": "support_email_conversation_created_at_idx",
+ "columns": ["conversationId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "support_email_conversation_fk": {
+ "name": "support_email_conversation_fk",
+ "tableFrom": "messenger_support_emails",
+ "tableTo": "messenger_conversations",
+ "columnsFrom": ["conversationId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "messenger_support_emails_id": {
+ "name": "messenger_support_emails_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "notifications": {
+ "name": "notifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipientId": {
+ "name": "recipientId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "data": {
+ "name": "data",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(50)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dedupKey": {
+ "name": "dedupKey",
+ "type": "varchar(128)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "readAt": {
+ "name": "readAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "org_id_idx": {
+ "name": "org_id_idx",
+ "columns": ["orgId"],
+ "isUnique": false
+ },
+ "type_idx": {
+ "name": "type_idx",
+ "columns": ["type"],
+ "isUnique": false
+ },
+ "read_at_idx": {
+ "name": "read_at_idx",
+ "columns": ["readAt"],
+ "isUnique": false
+ },
+ "created_at_idx": {
+ "name": "created_at_idx",
+ "columns": ["createdAt"],
+ "isUnique": false
+ },
+ "recipient_read_idx": {
+ "name": "recipient_read_idx",
+ "columns": ["recipientId", "readAt"],
+ "isUnique": false
+ },
+ "recipient_created_idx": {
+ "name": "recipient_created_idx",
+ "columns": ["recipientId", "createdAt"],
+ "isUnique": false
+ },
+ "dedup_key_idx": {
+ "name": "dedup_key_idx",
+ "columns": ["dedupKey"],
+ "isUnique": true
+ },
+ "type_recipient_created_idx": {
+ "name": "type_recipient_created_idx",
+ "columns": ["type", "recipientId", "createdAt"],
+ "isUnique": false
+ },
+ "type_recipient_video_created_idx": {
+ "name": "type_recipient_video_created_idx",
+ "columns": ["type", "recipientId", "videoId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "notifications_id": {
+ "name": "notifications_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_invites": {
+ "name": "organization_invites",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedEmail": {
+ "name": "invitedEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedByUserId": {
+ "name": "invitedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "invited_email_idx": {
+ "name": "invited_email_idx",
+ "columns": ["invitedEmail"],
+ "isUnique": false
+ },
+ "invited_by_user_id_idx": {
+ "name": "invited_by_user_id_idx",
+ "columns": ["invitedByUserId"],
+ "isUnique": false
+ },
+ "status_idx": {
+ "name": "status_idx",
+ "columns": ["status"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_invites_id": {
+ "name": "organization_invites_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_members": {
+ "name": "organization_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hasProSeat": {
+ "name": "hasProSeat",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "user_id_organization_id_idx": {
+ "name": "user_id_organization_id_idx",
+ "columns": ["userId", "organizationId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_members_id": {
+ "name": "organization_members_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tombstoneAt": {
+ "name": "tombstoneAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "allowedEmailDomain": {
+ "name": "allowedEmailDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customDomain": {
+ "name": "customDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "domainVerified": {
+ "name": "domainVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "iconUrl": {
+ "name": "iconUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "shareableLinkIconUrl": {
+ "name": "shareableLinkIconUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "workosOrganizationId": {
+ "name": "workosOrganizationId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workosConnectionId": {
+ "name": "workosConnectionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "owner_id_tombstone_idx": {
+ "name": "owner_id_tombstone_idx",
+ "columns": ["ownerId", "tombstoneAt"],
+ "isUnique": false
+ },
+ "custom_domain_idx": {
+ "name": "custom_domain_idx",
+ "columns": ["customDomain"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organizations_id": {
+ "name": "organizations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "s3_buckets": {
+ "name": "s3_buckets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bucketName": {
+ "name": "bucketName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accessKeyId": {
+ "name": "accessKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secretAccessKey": {
+ "name": "secretAccessKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('aws')"
+ },
+ "active": {
+ "name": "active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "owner_organization_idx": {
+ "name": "owner_organization_idx",
+ "columns": ["ownerId", "organizationId"],
+ "isUnique": false
+ },
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "organization_active_idx": {
+ "name": "organization_active_idx",
+ "columns": ["organizationId", "active", "updatedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "s3_buckets_id": {
+ "name": "s3_buckets_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "session_token_idx": {
+ "name": "session_token_idx",
+ "columns": ["sessionToken"],
+ "isUnique": true
+ },
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "sessions_id": {
+ "name": "sessions_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "shared_videos": {
+ "name": "shared_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedByUserId": {
+ "name": "sharedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedAt": {
+ "name": "sharedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "shared_by_user_id_idx": {
+ "name": "shared_by_user_id_idx",
+ "columns": ["sharedByUserId"],
+ "isUnique": false
+ },
+ "video_id_organization_id_idx": {
+ "name": "video_id_organization_id_idx",
+ "columns": ["videoId", "organizationId"],
+ "isUnique": false
+ },
+ "video_id_folder_id_idx": {
+ "name": "video_id_folder_id_idx",
+ "columns": ["videoId", "folderId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "shared_videos_id": {
+ "name": "shared_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "signed_baas": {
+ "name": "signed_baas",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "entityName": {
+ "name": "entityName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "entityType": {
+ "name": "entityType",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "entityAddress": {
+ "name": "entityAddress",
+ "type": "varchar(500)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signerName": {
+ "name": "signerName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signerTitle": {
+ "name": "signerTitle",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "noticesEmail": {
+ "name": "noticesEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signatureData": {
+ "name": "signatureData",
+ "type": "longtext",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "signedAt": {
+ "name": "signedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "emailSentAt": {
+ "name": "emailSentAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "signed_baa_organization_id_idx": {
+ "name": "signed_baa_organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": true
+ },
+ "signed_baa_stripe_subscription_idx": {
+ "name": "signed_baa_stripe_subscription_idx",
+ "columns": ["stripeSubscriptionId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "signed_baas_id": {
+ "name": "signed_baas_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "space_members": {
+ "name": "space_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_members_id": {
+ "name": "space_members_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "space_id_user_id_unique": {
+ "name": "space_id_user_id_unique",
+ "columns": ["spaceId", "userId"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "space_videos": {
+ "name": "space_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedById": {
+ "name": "addedById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedAt": {
+ "name": "addedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": ["videoId"],
+ "isUnique": false
+ },
+ "added_by_id_idx": {
+ "name": "added_by_id_idx",
+ "columns": ["addedById"],
+ "isUnique": false
+ },
+ "space_id_video_id_idx": {
+ "name": "space_id_video_id_idx",
+ "columns": ["spaceId", "videoId"],
+ "isUnique": false
+ },
+ "space_id_folder_id_idx": {
+ "name": "space_id_folder_id_idx",
+ "columns": ["spaceId", "folderId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_videos_id": {
+ "name": "space_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "spaces": {
+ "name": "spaces",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "primary": {
+ "name": "primary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "iconUrl": {
+ "name": "iconUrl",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(1000)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "privacy": {
+ "name": "privacy",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Private'"
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "created_by_id_idx": {
+ "name": "created_by_id_idx",
+ "columns": ["createdById"],
+ "isUnique": false
+ },
+ "public_organization_id_idx": {
+ "name": "public_organization_id_idx",
+ "columns": ["public", "organizationId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "spaces_id": {
+ "name": "spaces_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "storage_integrations": {
+ "name": "storage_integrations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "displayName": {
+ "name": "displayName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "active": {
+ "name": "active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "encryptedConfig": {
+ "name": "encryptedConfig",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "googleDriveAccessToken": {
+ "name": "googleDriveAccessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveAccessTokenExpiresAt": {
+ "name": "googleDriveAccessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveTokenRefreshLeaseId": {
+ "name": "googleDriveTokenRefreshLeaseId",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveTokenRefreshLeaseExpiresAt": {
+ "name": "googleDriveTokenRefreshLeaseExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "googleDriveStorageQuotaCache": {
+ "name": "googleDriveStorageQuotaCache",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "owner_provider_idx": {
+ "name": "owner_provider_idx",
+ "columns": ["ownerId", "provider"],
+ "isUnique": false
+ },
+ "owner_active_idx": {
+ "name": "owner_active_idx",
+ "columns": ["ownerId", "active"],
+ "isUnique": false
+ },
+ "organization_provider_idx": {
+ "name": "organization_provider_idx",
+ "columns": ["organizationId", "provider"],
+ "isUnique": false
+ },
+ "organization_active_idx": {
+ "name": "organization_active_idx",
+ "columns": ["organizationId", "active", "status"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "storage_integrations_id": {
+ "name": "storage_integrations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "storage_objects": {
+ "name": "storage_objects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "integrationId": {
+ "name": "integrationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "objectKey": {
+ "name": "objectKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "objectKeyHash": {
+ "name": "objectKeyHash",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerObjectId": {
+ "name": "providerObjectId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploadSessionUrl": {
+ "name": "uploadSessionUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "uploadStatus": {
+ "name": "uploadStatus",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "contentType": {
+ "name": "contentType",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "contentLength": {
+ "name": "contentLength",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "integration_key_hash_idx": {
+ "name": "integration_key_hash_idx",
+ "columns": ["integrationId", "objectKeyHash"],
+ "isUnique": true
+ },
+ "integration_status_idx": {
+ "name": "integration_status_idx",
+ "columns": ["integrationId", "uploadStatus"],
+ "isUnique": false
+ },
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": ["videoId"],
+ "isUnique": false
+ },
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": ["ownerId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "storage_objects_integrationId_storage_integrations_id_fk": {
+ "name": "storage_objects_integrationId_storage_integrations_id_fk",
+ "tableFrom": "storage_objects",
+ "tableTo": "storage_integrations",
+ "columnsFrom": ["integrationId"],
+ "columnsTo": ["id"],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "storage_objects_id": {
+ "name": "storage_objects_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastName": {
+ "name": "lastName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thirdPartyStripeSubscriptionId": {
+ "name": "thirdPartyStripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionStatus": {
+ "name": "stripeSubscriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionPriceId": {
+ "name": "stripeSubscriptionPriceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "preferences": {
+ "name": "preferences",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "('null')"
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "onboardingSteps": {
+ "name": "onboardingSteps",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "onboarding_completed_at": {
+ "name": "onboarding_completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customBucket": {
+ "name": "customBucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "inviteQuota": {
+ "name": "inviteQuota",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "defaultOrgId": {
+ "name": "defaultOrgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "authSessionVersion": {
+ "name": "authSessionVersion",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "email_idx": {
+ "name": "email_idx",
+ "columns": ["email"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "users_id": {
+ "name": "users_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "verification_tokens": {
+ "name": "verification_tokens",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_tokens_identifier": {
+ "name": "verification_tokens_identifier",
+ "columns": ["identifier"]
+ }
+ },
+ "uniqueConstraints": {
+ "verification_tokens_token_unique": {
+ "name": "verification_tokens_token_unique",
+ "columns": ["token"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "video_edits": {
+ "name": "video_edits",
+ "columns": {
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sourceKey": {
+ "name": "sourceKey",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "editSpec": {
+ "name": "editSpec",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "video_edits_videoId_videos_id_fk": {
+ "name": "video_edits_videoId_videos_id_fk",
+ "tableFrom": "video_edits",
+ "tableTo": "videos",
+ "columnsFrom": ["videoId"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "video_edits_videoId": {
+ "name": "video_edits_videoId",
+ "columns": ["videoId"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "video_processing_jobs": {
+ "name": "video_processing_jobs",
+ "columns": {
+ "video_id": {
+ "name": "video_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "manifest_sha256": {
+ "name": "manifest_sha256",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'committing'"
+ },
+ "attempt_id": {
+ "name": "attempt_id",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "attempt_count": {
+ "name": "attempt_count",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "lease_expires_at": {
+ "name": "lease_expires_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_retry_at": {
+ "name": "next_retry_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workflow_run_id": {
+ "name": "workflow_run_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "remote_job_id": {
+ "name": "remote_job_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "verification": {
+ "name": "verification",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "output": {
+ "name": "output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "varchar(64)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "datetime(3)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "processing_state_retry_video_idx": {
+ "name": "processing_state_retry_video_idx",
+ "columns": ["state", "next_retry_at", "video_id"],
+ "isUnique": false
+ },
+ "processing_state_lease_video_idx": {
+ "name": "processing_state_lease_video_idx",
+ "columns": ["state", "lease_expires_at", "video_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "video_processing_jobs_video_id": {
+ "name": "video_processing_jobs_video_id",
+ "columns": ["video_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "video_uploads": {
+ "name": "video_uploads",
+ "columns": {
+ "video_id": {
+ "name": "video_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploaded": {
+ "name": "uploaded",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total": {
+ "name": "total",
+ "type": "bigint unsigned",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "phase": {
+ "name": "phase",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'uploading'"
+ },
+ "processing_progress": {
+ "name": "processing_progress",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "processing_message": {
+ "name": "processing_message",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "processing_error": {
+ "name": "processing_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "raw_file_key": {
+ "name": "raw_file_key",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "phase_updated_at_video_id_idx": {
+ "name": "phase_updated_at_video_id_idx",
+ "columns": ["phase", "updated_at", "video_id"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "video_uploads_video_id": {
+ "name": "video_uploads_video_id",
+ "columns": ["video_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "videos": {
+ "name": "videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'My Video'"
+ },
+ "bucket": {
+ "name": "bucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "storageIntegrationId": {
+ "name": "storageIntegrationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration": {
+ "name": "duration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "width": {
+ "name": "width",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fps": {
+ "name": "fps",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "transcriptionStatus": {
+ "name": "transcriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('{\"type\":\"MediaConvert\"}')"
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "effectiveCreatedAt": {
+ "name": "effectiveCreatedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "generated": {
+ "as": "COALESCE(\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%s.%fZ'),\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%sZ'),\n `createdAt`\n )",
+ "type": "stored"
+ }
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "xStreamInfo": {
+ "name": "xStreamInfo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "firstViewEmailSentAt": {
+ "name": "firstViewEmailSentAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "isScreenshot": {
+ "name": "isScreenshot",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "awsRegion": {
+ "name": "awsRegion",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awsBucket": {
+ "name": "awsBucket",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "videoStartTime": {
+ "name": "videoStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "audioStartTime": {
+ "name": "audioStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobId": {
+ "name": "jobId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobStatus": {
+ "name": "jobStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skipProcessing": {
+ "name": "skipProcessing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": ["ownerId"],
+ "isUnique": false
+ },
+ "is_public_idx": {
+ "name": "is_public_idx",
+ "columns": ["public"],
+ "isUnique": false
+ },
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "storage_integration_id_idx": {
+ "name": "storage_integration_id_idx",
+ "columns": ["storageIntegrationId"],
+ "isUnique": false
+ },
+ "org_owner_folder_idx": {
+ "name": "org_owner_folder_idx",
+ "columns": ["orgId", "ownerId", "folderId"],
+ "isUnique": false
+ },
+ "org_effective_created_idx": {
+ "name": "org_effective_created_idx",
+ "columns": ["orgId", "effectiveCreatedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "videos_storageIntegrationId_storage_integrations_id_fk": {
+ "name": "videos_storageIntegrationId_storage_integrations_id_fk",
+ "tableFrom": "videos",
+ "tableTo": "storage_integrations",
+ "columnsFrom": ["storageIntegrationId"],
+ "columnsTo": ["id"],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "videos_id": {
+ "name": "videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ }
+ },
+ "views": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "tables": {},
+ "indexes": {}
+ }
+}
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index d5ab96235..2c1193952 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -281,6 +281,13 @@
"when": 1787096888361,
"tag": "0039_magical_vermin",
"breakpoints": true
+ },
+ {
+ "idx": 40,
+ "version": "5",
+ "when": 1788366318415,
+ "tag": "0040_recording_jobs",
+ "breakpoints": true
}
]
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 1510b6d44..c56643f67 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -389,7 +389,12 @@ export const videos = mysqlTable(
.$type<
| { type: "MediaConvert" }
| { type: "local" }
- | { type: "desktopMP4" }
+ | {
+ type: "desktopMP4";
+ outputKey?: string;
+ thumbnailKey?: string;
+ previewKey?: string;
+ }
| { type: "desktopSegments" }
| { type: "webMP4" }
>()
@@ -1386,6 +1391,56 @@ export const videoUploads = mysqlTable(
],
);
+export const videoProcessingJobs = mysqlTable(
+ "video_processing_jobs",
+ {
+ videoId: nanoId("video_id").primaryKey().notNull().$type<Video.VideoId>(),
+ ownerId: nanoId("owner_id").notNull().$type<User.UserId>(),
+ generation: varchar("generation", { length: 64 }).notNull(),
+ manifestSha256: varchar("manifest_sha256", { length: 64 }),
+ state: varchar("state", { length: 32 })
+ .$type<
+ | "committing"
+ | "queued"
+ | "processing"
+ | "retry"
+ | "verified"
+ | "source-blocked"
+ >()
+ .notNull()
+ .default("committing"),
+ attemptId: varchar("attempt_id", { length: 64 }),
+ attemptCount: int("attempt_count").notNull().default(0),
+ leaseExpiresAt: datetime("lease_expires_at", { fsp: 3 }),
+ nextRetryAt: datetime("next_retry_at", { fsp: 3 }).notNull(),
+ workflowRunId: varchar("workflow_run_id", { length: 255 }),
+ remoteJobId: varchar("remote_job_id", { length: 255 }),
+ source: json("source").$type<unknown>(),
+ verification: json("verification").$type<unknown>(),
+ output: json("output").$type<unknown>(),
+ errorCode: varchar("error_code", { length: 64 }),
+ errorMessage: text("error_message"),
+ createdAt: datetime("created_at", { fsp: 3 })
+ .notNull()
+ .$defaultFn(() => new Date()),
+ updatedAt: datetime("updated_at", { fsp: 3 })
+ .notNull()
+ .$defaultFn(() => new Date()),
+ },
+ (table) => [
+ index("processing_state_retry_video_idx").on(
+ table.state,
+ table.nextRetryAt,
+ table.videoId,
+ ),
+ index("processing_state_lease_video_idx").on(
+ table.state,
+ table.leaseExpiresAt,
+ table.videoId,
+ ),
+ ],
+);
+
export const importedVideos = mysqlTable(
"imported_videos",
{
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index db774dddf..aa846dad2 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -22,6 +22,18 @@ export interface VideoMetadata {
fullDecode: true;
requiredAudioVerified?: boolean;
objectIdentity: string;
+ outputKey?: string;
+ outputSha256?: string;
+ sourceObjectIdentity?: string;
+ sourceProof?: {
+ version: 1;
+ manifestSha256: string;
+ inventorySha256: string;
+ sourcePreserved: true;
+ videoDuration: number;
+ hasAudio: boolean;
+ audioVerified: boolean;
+ };
};
/**
* Custom created date that can be edited by the user
diff --git a/packages/web-backend/src/S3Buckets/S3BucketAccess.ts b/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
index 4f2002fda..19911c26d 100644
--- a/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
+++ b/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
@@ -328,7 +328,20 @@ export const createS3BucketAccess = Effect.gen(function* () {
),
),
),
- ).pipe(Effect.when(() => objects.length > 0)),
+ ).pipe(
+ Effect.flatMap((response) =>
+ response.Errors?.length
+ ? Effect.fail(
+ new S3Error({
+ cause: new Error(
+ `S3 rejected deletion of ${response.Errors.length} objects`,
+ ),
+ }),
+ )
+ : Effect.succeed(response),
+ ),
+ Effect.when(() => objects.length > 0),
+ ),
getPresignedPutUrl: (
key: string,
args?: Omit<S3.PutObjectRequest, "Key" | "Bucket">,
@@ -442,6 +455,30 @@ export const createS3BucketAccess = Effect.gen(function* () {
),
),
),
+ copyPart: (
+ key: string,
+ uploadId: string,
+ partNumber: number,
+ args: Omit<
+ S3.UploadPartCopyCommandInput,
+ "Key" | "Bucket" | "UploadId" | "PartNumber"
+ >,
+ ) =>
+ wrapS3Promise(
+ provider.getInternal.pipe(
+ Effect.map((client) =>
+ client.send(
+ new S3.UploadPartCopyCommand({
+ Bucket: provider.bucket,
+ Key: key,
+ UploadId: uploadId,
+ PartNumber: partNumber,
+ ...args,
+ }),
+ ),
+ ),
+ ),
+ ),
abort: (
key: string,
uploadId: string,
diff --git a/packages/web-backend/src/Storage/index.ts b/packages/web-backend/src/Storage/index.ts
index 1cd68aa87..e9c17e6e8 100644
--- a/packages/web-backend/src/Storage/index.ts
+++ b/packages/web-backend/src/Storage/index.ts
@@ -8,7 +8,7 @@ import {
type User,
type Video,
} from "@cap/web-domain";
-import { Effect, Option } from "effect";
+import { Effect, Exit, Option } from "effect";
import { S3Buckets } from "../S3Buckets/index.ts";
import type { S3BucketAccess } from "../S3Buckets/S3BucketAccess.ts";
@@ -19,12 +19,14 @@ import {
findGoogleDriveFileByObjectKey,
GOOGLE_DRIVE_FOLDER_MIME_TYPE,
type GoogleDriveFile,
+ GoogleDriveRequestError,
type GoogleDriveTokenStore,
getGoogleDriveFileMetadata,
getGoogleDriveObjectResponse,
getGoogleDriveObjectText,
parseVideoIdFromObjectKey,
} from "./GoogleDrive.ts";
+import { resolveRecordingObjectKey } from "./recording-output.ts";
import { createStorageObjectToken } from "./SignedObject.ts";
import type { GoogleDriveIntegrationConfig } from "./StorageRepo.ts";
import { StorageRepo } from "./StorageRepo.ts";
@@ -37,6 +39,18 @@ type UploadTargetInput = {
};
type MultipartAccess = {
+ copyPart?: (
+ key: string,
+ uploadId: string,
+ partNumber: number,
+ args: Omit<
+ S3.UploadPartCopyCommandInput,
+ "Key" | "Bucket" | "UploadId" | "PartNumber"
+ >,
+ ) => Effect.Effect<
+ S3.UploadPartCopyCommandOutput,
+ StorageDomain.StorageError
+ >;
create: (
key: string,
args?: Omit<S3.CreateMultipartUploadCommandInput, "Bucket" | "Key">,
@@ -131,7 +145,10 @@ const requireDriveObject = (
onNone: () =>
Effect.fail(
new StorageDomain.StorageError({
- cause: new Error(`Storage object not found: ${key}`),
+ cause: new GoogleDriveRequestError(
+ 404,
+ `Storage object not found: ${key}`,
+ ),
}),
),
onSome: Effect.succeed,
@@ -163,6 +180,8 @@ const mapStorageError = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
);
const makeS3MultipartAccess = (s3: S3BucketAccess): MultipartAccess => ({
+ copyPart: (key, uploadId, partNumber, args) =>
+ mapStorageError(s3.multipart.copyPart(key, uploadId, partNumber, args)),
create: (
key: string,
args?: Omit<S3.CreateMultipartUploadCommandInput, "Bucket" | "Key">,
@@ -224,6 +243,163 @@ const makeGoogleDriveTokenStore = (
),
});
+const recordingCopyMetadata = (metadata: {
+ ContentLength?: number;
+ ETag?: string;
+}) => {
+ const fileSize = metadata.ContentLength;
+ const objectIdentity = metadata.ETag;
+ if (
+ fileSize === undefined ||
+ !Number.isSafeInteger(fileSize) ||
+ fileSize < 0 ||
+ !objectIdentity ||
+ !/^"[\x21\x23-\x7e]+"$/.test(objectIdentity)
+ ) {
+ return Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording copy requires a stable source identity and size",
+ ),
+ }),
+ );
+ }
+ return Effect.succeed({ fileSize, objectIdentity });
+};
+
+const copyS3ObjectForRecording = (
+ s3: S3BucketAccess,
+ source: string,
+ key: string,
+) =>
+ Effect.gen(function* () {
+ const prefix = `${s3.bucketName}/`;
+ if (!source.startsWith(prefix) || source.slice(prefix.length) === key) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording copy requires a distinct object in the same bucket",
+ ),
+ }),
+ );
+ }
+ const sourceKey = source.slice(prefix.length);
+ const sourceMetadata = yield* s3.headObject(sourceKey);
+ const { fileSize, objectIdentity } =
+ yield* recordingCopyMetadata(sourceMetadata);
+ const copySource = `${prefix}${sourceKey.split("/").map(encodeURIComponent).join("/")}`;
+ const singleCopyLimit = 5 * 1024 ** 3;
+ const copiedIdentity = yield* fileSize <= singleCopyLimit
+ ? s3
+ .copyObject(copySource, key, { CopySourceIfMatch: objectIdentity })
+ .pipe(Effect.map((result) => result.CopyObjectResult?.ETag))
+ : Effect.acquireUseRelease(
+ s3.multipart
+ .create(key, {
+ ContentType: sourceMetadata.ContentType,
+ CacheControl: sourceMetadata.CacheControl,
+ ContentDisposition: sourceMetadata.ContentDisposition,
+ ContentEncoding: sourceMetadata.ContentEncoding,
+ ContentLanguage: sourceMetadata.ContentLanguage,
+ Expires: sourceMetadata.Expires,
+ Metadata: sourceMetadata.Metadata,
+ })
+ .pipe(
+ Effect.flatMap((upload) =>
+ upload.UploadId
+ ? Effect.succeed(upload.UploadId)
+ : Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording multipart copy did not return an upload id",
+ ),
+ }),
+ ),
+ ),
+ ),
+ (uploadId) =>
+ Effect.gen(function* () {
+ const partSize = Math.max(
+ 128 * 1024 ** 2,
+ Math.ceil(fileSize / 10_000),
+ );
+ if (partSize > singleCopyLimit) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error("Recording exceeds multipart copy limits"),
+ }),
+ );
+ }
+ const parts = yield* Effect.forEach(
+ Array.from(
+ { length: Math.ceil(fileSize / partSize) },
+ (_, index) => index,
+ ),
+ (index) =>
+ Effect.gen(function* () {
+ const start = index * partSize;
+ const result = yield* s3.multipart.copyPart(
+ key,
+ uploadId,
+ index + 1,
+ {
+ CopySource: copySource,
+ CopySourceIfMatch: objectIdentity,
+ CopySourceRange: `bytes=${start}-${Math.min(fileSize, start + partSize) - 1}`,
+ },
+ );
+ const etag = result.CopyPartResult?.ETag;
+ if (!etag) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording multipart copy returned an incomplete part",
+ ),
+ }),
+ );
+ }
+ return { PartNumber: index + 1, ETag: etag };
+ }),
+ { concurrency: 3 },
+ );
+ const result = yield* s3.multipart.complete(key, uploadId, {
+ MultipartUpload: { Parts: parts },
+ IfNoneMatch: "*",
+ });
+ return result.ETag;
+ }),
+ (uploadId, exit) =>
+ Exit.isFailure(exit)
+ ? s3.multipart.abort(key, uploadId).pipe(
+ Effect.catchAll(() =>
+ Effect.logWarning("Recording multipart copy abort failed"),
+ ),
+ Effect.asVoid,
+ )
+ : Effect.void,
+ );
+ const [currentSource, currentDestination] = yield* Effect.all([
+ s3.headObject(sourceKey),
+ s3.headObject(key),
+ ]);
+ yield* recordingCopyMetadata(currentDestination);
+ if (
+ currentSource.ContentLength !== fileSize ||
+ currentSource.ETag !== objectIdentity ||
+ !copiedIdentity ||
+ currentDestination.ContentLength !== fileSize ||
+ currentDestination.ETag !== copiedIdentity
+ ) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording copy changed during transfer or failed readback",
+ ),
+ }),
+ );
+ }
+ }).pipe(mapStorageError);
+
const makeS3Access = (s3: S3BucketAccess) => ({
provider: "s3" as const,
bucketName: s3.bucketName,
@@ -273,6 +449,8 @@ const makeS3Access = (s3: S3BucketAccess) => ({
key: string,
args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,
) => mapStorageError(s3.copyObject(source, key, args)),
+ copyObjectForRecording: (source: string, key: string) =>
+ copyS3ObjectForRecording(s3, source, key),
deleteObject: (key: string) =>
mapStorageError(s3.deleteObject(key)).pipe(Effect.asVoid),
deleteObjects: (objects: Array<{ Key?: string }>) =>
@@ -336,6 +514,9 @@ const parseObjectKeyVideoId = (key: string) =>
Option.getOrNull,
);
+const isMissingDriveObject = (error: StorageDomain.StorageError) =>
+ error.cause instanceof GoogleDriveRequestError && error.cause.status === 404;
+
const makeGoogleDriveAccess = ({
repo,
integration,
@@ -361,7 +542,10 @@ const makeGoogleDriveAccess = ({
onNone: () =>
Effect.fail(
new StorageDomain.StorageError({
- cause: new Error(`Google Drive object not found: ${key}`),
+ cause: new GoogleDriveRequestError(
+ 404,
+ `Object not found: ${key}`,
+ ),
}),
),
onSome: (file) => {
@@ -398,10 +582,128 @@ const makeGoogleDriveAccess = ({
read: (fileId: string) => Effect.Effect<A, StorageDomain.StorageError>,
) =>
read(object.providerObjectId).pipe(
- Effect.catchTag("StorageError", () =>
- recoverDriveFileId(key, object).pipe(Effect.flatMap(read)),
+ Effect.catchTag("StorageError", (error) =>
+ isMissingDriveObject(error)
+ ? recoverDriveFileId(key, object).pipe(Effect.flatMap(read))
+ : Effect.fail(error),
+ ),
+ );
+ const copyObject = (
+ source: string,
+ key: string,
+ args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,
+ ) =>
+ getObjectRecord(parseSourceKey(source)).pipe(
+ Effect.flatMap((sourceObject) =>
+ copyGoogleDriveFile({
+ repo,
+ config,
+ sourceFileId: sourceObject.providerObjectId,
+ input: {
+ integrationId,
+ ownerId,
+ videoId: parseObjectKeyVideoId(key),
+ key,
+ contentType:
+ args?.ContentType ??
+ sourceObject.contentType ??
+ "application/octet-stream",
+ },
+ tokenStore,
+ }).pipe(mapStorageError),
),
);
+ const deleteObject = (key: string) =>
+ Effect.gen(function* () {
+ const stored = yield* mapStorageError(
+ repo.getObjectByKey(integrationId, key),
+ );
+ if (Option.isNone(stored)) return;
+ yield* deleteGoogleDriveFile(
+ config,
+ stored.value.providerObjectId,
+ tokenStore,
+ ).pipe(
+ Effect.catchAll((error) =>
+ isMissingDriveObject(error) ? Effect.void : Effect.fail(error),
+ ),
+ );
+ yield* mapStorageError(repo.deleteObjectByKey(integrationId, key));
+ });
+ const copyObjectForRecording = (source: string, key: string) =>
+ Effect.gen(function* () {
+ const sourceKey = parseSourceKey(source);
+ if (!source.startsWith("google-drive/") || sourceKey === key) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording copy requires a distinct object in the same storage integration",
+ ),
+ }),
+ );
+ }
+ const sourceObject = yield* getObjectRecord(sourceKey);
+ const before = yield* withRecoveredDriveFile(
+ sourceKey,
+ sourceObject,
+ (fileId) => getGoogleDriveFileMetadata(config, fileId, tokenStore),
+ );
+ const { fileSize } = yield* recordingCopyMetadata({
+ ContentLength: parseGoogleDriveContentLength(before) ?? undefined,
+ ETag:
+ before.id && before.version
+ ? `"${before.id}:${before.version}"`
+ : undefined,
+ });
+ yield* copyGoogleDriveFile({
+ repo,
+ config,
+ sourceFileId: before.id,
+ input: {
+ integrationId,
+ ownerId,
+ videoId: parseObjectKeyVideoId(key),
+ key,
+ contentType:
+ before.mimeType ??
+ sourceObject.contentType ??
+ "application/octet-stream",
+ },
+ tokenStore,
+ }).pipe(mapStorageError);
+ const currentSource = yield* getObjectRecord(sourceKey);
+ const destination = yield* getObjectRecord(key);
+ const [after, copied] = yield* Effect.all([
+ getGoogleDriveFileMetadata(config, before.id, tokenStore),
+ getGoogleDriveFileMetadata(
+ config,
+ destination.providerObjectId,
+ tokenStore,
+ ),
+ ]);
+ yield* recordingCopyMetadata({
+ ContentLength: parseGoogleDriveContentLength(copied) ?? undefined,
+ ETag:
+ copied.id && copied.version
+ ? `"${copied.id}:${copied.version}"`
+ : undefined,
+ });
+ if (
+ currentSource.providerObjectId !== before.id ||
+ after.id !== before.id ||
+ after.version !== before.version ||
+ parseGoogleDriveContentLength(after) !== fileSize ||
+ parseGoogleDriveContentLength(copied) !== fileSize
+ ) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Recording copy changed during transfer or failed readback",
+ ),
+ }),
+ );
+ }
+ });
const multipart: MultipartAccess = {
create: (
@@ -478,15 +780,22 @@ const makeGoogleDriveAccess = ({
signingArgs?: Parameters<S3BucketAccess["getInternalSignedObjectUrl"]>[1],
) => createDriveObjectUrl(key, signingArgs?.expiresIn ?? 7200),
getObject: (key: string) =>
- getObjectRecord(key).pipe(
- Effect.flatMap((object) =>
- withRecoveredDriveFile(key, object, (fileId) =>
- getGoogleDriveObjectText(config, fileId, tokenStore),
+ Effect.gen(function* () {
+ const object = yield* mapStorageError(
+ repo.getObjectByKey(integrationId, key),
+ );
+ if (Option.isNone(object)) return Option.none<string>();
+ return yield* withRecoveredDriveFile(key, object.value, (fileId) =>
+ getGoogleDriveObjectText(config, fileId, tokenStore),
+ ).pipe(
+ Effect.map(Option.some),
+ Effect.catchTag("StorageError", (error) =>
+ isMissingDriveObject(error)
+ ? Effect.succeed(Option.none<string>())
+ : Effect.fail(error),
),
- ),
- Effect.map(Option.some),
- Effect.catchTag("StorageError", () => Effect.succeed(Option.none())),
- ),
+ );
+ }),
listObjects: (input: {
prefix?: string;
maxKeys?: number;
@@ -592,77 +901,14 @@ const makeGoogleDriveAccess = ({
repo.markObjectComplete(integrationId, key, contentLength),
);
}),
- copyObject: (
- source: string,
- key: string,
- args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,
- ) =>
- getObjectRecord(parseSourceKey(source)).pipe(
- Effect.flatMap((sourceObject) =>
- copyGoogleDriveFile({
- repo,
- config,
- sourceFileId: sourceObject.providerObjectId,
- input: {
- integrationId,
- ownerId,
- videoId: parseVideoIdFromObjectKey(key).pipe(
- Option.map((id) => id as Video.VideoId),
- Option.getOrNull,
- ),
- key,
- contentType:
- (args?.ContentType as string | undefined) ??
- sourceObject.contentType ??
- "application/octet-stream",
- },
- tokenStore,
- }).pipe(mapStorageError),
- ),
- ),
- deleteObject: (key: string) =>
- getObjectRecord(key).pipe(
- Effect.flatMap((object) =>
- deleteGoogleDriveFile(
- config,
- object.providerObjectId,
- tokenStore,
- ).pipe(
- Effect.catchAll(() => Effect.void),
- Effect.flatMap(() =>
- mapStorageError(repo.deleteObjectByKey(integrationId, key)),
- ),
- ),
- ),
- Effect.catchAll(() => Effect.void),
- ),
+ copyObject,
+ copyObjectForRecording,
+ deleteObject,
deleteObjects: (objects: Array<{ Key?: string }>) =>
Effect.forEach(
objects,
- (object) =>
- object.Key
- ? getObjectRecord(object.Key).pipe(
- Effect.flatMap((record) =>
- deleteGoogleDriveFile(
- config,
- record.providerObjectId,
- tokenStore,
- ).pipe(
- Effect.catchAll(() => Effect.void),
- Effect.flatMap(() =>
- mapStorageError(
- repo.deleteObjectByKey(
- integrationId,
- object.Key as string,
- ),
- ),
- ),
- ),
- ),
- Effect.catchAll(() => Effect.void),
- )
- : Effect.void,
- { concurrency: 3 },
+ (object) => (object.Key ? deleteObject(object.Key) : Effect.void),
+ { concurrency: 3, discard: true },
),
getPresignedPutUrl: (
key: string,
@@ -744,6 +990,47 @@ const makeGoogleDriveAccess = ({
};
};
+function withPublishedRecordingOutput<
+ Access extends
+ | ReturnType<typeof makeS3Access>
+ | ReturnType<typeof makeGoogleDriveAccess>,
+>(video: Video.Video, access: Access): Access {
+ const resolve = (key: string) => resolveRecordingObjectKey(video, key);
+ const resolveCopySource = (source: string) => {
+ const prefix = `${access.bucketName}/`;
+ return source.startsWith(prefix)
+ ? `${prefix}${resolve(source.slice(prefix.length))}`
+ : source;
+ };
+ const shared = {
+ ...access,
+ getObject: (key: string) => access.getObject(resolve(key)),
+ headObject: (key: string) => access.headObject(resolve(key)),
+ getSignedObjectUrl: (
+ key: string,
+ args?: Parameters<S3BucketAccess["getSignedObjectUrl"]>[1],
+ ) => access.getSignedObjectUrl(resolve(key), args),
+ getInternalSignedObjectUrl: (
+ key: string,
+ args?: Parameters<S3BucketAccess["getInternalSignedObjectUrl"]>[1],
+ ) => access.getInternalSignedObjectUrl(resolve(key), args),
+ copyObject: (
+ source: string,
+ key: string,
+ args?: Omit<S3.CopyObjectCommandInput, "Bucket" | "CopySource" | "Key">,
+ ) => access.copyObject(resolveCopySource(source), key, args),
+ copyObjectForRecording: (source: string, key: string) =>
+ access.copyObjectForRecording(resolveCopySource(source), key),
+ };
+ if (access.provider === "googleDrive") {
+ return Object.assign({}, access, shared, {
+ getObjectResponse: (key: string, range?: string | null) =>
+ access.getObjectResponse(resolve(key), range),
+ });
+ }
+ return Object.assign({}, access, shared);
+}
+
type WritableStorageAccess = {
access:
| ReturnType<typeof makeS3Access>
@@ -874,16 +1161,28 @@ export class Storage extends Effect.Service<Storage>()("Storage", {
const getAccessForVideo = Effect.fn("Storage.getAccessForVideo")(function* (
video: Video.Video,
+ options?: { resolvePublishedOutput?: boolean },
) {
if (Option.isSome(video.storageIntegrationId)) {
const access = yield* getDriveAccess(video.storageIntegrationId.value);
- return [access, Option.none()] as const;
+ return [
+ options?.resolvePublishedOutput === false
+ ? access
+ : withPublishedRecordingOutput(video, access),
+ Option.none(),
+ ] as const;
}
const [s3, customBucket] = yield* mapStorageError(
s3Buckets.getBucketAccess(video.bucketId),
);
- return [makeS3Access(s3), customBucket] as const;
+ const access = makeS3Access(s3);
+ return [
+ options?.resolvePublishedOutput === false
+ ? access
+ : withPublishedRecordingOutput(video, access),
+ customBucket,
+ ] as const;
});
const createUploadTargetForUser = Effect.fn(
@@ -937,8 +1236,13 @@ export class Storage extends Effect.Service<Storage>()("Storage", {
Effect.flatMap(Storage, (storage) =>
storage.getOrganizationWritableAccess(organizationId),
);
- static getAccessForVideo = (video: Video.Video) =>
- Effect.flatMap(Storage, (storage) => storage.getAccessForVideo(video));
+ static getAccessForVideo = (
+ video: Video.Video,
+ options?: { resolvePublishedOutput?: boolean },
+ ) =>
+ Effect.flatMap(Storage, (storage) =>
+ storage.getAccessForVideo(video, options),
+ );
static createUploadTargetForUser = (
userId: User.UserId,
key: string,
diff --git a/packages/web-backend/src/Storage/recording-output.ts b/packages/web-backend/src/Storage/recording-output.ts
new file mode 100644
index 000000000..fb91708aa
--- /dev/null
+++ b/packages/web-backend/src/Storage/recording-output.ts
@@ -0,0 +1,58 @@
+import { Video } from "@cap/web-domain";
+
+type RecordingVideo = {
+ id: string;
+ ownerId: string;
+ source: {
+ type: string;
+ outputKey?: string;
+ thumbnailKey?: string;
+ previewKey?: string;
+ };
+};
+
+export function isInternalRecordingKey(key: string) {
+ return key.split("/")[2] === ".recording";
+}
+
+export function getPublishedRecordingOutputKey(video: RecordingVideo) {
+ return video.source.type === "desktopMP4"
+ ? Video.getRetainedRecordingOutputKey(
+ video.ownerId,
+ video.id,
+ video.source.outputKey,
+ )
+ : undefined;
+}
+
+export function resolveRecordingObjectKey(video: RecordingVideo, key: string) {
+ const prefix = `${video.ownerId}/${video.id}/`;
+ const asset =
+ key === `${prefix}screenshot/screen-capture.jpg`
+ ? video.source.thumbnailKey
+ : key === `${prefix}preview/animated-preview.gif`
+ ? video.source.previewKey
+ : undefined;
+ if (
+ video.source.type === "desktopMP4" &&
+ asset?.startsWith(`${prefix}.recording/outputs/`) &&
+ !asset.includes("..") &&
+ /^[a-zA-Z0-9_./-]+$/.test(asset)
+ ) {
+ return asset;
+ }
+ return key === `${video.ownerId}/${video.id}/result.mp4`
+ ? (getPublishedRecordingOutputKey(video) ?? key)
+ : key;
+}
+
+export function getPublishedRecordingCopyKeys(video: RecordingVideo) {
+ if (!getPublishedRecordingOutputKey(video)) return [];
+ const prefix = `${video.ownerId}/${video.id}/`;
+ return [
+ `${prefix}result.mp4`,
+ ...["screenshot/screen-capture.jpg", "preview/animated-preview.gif"]
+ .map((suffix) => `${prefix}${suffix}`)
+ .filter((key) => resolveRecordingObjectKey(video, key) !== key),
+ ];
+}
diff --git a/packages/web-backend/src/Videos/VideosRepo.ts b/packages/web-backend/src/Videos/VideosRepo.ts
index 17dec55dd..82fb453b8 100644
--- a/packages/web-backend/src/Videos/VideosRepo.ts
+++ b/packages/web-backend/src/Videos/VideosRepo.ts
@@ -1,6 +1,7 @@
+import { randomUUID } from "node:crypto";
import { nanoId } from "@cap/database/helpers";
import * as Db from "@cap/database/schema";
-import { Video } from "@cap/web-domain";
+import { type User, Video } from "@cap/web-domain";
import * as Dz from "drizzle-orm";
import type { MySqlInsertBase } from "drizzle-orm/mysql-core";
import { Effect, Option } from "effect";
@@ -45,9 +46,53 @@ export class VideosRepo extends Effect.Service<VideosRepo>()("VideosRepo", {
);
});
- const delete_ = (id: Video.VideoId) =>
+ const prepareDelete = (id: Video.VideoId, ownerId: User.UserId) =>
+ db.use((database) =>
+ database.transaction(async (tx) => {
+ const now = new Date();
+ const retired = {
+ generation: randomUUID(),
+ state: "source-blocked" as const,
+ attemptId: null,
+ leaseExpiresAt: null,
+ nextRetryAt: now,
+ workflowRunId: null,
+ remoteJobId: null,
+ errorCode: "video-deleting",
+ errorMessage: "Recording deletion is in progress.",
+ updatedAt: now,
+ };
+ await tx
+ .insert(Db.videoProcessingJobs)
+ .values({ videoId: id, ownerId, createdAt: now, ...retired })
+ .onDuplicateKeyUpdate({ set: retired });
+ const [video] = await tx
+ .select({ ownerId: Db.videos.ownerId })
+ .from(Db.videos)
+ .where(Dz.eq(Db.videos.id, id))
+ .for("update");
+ if (!video || video.ownerId !== ownerId) {
+ throw new Error("Video owner changed before deletion");
+ }
+ }),
+ );
+
+ const delete_ = (id: Video.VideoId, ownerId?: User.UserId) =>
db.use(async (db) => {
await db.transaction(async (db) => {
+ await db
+ .delete(Db.videoProcessingJobs)
+ .where(Dz.eq(Db.videoProcessingJobs.videoId, id));
+ if (ownerId) {
+ const [video] = await db
+ .select({ ownerId: Db.videos.ownerId })
+ .from(Db.videos)
+ .where(Dz.eq(Db.videos.id, id))
+ .for("update");
+ if (!video || video.ownerId !== ownerId) {
+ throw new Error("Video owner changed during deletion");
+ }
+ }
await Promise.all([
db.delete(Db.importedVideos).where(Dz.eq(Db.importedVideos.id, id)),
db.delete(Db.videos).where(Dz.eq(Db.videos.id, id)),
@@ -58,9 +103,9 @@ export class VideosRepo extends Effect.Service<VideosRepo>()("VideosRepo", {
});
});
- const create = (data: CreateVideoInput) =>
+ const create = (data: CreateVideoInput, options?: { id: Video.VideoId }) =>
Effect.gen(function* () {
- const id = Video.VideoId.make(nanoId());
+ const id = options?.id ?? Video.VideoId.make(nanoId());
yield* db.use((db) =>
db.transaction(async (db) => {
@@ -105,7 +150,7 @@ export class VideosRepo extends Effect.Service<VideosRepo>()("VideosRepo", {
return id;
});
- return { getById, delete: delete_, create };
+ return { getById, prepareDelete, delete: delete_, create };
}),
dependencies: [Database.Default],
}) {}
diff --git a/packages/web-backend/src/Videos/index.ts b/packages/web-backend/src/Videos/index.ts
index 2efc876e4..2ac200dd8 100644
--- a/packages/web-backend/src/Videos/index.ts
+++ b/packages/web-backend/src/Videos/index.ts
@@ -1,13 +1,24 @@
+import { nanoId } from "@cap/database/helpers";
import * as Db from "@cap/database/schema";
import { buildEnv, NODE_ENV, serverEnv } from "@cap/env";
import { dub } from "@cap/utils";
-import { CurrentUser, type Folder, Policy, Video } from "@cap/web-domain";
+import {
+ CurrentUser,
+ type Folder,
+ Policy,
+ Storage as StorageDomain,
+ Video,
+} from "@cap/web-domain";
import * as Dz from "drizzle-orm";
-import { Effect, Array as EffectArray, Exit, Option } from "effect";
+import { Effect, Exit, Option } from "effect";
import type { Schema } from "effect/Schema";
import { Database } from "../Database.ts";
import { Storage as StorageService } from "../Storage/index.ts";
+import {
+ getPublishedRecordingCopyKeys,
+ isInternalRecordingKey,
+} from "../Storage/recording-output.ts";
import { Tinybird } from "../Tinybird/index.ts";
import { VideosPolicy } from "./VideosPolicy.ts";
import type { CreateVideoInput as RepoCreateVideoInput } from "./VideosRepo.ts";
@@ -94,6 +105,22 @@ type RepoTranscriptionStatusValue = OptionValue<
RepoCreateVideoInput["transcriptionStatus"]
>;
+const nextObjectPage = (
+ page: { IsTruncated?: boolean; NextContinuationToken?: string },
+ seen: Set<string>,
+) => {
+ const next = page.NextContinuationToken;
+ if ((page.IsTruncated && !next) || (next && seen.has(next))) {
+ return Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error("Storage returned an invalid continuation token"),
+ }),
+ );
+ }
+ if (next) seen.add(next);
+ return Effect.succeed(next);
+};
+
export class Videos extends Effect.Service<Videos>()("Videos", {
effect: Effect.gen(function* () {
const db = yield* Database;
@@ -275,30 +302,48 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
* Delete a video. Will fail if the user does not have access.
*/
delete: Effect.fn("Videos.delete")(function* (videoId: Video.VideoId) {
- const maybeVideo = yield* repo.getById(videoId);
+ const maybeVideo = yield* repo
+ .getById(videoId)
+ .pipe(Policy.withPolicy(policy.isOwner(videoId)));
if (Option.isNone(maybeVideo))
return yield* Effect.fail(new Video.NotFoundError());
const [video] = maybeVideo.value;
const [bucket] = yield* storage.getAccessForVideo(video);
- yield* repo
- .delete(video.id)
- .pipe(Policy.withPolicy(policy.isOwner(video.id)));
-
- yield* Effect.log(`Deleted video ${video.id}`);
+ yield* repo.prepareDelete(video.id, video.ownerId);
const prefix = `${video.ownerId}/${video.id}/`;
- const listedObjects = yield* bucket.listObjects({ prefix });
-
- if (listedObjects.Contents) {
- yield* bucket.deleteObjects(
- listedObjects.Contents.map((content) => ({
- Key: content.Key,
- })),
- );
- }
+ let continuationToken: string | undefined;
+ const seenTokens = new Set<string>();
+ do {
+ const listedObjects = yield* bucket.listObjects({
+ prefix,
+ continuationToken,
+ });
+ continuationToken = yield* nextObjectPage(listedObjects, seenTokens);
+ if (listedObjects.Contents?.length) {
+ if (
+ listedObjects.Contents.some(
+ (content) => !content.Key?.startsWith(prefix),
+ )
+ ) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Storage returned an unexpected recording key",
+ ),
+ }),
+ );
+ }
+ yield* bucket.deleteObjects(
+ listedObjects.Contents.map((content) => ({ Key: content.Key })),
+ );
+ }
+ } while (continuationToken);
+ yield* repo.delete(video.id, video.ownerId);
+ yield* Effect.log(`Deleted video ${video.id}`);
}),
/*
@@ -317,33 +362,108 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
const [bucket] = yield* storage.getAccessForVideo(video);
- // Don't duplicate password or sharing data
- const newVideoId = yield* repo.create(video);
+ const publishedKeys = new Set(getPublishedRecordingCopyKeys(video));
+ const newVideoId = Video.VideoId.make(nanoId());
+ if (Option.isSome(yield* repo.getById(newVideoId))) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error("Duplicate video id is already in use"),
+ }),
+ );
+ }
const prefix = `${video.ownerId}/${video.id}/`;
const newPrefix = `${video.ownerId}/${newVideoId}/`;
-
- const allObjects = yield* bucket.listObjects({ prefix });
-
- if (allObjects.Contents)
- yield* Effect.all(
- EffectArray.filterMap(allObjects.Contents, (obj) =>
- Option.fromNullable(obj.Key).pipe(
- // Comment media belongs to the original video's comments,
- // which aren't duplicated — copying the bytes would leave
- // orphans no row points at.
- Option.filter((key) => !key.includes("/comments/")),
- Option.map((key) => {
- const newKey = key.replace(prefix, newPrefix);
- return bucket.copyObject(
- `${bucket.bucketName}/${obj.Key}`,
- newKey,
- );
- }),
+ const attemptedKeys: string[] = [];
+ let publicationAttempted = false;
+
+ const copyObject = (key: string) =>
+ Effect.gen(function* () {
+ const newKey = `${newPrefix}${key.slice(prefix.length)}`;
+ attemptedKeys.push(newKey);
+ yield* bucket.copyObjectForRecording(
+ `${bucket.bucketName}/${key}`,
+ newKey,
+ );
+ });
+ yield* Effect.gen(function* () {
+ for (const key of publishedKeys) yield* copyObject(key);
+ let continuationToken: string | undefined;
+ const seenTokens = new Set<string>();
+ do {
+ const allObjects = yield* bucket.listObjects({
+ prefix,
+ continuationToken,
+ });
+ continuationToken = yield* nextObjectPage(allObjects, seenTokens);
+ for (const object of allObjects.Contents ?? []) {
+ const key = object.Key;
+ if (!key?.startsWith(prefix)) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Storage returned an unexpected recording key",
+ ),
+ }),
+ );
+ }
+ if (
+ key.includes("/comments/") ||
+ isInternalRecordingKey(key) ||
+ publishedKeys.has(key) ||
+ (publishedKeys.size > 0 && key.startsWith(`${prefix}segments/`))
+ ) {
+ continue;
+ }
+ yield* copyObject(key);
+ }
+ } while (continuationToken);
+ publicationAttempted = true;
+ yield* repo.create(
+ {
+ ...video,
+ source:
+ publishedKeys.size > 0 ? { type: "desktopMP4" } : video.source,
+ metadata: Option.map(video.metadata, (metadata) => {
+ const copied = { ...metadata };
+ delete copied.desktopRecordingUpload;
+ return copied;
+ }),
+ },
+ { id: newVideoId },
+ );
+ }).pipe(
+ Effect.onError(() =>
+ Effect.gen(function* () {
+ if (
+ publicationAttempted &&
+ Option.isSome(yield* repo.getById(newVideoId))
+ ) {
+ return;
+ }
+ for (
+ let offset = 0;
+ offset < attemptedKeys.length;
+ offset += 1000
+ ) {
+ yield* bucket.deleteObjects(
+ attemptedKeys
+ .slice(offset, offset + 1000)
+ .map((Key) => ({ Key })),
+ );
+ }
+ }).pipe(
+ Effect.catchAllCause(() =>
+ Effect.logWarning(
+ "Recording duplicate cleanup did not finish",
+ {
+ videoId: newVideoId,
+ },
+ ),
),
),
- { concurrency: 1 },
- );
+ ),
+ );
}),
/*
@@ -365,24 +485,37 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
processingMessage: Db.videoUploads.processingMessage,
processingError: Db.videoUploads.processingError,
rawFileKey: Db.videoUploads.rawFileKey,
+ processingJobState: Db.videoProcessingJobs.state,
})
.from(Db.videoUploads)
+ .leftJoin(
+ Db.videoProcessingJobs,
+ Dz.eq(Db.videoProcessingJobs.videoId, Db.videoUploads.videoId),
+ )
.where(Dz.eq(Db.videoUploads.videoId, videoId)),
)
.pipe(Policy.withPublicPolicy(policy.canView(videoId)));
if (result == null) return Option.none();
+ const automaticRetry =
+ result.processingJobState === "committing" ||
+ result.processingJobState === "queued" ||
+ result.processingJobState === "processing" ||
+ result.processingJobState === "retry";
return Option.some(
new Video.UploadProgress({
uploaded: result.uploaded,
total: result.total,
startedAt: result.startedAt,
updatedAt: result.updatedAt,
- phase: result.phase,
+ phase: automaticRetry ? "processing" : result.phase,
processingProgress: result.processingProgress,
processingMessage: Option.fromNullable(result.processingMessage),
- processingError: Option.fromNullable(result.processingError),
+ processingError: automaticRetry
+ ? Option.none()
+ : Option.fromNullable(result.processingError),
hasRawFallback: result.rawFileKey != null,
+ automaticRetry,
}),
);
}),
diff --git a/packages/web-domain/src/Video.ts b/packages/web-domain/src/Video.ts
index 82cc67242..3c0138fcb 100644
--- a/packages/web-domain/src/Video.ts
+++ b/packages/web-domain/src/Video.ts
@@ -31,6 +31,9 @@ export class Video extends Schema.Class<Video>("Video")({
name: Schema.String,
public: Schema.Boolean,
source: Schema.Struct({
+ outputKey: Schema.optional(Schema.String),
+ thumbnailKey: Schema.optional(Schema.String),
+ previewKey: Schema.optional(Schema.String),
type: Schema.Literal(
"MediaConvert",
"local",
@@ -75,7 +78,11 @@ export class Video extends Schema.Class<Video>("Video")({
return new SegmentsSource({ videoId: self.id, ownerId: self.ownerId });
if (self.source.type === "desktopMP4" || self.source.type === "webMP4")
- return new Mp4Source({ videoId: self.id, ownerId: self.ownerId });
+ return new Mp4Source({
+ videoId: self.id,
+ ownerId: self.ownerId,
+ outputKey: self.source.outputKey,
+ });
}
}
@@ -100,6 +107,7 @@ export class UploadProgress extends Schema.Class<UploadProgress>(
processingMessage: Schema.OptionFromNullOr(Schema.String),
processingError: Schema.OptionFromNullOr(Schema.String),
hasRawFallback: Schema.Boolean,
+ automaticRetry: Schema.optional(Schema.Boolean),
}) {}
export const UploadProgressUpdateInput = Schema.Struct({
@@ -137,12 +145,35 @@ export class ImportSource extends Schema.Class<ImportSource>("ImportSource")({
id: Schema.String,
}) {}
+export function getRetainedRecordingOutputKey(
+ ownerId: string,
+ videoId: string,
+ key: string | undefined,
+) {
+ if (
+ !key?.startsWith(`${ownerId}/${videoId}/.recording/`) ||
+ !key.endsWith(".mp4") ||
+ key.includes("..") ||
+ !/^[a-zA-Z0-9_./-]+$/.test(key)
+ ) {
+ return undefined;
+ }
+ return key;
+}
+
export class Mp4Source extends Schema.TaggedClass<Mp4Source>()("Mp4Source", {
videoId: Schema.String,
ownerId: Schema.String,
+ outputKey: Schema.optional(Schema.String),
}) {
getFileKey() {
- return `${this.ownerId}/${this.videoId}/result.mp4`;
+ return (
+ getRetainedRecordingOutputKey(
+ this.ownerId,
+ this.videoId,
+ this.outputKey,
+ ) ?? `${this.ownerId}/${this.videoId}/result.mp4`
+ );
}
}