Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: fence video edit dispatch and completion by operation

Richie McIlroyb564f6c66057
diff --git a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
index c15c16203..59ac3893c 100644
--- a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
@@ -24,6 +24,7 @@ vi.mock("@cap/database/schema", () => ({
rawFileKey: "rawFileKey",
},
videoEdits: { table: "edits" },
+ videoProcessingJobs: { table: "jobs", videoId: "videoId" },
comments: { table: "comments" },
}));
vi.mock("drizzle-orm", () => ({ and: vi.fn(), eq: vi.fn() }));
@@ -76,6 +77,7 @@ import {
import { saveMetadataAndComplete } from "@/workflows/admin-reprocess-video";
import {
saveEditResultAndComplete,
+ startMediaServerEditJob,
verifyRenderedEditOutput,
} from "@/workflows/edit-video";
@@ -94,6 +96,12 @@ let video: {
};
let events: string[];
let updates: Record<string, unknown>[];
+const operation = {
+ token: "11111111-1111-4111-8111-111111111111",
+ startedAt: "2026-09-08T12:00:00.000Z",
+};
+const sourceKey = "user/video/edit-original.mp4";
+let upload: Record<string, unknown>;
const metadata = { duration: 5, width: 320, height: 180, fps: 30 };
const editSpec: VideoEditSpec = {
version: 1,
@@ -107,10 +115,15 @@ function createClient() {
return {
from: (table: { table: string }) => ({
where: () => {
- const rows = table.table === "comments" ? [] : [video];
+ const rows =
+ table.table === "comments"
+ ? []
+ : table.table === "uploads"
+ ? [upload]
+ : [video];
return Object.assign(Promise.resolve(rows), {
for: async () => {
- events.push("lock-video");
+ events.push(table.table === "jobs" ? "lock-job" : "lock-video");
return rows;
},
});
@@ -175,6 +188,11 @@ beforeEach(() => {
summary: "old summary",
},
};
+ upload = {
+ phase: "complete",
+ startedAt: new Date(operation.startedAt),
+ rawFileKey: sourceKey,
+ };
events = [];
updates = [];
mocks.db.mockReturnValue(createClient());
@@ -235,22 +253,42 @@ describe("edited recording publication", () => {
});
it("switches a completed edit to canonical output and retires old upload proof atomically", async () => {
+ video.metadata.editProcessing = {
+ ...operation,
+ ownerId: video.ownerId,
+ bucket: video.bucket,
+ storageIntegrationId: video.storageIntegrationId,
+ sourceKey,
+ source: JSON.stringify(video.source),
+ dispatch: "accepted",
+ };
await saveEditResultAndComplete(
"video",
"user/video/edit-original.mp4",
editSpec,
editSpec,
metadata,
+ operation,
);
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(
+ expect(events.indexOf("lock-job")).toBeLessThan(
events.indexOf("lock-video"),
);
expect(events.indexOf("lock-video")).toBeLessThan(
events.indexOf("update-videos"),
);
+ const before = events.length;
+ await saveEditResultAndComplete(
+ "video",
+ sourceKey,
+ editSpec,
+ editSpec,
+ metadata,
+ operation,
+ );
+ expect(events).toHaveLength(before);
});
it("checks a reprocessed canonical object before clearing its previous immutable publication", async () => {
@@ -326,3 +364,37 @@ describe("intentional administrator replacements", () => {
expect(mocks.retire).not.toHaveBeenCalled();
});
});
+
+describe("edit dispatch acceptance", () => {
+ it("retries only an explicit capacity rejection", async () => {
+ mocks.fetch.mockResolvedValue(
+ Response.json({ code: "SERVER_BUSY" }, { status: 503 }),
+ );
+ await expect(
+ startMediaServerEditJob("https://media.test", { videoId: "video" }),
+ ).resolves.toEqual({ status: "capacity" });
+ expect(mocks.fetch).toHaveBeenCalledOnce();
+ });
+ it("treats proxy failures as uncertain acceptance", async () => {
+ mocks.fetch.mockResolvedValue(
+ Response.json({ error: "Gateway timeout" }, { status: 504 }),
+ );
+ await expect(
+ startMediaServerEditJob("https://media.test", { videoId: "video" }),
+ ).rejects.toThrow("uncertain");
+ expect(mocks.fetch).toHaveBeenCalledOnce();
+ });
+ it("does not resend a request after a lost response", async () => {
+ mocks.fetch.mockRejectedValue(new Error("Connection reset"));
+ await expect(
+ startMediaServerEditJob("https://media.test", { videoId: "video" }),
+ ).rejects.toThrow("Connection reset");
+ expect(mocks.fetch).toHaveBeenCalledOnce();
+ });
+ it("accepts only responses containing the worker identity", async () => {
+ mocks.fetch.mockResolvedValue(Response.json({ jobId: "worker-1" }));
+ await expect(
+ startMediaServerEditJob("https://media.test", { videoId: "video" }),
+ ).resolves.toEqual({ status: "accepted", jobId: "worker-1" });
+ });
+});
diff --git a/apps/web/__tests__/unit/media-server-progress.test.ts b/apps/web/__tests__/unit/media-server-progress.test.ts
index 343d0d630..c55705cc9 100644
--- a/apps/web/__tests__/unit/media-server-progress.test.ts
+++ b/apps/web/__tests__/unit/media-server-progress.test.ts
@@ -179,7 +179,7 @@ function databaseFixture(initial: DesktopRecordingJob | null = fixture().job) {
};
const mutations: Mutation[] = [];
const rows = (table: unknown) => {
- if (table === mocks.tables.videos) return [structuredClone(video)];
+ if (table === mocks.tables.videos) return [{ ...video }];
if (table === mocks.tables.jobs)
return current ? [structuredClone(current)] : [];
if (table === mocks.tables.uploads) return [{ rawFileKey }];
diff --git a/apps/web/__tests__/unit/video-edit-operation.test.ts b/apps/web/__tests__/unit/video-edit-operation.test.ts
new file mode 100644
index 000000000..659c84007
--- /dev/null
+++ b/apps/web/__tests__/unit/video-edit-operation.test.ts
@@ -0,0 +1,242 @@
+import { User } from "@cap/web-domain";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ video: undefined as Record<string, unknown> | undefined,
+ upload: undefined as Record<string, unknown> | undefined,
+ writes: [] as { table: string; data: Record<string, unknown> }[],
+}));
+vi.mock("@cap/database/schema", () => ({
+ videos: { id: "video.id", name: "video" },
+ videoUploads: { videoId: "upload.videoId", name: "upload" },
+}));
+vi.mock("@cap/database", () => {
+ const tx = {
+ select: () => ({
+ from: (table: { name: "video" | "upload" }) => ({
+ where: () => {
+ const rows = mocks[table.name] ? [mocks[table.name]] : [];
+ return Object.assign(Promise.resolve(rows), {
+ for: async () => rows,
+ });
+ },
+ }),
+ }),
+ update: (table: { name: "video" | "upload" }) => ({
+ set: (data: Record<string, unknown>) => ({
+ where: async () => {
+ mocks.writes.push({ table: table.name, data });
+ Object.assign(mocks[table.name] ?? {}, data);
+ },
+ }),
+ }),
+ delete: (table: { name: "video" | "upload" }) => ({
+ where: async () => {
+ mocks.writes.push({ table: table.name, data: { deleted: true } });
+ mocks[table.name] = undefined;
+ },
+ }),
+ };
+ return {
+ db: () => ({
+ ...tx,
+ transaction: (run: (value: typeof tx) => unknown) => run(tx),
+ }),
+ };
+});
+
+import {
+ clearPendingEdit,
+ getEditProcessingState,
+ matchesEditOperation,
+} from "@/lib/video-edit-operation";
+import { applyEditProgress } from "@/lib/video-edit-progress";
+
+const operation = {
+ token: "11111111-1111-4111-8111-111111111111",
+ startedAt: "2026-09-08T12:00:00.000Z",
+};
+const sourceKey = "owner/video/source/original.mp4";
+const storage = {
+ ownerId: User.UserId.make("owner"),
+ bucket: null,
+ storageIntegrationId: null,
+};
+const source = { type: "webMP4" as const };
+const state = {
+ ...operation,
+ ...storage,
+ sourceKey,
+ source: JSON.stringify(source),
+ dispatch: "dispatching" as const,
+};
+const progress = {
+ videoId: "video",
+ jobId: "job-1",
+ phase: "processing",
+ progress: 25,
+};
+
+beforeEach(() => {
+ mocks.video = {
+ id: "video",
+ ...storage,
+ source,
+ metadata: { editProcessing: { ...state } },
+ duration: 10,
+ };
+ mocks.upload = {
+ rawFileKey: sourceKey,
+ startedAt: new Date(operation.startedAt),
+ phase: "processing",
+ };
+ mocks.writes = [];
+});
+
+describe("edit operation ownership", () => {
+ it("matches both the original source and the precise operation", () => {
+ const video = { ...storage, source, metadata: { editProcessing: state } };
+ const upload = {
+ rawFileKey: sourceKey,
+ startedAt: new Date(operation.startedAt),
+ };
+ expect(matchesEditOperation(video, upload, sourceKey, operation)).toBe(
+ true,
+ );
+ expect(
+ matchesEditOperation(video, upload, sourceKey, {
+ ...operation,
+ token: "stale",
+ }),
+ ).toBe(false);
+ expect(
+ matchesEditOperation(
+ video,
+ { ...upload, startedAt: new Date("2026-09-08T12:00:01Z") },
+ sourceKey,
+ operation,
+ ),
+ ).toBe(false);
+ expect(
+ matchesEditOperation(
+ { ...video, source: { type: "desktopMP4" } },
+ upload,
+ sourceKey,
+ operation,
+ ),
+ ).toBe(false);
+ });
+ it("accepts the first callback even when the dispatch response was lost", async () => {
+ expect(
+ await applyEditProgress(progress, operation.token, operation.startedAt),
+ ).toBe(true);
+ expect(mocks.video?.metadata).toMatchObject({
+ editProcessing: { dispatch: "accepted", jobId: "job-1" },
+ });
+ expect(mocks.upload?.processingProgress).toBe(25);
+ });
+ it.each(["stale-token", null])(
+ "ignores callbacks without the current token (%s)",
+ async (token) => {
+ expect(
+ await applyEditProgress(progress, token, operation.startedAt),
+ ).toBe(true);
+ expect(mocks.writes).toEqual([]);
+ },
+ );
+ it("ignores callbacks after recording storage is moved", async () => {
+ if (!mocks.video) throw new Error("Missing fixture");
+ mocks.video.bucket = "new-bucket";
+ await applyEditProgress(progress, operation.token, operation.startedAt);
+ expect(mocks.writes).toEqual([]);
+ });
+ it("rejects callbacks from a second worker", async () => {
+ await applyEditProgress(progress, operation.token, operation.startedAt);
+ mocks.writes = [];
+ await applyEditProgress(
+ { ...progress, jobId: "job-2", phase: "error" },
+ operation.token,
+ operation.startedAt,
+ );
+ expect(mocks.writes).toEqual([]);
+ });
+ it("keeps completion terminal when delayed progress or errors arrive", async () => {
+ await applyEditProgress(
+ {
+ ...progress,
+ phase: "complete",
+ metadata: { duration: 5, width: 1920, height: 1080, fps: 30 },
+ },
+ operation.token,
+ operation.startedAt,
+ );
+ mocks.writes = [];
+ await applyEditProgress(progress, operation.token, operation.startedAt);
+ await applyEditProgress(
+ { ...progress, phase: "error" },
+ operation.token,
+ operation.startedAt,
+ );
+ expect(mocks.writes).toEqual([]);
+ expect(mocks.upload?.phase).toBe("complete");
+ expect(mocks.video?.duration).toBe(5);
+ });
+ it("rejects invalid completion metadata without changing state", async () => {
+ await expect(
+ applyEditProgress(
+ {
+ ...progress,
+ phase: "complete",
+ metadata: {
+ duration: Number.NaN,
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ },
+ },
+ operation.token,
+ operation.startedAt,
+ ),
+ ).rejects.toThrow("valid media metadata");
+ expect(mocks.writes).toEqual([]);
+ });
+ it("preserves ambiguous dispatches during cleanup", async () => {
+ await clearPendingEdit("video", sourceKey, operation);
+ expect(mocks.writes).toEqual([]);
+ });
+ it("clears only an operation that has not dispatched", async () => {
+ if (!mocks.video) throw new Error("Missing fixture");
+ mocks.video.metadata = {
+ editProcessing: { ...state, dispatch: "pending" },
+ };
+ await clearPendingEdit("video", sourceKey, operation);
+ expect(mocks.upload).toBeUndefined();
+ expect(mocks.video.metadata).toEqual({});
+ });
+ it("never clears a newer operation", async () => {
+ await clearPendingEdit("video", sourceKey, {
+ ...operation,
+ token: "stale",
+ });
+ expect(mocks.writes).toEqual([]);
+ });
+ it("leaves legacy callbacks to the existing processor", async () => {
+ if (!mocks.video) throw new Error("Missing fixture");
+ mocks.video.metadata = {};
+ expect(await applyEditProgress(progress, null, null)).toBe(false);
+ expect(mocks.writes).toEqual([]);
+ });
+ it("ignores callbacks from an edit after its lock was released", async () => {
+ if (!mocks.video) throw new Error("Missing fixture");
+ mocks.video.metadata = {};
+ expect(
+ await applyEditProgress(progress, operation.token, operation.startedAt),
+ ).toBe(true);
+ expect(mocks.writes).toEqual([]);
+ });
+ it("rejects malformed persisted identities", () => {
+ expect(
+ getEditProcessingState({ editProcessing: { ...state, token: "bad" } }),
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/web/actions/videos/save-edits.ts b/apps/web/actions/videos/save-edits.ts
index 18ed8d436..41d4b320f 100644
--- a/apps/web/actions/videos/save-edits.ts
+++ b/apps/web/actions/videos/save-edits.ts
@@ -1,5 +1,6 @@
"use server";
+import { randomUUID } from "node:crypto";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { videoEdits, videos, videoUploads } from "@cap/database/schema";
@@ -12,6 +13,10 @@ import { Effect } from "effect";
import { revalidatePath } from "next/cache";
import { start } from "workflow/api";
import { runPromise } from "@/lib/server";
+import {
+ clearPendingEdit,
+ type EditOperation,
+} from "@/lib/video-edit-operation";
import { getEditSourceKey } from "@/lib/video-edit-processing";
import {
areEditSpecsEquivalent,
@@ -76,16 +81,57 @@ async function ensureOriginalSourceCopy(
}
async function markEditProcessing({
- videoId,
+ video,
sourceKey,
+ previousSpec,
}: {
- videoId: Video.VideoId;
+ video: typeof videos.$inferSelect;
sourceKey: string;
-}) {
- await db()
- .insert(videoUploads)
- .values({
- videoId,
+ previousSpec: VideoEditSpec;
+}): Promise<EditOperation> {
+ const startedAt = new Date(Math.floor(Date.now() / 1000) * 1000);
+ const operation = { token: randomUUID(), startedAt: startedAt.toISOString() };
+ await db().transaction(async (tx) => {
+ const [current] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, video.id))
+ .for("update");
+ if (
+ !current ||
+ current.ownerId !== video.ownerId ||
+ current.bucket !== video.bucket ||
+ current.storageIntegrationId !== video.storageIntegrationId ||
+ JSON.stringify(current.source) !== JSON.stringify(video.source)
+ ) {
+ throw new Error("Video changed before the edit could start");
+ }
+ const [upload] = await tx
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, video.id))
+ .for("update");
+ if (upload || (current.metadata && "editProcessing" in current.metadata)) {
+ throw new Error("Video is already uploading or processing");
+ }
+ const [currentEdit] = await tx
+ .select()
+ .from(videoEdits)
+ .where(eq(videoEdits.videoId, video.id))
+ .for("update");
+ if (
+ !areEditSpecsEquivalent(
+ currentEdit?.editSpec ??
+ createIdentityEditSpec(
+ current.duration ?? previousSpec.sourceDuration,
+ ),
+ previousSpec,
+ )
+ ) {
+ throw new Error("Video edits changed before this edit could start");
+ }
+ await tx.insert(videoUploads).values({
+ videoId: video.id,
uploaded: 0,
total: 0,
mode: "singlepart",
@@ -94,21 +140,24 @@ async function markEditProcessing({
processingMessage: "Starting video edit...",
processingError: null,
rawFileKey: sourceKey,
- updatedAt: new Date(),
- })
- .onDuplicateKeyUpdate({
- set: {
- uploaded: 0,
- total: 0,
- mode: "singlepart",
- phase: "processing",
- processingProgress: 0,
- processingMessage: "Starting video edit...",
- processingError: null,
- rawFileKey: sourceKey,
- updatedAt: new Date(),
- },
+ startedAt,
+ updatedAt: startedAt,
});
+ const metadata = {
+ ...(current.metadata ?? {}),
+ editProcessing: {
+ ...operation,
+ sourceKey,
+ ownerId: current.ownerId,
+ bucket: current.bucket,
+ storageIntegrationId: current.storageIntegrationId,
+ source: JSON.stringify(current.source),
+ dispatch: "pending" as const,
+ },
+ };
+ await tx.update(videos).set({ metadata }).where(eq(videos.id, video.id));
+ });
+ return operation;
}
async function loadEditableVideo(videoId: Video.VideoId) {
@@ -181,13 +230,20 @@ export async function saveVideoEdits(
return { success: true, skipped: true };
}
- const sourceKey = await ensureOriginalSourceCopy(
- video,
- existingEdit?.sourceKey,
- );
+ const sourceKey =
+ existingEdit?.sourceKey ?? getEditSourceKey(video.ownerId, video.id);
const aiGenerationEnabled = await isAiGenerationEnabled(user);
-
- await markEditProcessing({ videoId, sourceKey });
+ const operation = await markEditProcessing({
+ video,
+ sourceKey,
+ previousSpec,
+ });
+ try {
+ await ensureOriginalSourceCopy(video, sourceKey);
+ } catch (error) {
+ await clearPendingEdit(videoId, sourceKey, operation);
+ throw error;
+ }
try {
await start(editVideoWorkflow, [
@@ -199,10 +255,10 @@ export async function saveVideoEdits(
editSpec: normalizedEditSpec,
keepRanges: normalizedEditSpec.keepRanges,
aiGenerationEnabled,
+ operation,
},
]);
} catch (error) {
- await db().delete(videoUploads).where(eq(videoUploads.videoId, videoId));
throw error instanceof Error
? error
: new Error("Video edit could not start");
@@ -248,7 +304,11 @@ export async function restoreVideoToOriginal(videoId: Video.VideoId) {
const aiGenerationEnabled = await isAiGenerationEnabled(user);
- await markEditProcessing({ videoId, sourceKey });
+ const operation = await markEditProcessing({
+ video,
+ sourceKey,
+ previousSpec,
+ });
try {
await start(editVideoWorkflow, [
@@ -260,10 +320,10 @@ export async function restoreVideoToOriginal(videoId: Video.VideoId) {
editSpec: restoredSpec,
keepRanges: restoredSpec.keepRanges,
aiGenerationEnabled,
+ operation,
},
]);
} catch (error) {
- await db().delete(videoUploads).where(eq(videoUploads.videoId, videoId));
throw error instanceof Error
? error
: new Error("Video restore could not start");
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 106f468ce..8f4036bb6 100644
--- a/apps/web/app/api/webhooks/media-server/progress/route.ts
+++ b/apps/web/app/api/webhooks/media-server/progress/route.ts
@@ -19,6 +19,7 @@ import {
shouldQueueTranscriptionAfterMediaComplete,
} from "@/lib/queue-video-transcription";
import { isEditSourceKey } from "@/lib/video-edit-processing";
+import { applyEditProgress } from "@/lib/video-edit-progress";
interface ProgressWebhookPayload {
manifestSha256?: string;
@@ -101,6 +102,15 @@ export async function POST(request: NextRequest) {
}
const payload: ProgressWebhookPayload = await request.json();
+ if (
+ await applyEditProgress(
+ payload,
+ request.nextUrl.searchParams.get("editOperation"),
+ request.nextUrl.searchParams.get("editStartedAt"),
+ )
+ ) {
+ return NextResponse.json({ success: true });
+ }
const recordingProgress = await applyDesktopRecordingProgress(payload);
if (recordingProgress.handled) {
if (recordingProgress.published) {
diff --git a/apps/web/lib/video-edit-operation.ts b/apps/web/lib/video-edit-operation.ts
new file mode 100644
index 000000000..c844987b1
--- /dev/null
+++ b/apps/web/lib/video-edit-operation.ts
@@ -0,0 +1,165 @@
+import { db } from "@cap/database";
+import {
+ videoProcessingJobs,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
+import type { VideoMetadata } from "@cap/database/types";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { FatalError } from "workflow";
+import { z } from "zod";
+
+export interface EditOperation {
+ token: string;
+ startedAt: string;
+}
+
+const stateSchema = z.object({
+ token: z.string().uuid(),
+ startedAt: z.string().datetime(),
+ ownerId: z.string(),
+ bucket: z.string().nullable(),
+ storageIntegrationId: z.string().nullable(),
+ sourceKey: z.string(),
+ source: z.string(),
+ dispatch: z.enum(["pending", "dispatching", "accepted"]),
+ jobId: z.string().optional(),
+ resultCommitted: z.boolean().optional(),
+});
+export type EditProcessingState = z.infer<typeof stateSchema>;
+type Transaction = Parameters<
+ Parameters<ReturnType<typeof db>["transaction"]>[0]
+>[0];
+
+export function getEditProcessingState(metadata: VideoMetadata | null) {
+ if (
+ !metadata ||
+ typeof metadata !== "object" ||
+ !("editProcessing" in metadata)
+ )
+ return undefined;
+ const parsed = stateSchema.safeParse(metadata.editProcessing);
+ return parsed.success ? parsed.data : undefined;
+}
+
+export function withoutEditProcessing(metadata: VideoMetadata | null) {
+ const next = { ...metadata };
+ delete next.editProcessing;
+ return next;
+}
+
+export function matchesEditOperation(
+ video: Pick<
+ typeof videos.$inferSelect,
+ "metadata" | "source" | "ownerId" | "bucket" | "storageIntegrationId"
+ >,
+ upload:
+ | Pick<typeof videoUploads.$inferSelect, "rawFileKey" | "startedAt">
+ | undefined,
+ sourceKey: string,
+ operation: EditOperation,
+) {
+ const state = getEditProcessingState(video.metadata);
+ return Boolean(
+ state &&
+ upload &&
+ state.token === operation.token &&
+ state.startedAt === operation.startedAt &&
+ state.ownerId === video.ownerId &&
+ state.bucket === video.bucket &&
+ state.storageIntegrationId === video.storageIntegrationId &&
+ state.sourceKey === sourceKey &&
+ state.source === JSON.stringify(video.source) &&
+ upload.rawFileKey === sourceKey &&
+ upload.startedAt.toISOString() === operation.startedAt,
+ );
+}
+
+export async function withEditOperation<T>(
+ videoId: string,
+ sourceKey: string,
+ operation: EditOperation,
+ run: (
+ tx: Transaction,
+ video: typeof videos.$inferSelect,
+ upload: typeof videoUploads.$inferSelect,
+ state: EditProcessingState,
+ ) => Promise<T>,
+ lockRecordingJob = false,
+): Promise<T> {
+ return db().transaction(async (tx) => {
+ if (lockRecordingJob) {
+ await tx
+ .select({ videoId: videoProcessingJobs.videoId })
+ .from(videoProcessingJobs)
+ .where(eq(videoProcessingJobs.videoId, videoId as Video.VideoId))
+ .for("update");
+ }
+ const [video] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId as Video.VideoId))
+ .for("update");
+ const [upload] = await tx
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId))
+ .for("update");
+ const state = getEditProcessingState(video?.metadata ?? null);
+ if (
+ !video ||
+ !upload ||
+ !state ||
+ !matchesEditOperation(video, upload, sourceKey, operation)
+ ) {
+ throw new FatalError("Edit operation has been replaced");
+ }
+ return run(tx, video, upload, state);
+ });
+}
+
+export function getCompletedEdit(metadata: VideoMetadata | null) {
+ if (
+ !metadata ||
+ typeof metadata !== "object" ||
+ !("completedVideoEdit" in metadata)
+ )
+ return undefined;
+ const parsed = z
+ .object({
+ token: z.string(),
+ startedAt: z.string(),
+ transcriptRemapped: z.boolean(),
+ })
+ .safeParse(metadata.completedVideoEdit);
+ return parsed.success ? parsed.data : undefined;
+}
+
+export async function clearPendingEdit(
+ videoId: string,
+ sourceKey: string,
+ operation: EditOperation,
+): Promise<void> {
+ await db().transaction(async (tx) => {
+ const [video] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId as Video.VideoId))
+ .for("update");
+ const [upload] = await tx
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId))
+ .for("update");
+ if (!video || !matchesEditOperation(video, upload, sourceKey, operation))
+ return;
+ const state = getEditProcessingState(video.metadata);
+ if (state?.dispatch !== "pending") return;
+ await tx
+ .update(videos)
+ .set({ metadata: withoutEditProcessing(video.metadata) })
+ .where(eq(videos.id, video.id));
+ await tx.delete(videoUploads).where(eq(videoUploads.videoId, video.id));
+ });
+}
diff --git a/apps/web/lib/video-edit-progress.ts b/apps/web/lib/video-edit-progress.ts
new file mode 100644
index 000000000..d35756dd6
--- /dev/null
+++ b/apps/web/lib/video-edit-progress.ts
@@ -0,0 +1,103 @@
+import { db } from "@cap/database";
+import { videos, videoUploads } from "@cap/database/schema";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import {
+ getEditProcessingState,
+ matchesEditOperation,
+} from "./video-edit-operation";
+
+interface EditProgress {
+ videoId: string;
+ jobId: string;
+ phase: string;
+ progress: number;
+ message?: string;
+ error?: string;
+ metadata?: { duration: number; width: number; height: number; fps: number };
+}
+
+export async function applyEditProgress(
+ payload: EditProgress,
+ token: string | null,
+ startedAt: string | null,
+) {
+ return db().transaction(async (tx) => {
+ const [video] = await tx
+ .select()
+ .from(videos)
+ .where(eq(videos.id, payload.videoId as Video.VideoId))
+ .for("update");
+ const state = getEditProcessingState(video?.metadata ?? null);
+ if (!token && !state) return false;
+ if (!video || !state || !token || !startedAt) return true;
+ const [upload] = await tx
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, video.id))
+ .for("update");
+ if (
+ !upload ||
+ !matchesEditOperation(video, upload, state.sourceKey, {
+ token,
+ startedAt,
+ }) ||
+ state.dispatch === "pending" ||
+ (state.jobId && state.jobId !== payload.jobId)
+ )
+ return true;
+ if (upload.phase === "complete" || upload.phase === "error") return true;
+ const complete = payload.phase === "complete";
+ const failed = payload.phase === "error" || payload.phase === "cancelled";
+ if (
+ complete &&
+ (!payload.metadata ||
+ ![
+ payload.metadata.duration,
+ payload.metadata.width,
+ payload.metadata.height,
+ payload.metadata.fps,
+ ].every((value) => Number.isFinite(value) && value > 0))
+ ) {
+ throw new Error("Edit completion is missing valid media metadata");
+ }
+ await tx
+ .update(videos)
+ .set({
+ metadata: {
+ ...video.metadata,
+ editProcessing: {
+ ...state,
+ dispatch: "accepted",
+ jobId: payload.jobId,
+ },
+ },
+ ...(complete && payload.metadata
+ ? {
+ duration: payload.metadata.duration,
+ width: payload.metadata.width,
+ height: payload.metadata.height,
+ fps: payload.metadata.fps,
+ }
+ : {}),
+ })
+ .where(eq(videos.id, video.id));
+ await tx
+ .update(videoUploads)
+ .set({
+ phase: complete ? "complete" : failed ? "error" : "processing",
+ processingProgress: complete
+ ? 100
+ : Number.isFinite(payload.progress)
+ ? Math.round(Math.max(0, Math.min(100, payload.progress)))
+ : 0,
+ processingMessage: payload.message,
+ processingError: failed
+ ? payload.error || payload.message || "Video edit failed"
+ : null,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, video.id));
+ return true;
+ });
+}
diff --git a/apps/web/workflows/edit-video.ts b/apps/web/workflows/edit-video.ts
index 37a1df012..28112c471 100644
--- a/apps/web/workflows/edit-video.ts
+++ b/apps/web/workflows/edit-video.ts
@@ -19,7 +19,7 @@ import { serverEnv } from "@cap/env";
import { AwsCredentials } from "@cap/web-backend/src/Aws";
import { Storage } from "@cap/web-backend/src/Storage/index";
import { Video } from "@cap/web-domain";
-import { and, eq } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { FatalError, sleep } from "workflow";
import { retireDesktopRecordingJobForOutputReplacement } from "@/lib/desktop-recording-jobs";
@@ -32,11 +32,15 @@ import {
} from "@/lib/edit-transcript";
import { decryptEditTranscriptObject } from "@/lib/edit-transcript-storage";
import { startAiGeneration } from "@/lib/generate-ai";
-import {
- createMediaServerCapacityError,
- isMediaServerCapacityError,
-} from "@/lib/media-server-backpressure";
import { transcribeVideo } from "@/lib/transcribe";
+import {
+ clearPendingEdit,
+ type EditOperation,
+ getCompletedEdit,
+ matchesEditOperation,
+ withEditOperation,
+ withoutEditProcessing,
+} from "@/lib/video-edit-operation";
import {
getEditSpecOutputDuration,
remapCurrentOutputTimeThroughEdit,
@@ -52,6 +56,7 @@ interface EditVideoWorkflowPayload {
editSpec: VideoEditSpec;
keepRanges: VideoEditRange[];
aiGenerationEnabled: boolean;
+ operation: EditOperation;
}
interface VideoEditRenderResult {
@@ -63,10 +68,8 @@ interface VideoEditRenderResult {
};
}
-const MEDIA_SERVER_START_MAX_ATTEMPTS = 2;
-const MEDIA_SERVER_START_RETRY_BASE_MS = 250;
const MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS = 720;
-const MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS = 5000;
+const MEDIA_SERVER_DISPATCH_TIMEOUT_MS = 30_000;
const MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS = 3 * 60 * 60;
const MEDIA_SERVER_PRESIGNED_PUT_EXPIRES_SECONDS = 3 * 60 * 60;
const MEDIA_SERVER_OUTPUT_VERIFICATION_MAX_ATTEMPTS = 4;
@@ -110,23 +113,38 @@ export async function editVideoWorkflow(
previousSpec,
editSpec,
aiGenerationEnabled,
+ operation,
} = payload;
try {
- await validateEditRequest(videoId, sourceKey);
- let result: VideoEditRenderResult;
+ await validateEditRequest(videoId, sourceKey, operation);
let capacityRetryCount = 0;
while (true) {
- try {
- result = await renderVideoEditOnMediaServer(payload);
- break;
- } catch (error) {
- if (!isMediaServerCapacityError(error)) throw error;
- await markEditWaitingForCapacity(videoId);
+ const dispatch = await renderVideoEditOnMediaServer(payload);
+ if (dispatch.status === "capacity") {
+ await markEditWaitingForCapacity(videoId, sourceKey, operation);
await sleep(`${Math.min(120, 15 + capacityRetryCount * 15)}s`);
capacityRetryCount++;
+ continue;
}
+ if (dispatch.status === "rejected")
+ throw new FatalError(dispatch.message);
+ break;
+ }
+ let result: VideoEditRenderResult | undefined;
+ for (
+ let attempt = 0;
+ attempt < MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS;
+ attempt++
+ ) {
+ await sleep("5s");
+ result = await readEditCompletion(videoId, sourceKey, operation);
+ if (result) break;
}
+ if (!result)
+ throw new FatalError(
+ "Video edit timed out; its worker must be reconciled before another edit can start",
+ );
await verifyRenderedEditOutput(videoId, userId, editSpec, result.metadata);
await invalidateEditedVideoCache(videoId, editSpec);
const { transcriptRemapped } = await saveEditResultAndComplete(
@@ -135,6 +153,7 @@ export async function editVideoWorkflow(
previousSpec,
editSpec,
result.metadata,
+ operation,
);
if (transcriptRemapped) {
@@ -154,7 +173,8 @@ export async function editVideoWorkflow(
return result;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
- await clearEditProcessingState(videoId, sourceKey, previousSpec);
+ if (operation)
+ await clearEditProcessingState(videoId, sourceKey, operation);
throw new FatalError(errorMessage);
}
}
@@ -162,12 +182,20 @@ export async function editVideoWorkflow(
async function validateEditRequest(
videoId: string,
sourceKey: string,
+ operation: EditOperation,
): Promise<void> {
"use step";
if (!serverEnv().MEDIA_SERVER_URL) {
throw new FatalError("MEDIA_SERVER_URL is not configured");
}
+ if (
+ !operation ||
+ !operation.token ||
+ !Number.isFinite(Date.parse(operation.startedAt))
+ ) {
+ throw new FatalError("Edit operation identity is missing");
+ }
const [video] = await db()
.select()
@@ -187,8 +215,8 @@ async function validateEditRequest(
throw new FatalError("Edit render does not exist");
}
- if (upload.rawFileKey !== sourceKey) {
- throw new FatalError("Edit source key does not match");
+ if (!matchesEditOperation(video, upload, sourceKey, operation)) {
+ throw new FatalError("Edit operation has been replaced");
}
if (upload.phase !== "processing") {
@@ -196,101 +224,55 @@ async function validateEditRequest(
}
}
-async function startMediaServerEditJob(
+type EditDispatch =
+ | { status: "accepted" | "capacity" }
+ | { status: "rejected"; message: string };
+
+export async function startMediaServerEditJob(
mediaServerUrl: string,
- body: {
- videoId: string;
- userId: string;
- sourceUrl: string;
- outputPresignedUrl: string;
- outputVerificationUrl?: string;
- thumbnailPresignedUrl: string;
- previewGifPresignedUrl: string;
- webhookUrl: string;
- webhookSecret?: string;
- keepRanges: VideoEditRange[];
- },
-): Promise<string> {
- for (let attempt = 0; attempt < MEDIA_SERVER_START_MAX_ATTEMPTS; attempt++) {
- const headers: Record<string, string> = {
+ body: { videoId: string; webhookSecret?: string; [key: string]: unknown },
+): Promise<EditDispatch & { jobId?: string }> {
+ const response = await fetch(`${mediaServerUrl}/video/edit`, {
+ method: "POST",
+ headers: {
"Content-Type": "application/json",
+ ...(body.webhookSecret
+ ? { "x-media-server-secret": body.webhookSecret }
+ : {}),
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(MEDIA_SERVER_DISPATCH_TIMEOUT_MS),
+ });
+ const data: unknown = await response.json();
+ const value = data && typeof data === "object" ? data : {};
+ if (response.ok && "jobId" in value && typeof value.jobId === "string") {
+ return { status: "accepted", jobId: value.jobId };
+ }
+ if (
+ response.status === 503 &&
+ "code" in value &&
+ value.code === "SERVER_BUSY"
+ )
+ return { status: "capacity" };
+ if (
+ response.status === 400 &&
+ "code" in value &&
+ value.code === "INVALID_REQUEST"
+ ) {
+ return {
+ status: "rejected",
+ message: "The media server rejected the edit request",
};
- if (body.webhookSecret) {
- headers["x-media-server-secret"] = body.webhookSecret;
- }
-
- const response = await fetch(`${mediaServerUrl}/video/edit`, {
- method: "POST",
- headers,
- body: JSON.stringify(body),
- });
-
- if (response.ok) {
- const { jobId } = (await response.json()) as { jobId: string };
- return jobId;
- }
-
- const errorData = (await response.json().catch(() => ({}))) as {
- error?: string;
- code?: string;
- details?: string;
- instanceId?: string;
- pid?: number;
- activeVideoProcesses?: number;
- maxConcurrentVideoProcesses?: number;
- jobCount?: number;
- };
- const baseErrorMessage =
- errorData.error || errorData.details || "Video edit failed to start";
- const busyDiagnostics =
- errorData.code === "SERVER_BUSY"
- ? [
- errorData.instanceId ? `instance=${errorData.instanceId}` : null,
- typeof errorData.pid === "number" ? `pid=${errorData.pid}` : null,
- typeof errorData.activeVideoProcesses === "number" &&
- typeof errorData.maxConcurrentVideoProcesses === "number"
- ? `active=${errorData.activeVideoProcesses}/${errorData.maxConcurrentVideoProcesses}`
- : null,
- typeof errorData.jobCount === "number"
- ? `jobCount=${errorData.jobCount}`
- : null,
- ]
- .filter(Boolean)
- .join(", ")
- : "";
- const errorMessage = busyDiagnostics
- ? `${baseErrorMessage} (${busyDiagnostics})`
- : baseErrorMessage;
- const shouldRetry =
- response.status === 503 &&
- (errorData.code === "SERVER_BUSY" ||
- errorMessage.includes("Server is busy"));
-
- if (shouldRetry && attempt < MEDIA_SERVER_START_MAX_ATTEMPTS - 1) {
- await waitForRetry(MEDIA_SERVER_START_RETRY_BASE_MS * 2 ** attempt);
- continue;
- }
-
- if (shouldRetry) {
- throw createMediaServerCapacityError({
- response,
- message: errorMessage,
- videoId: body.videoId,
- });
- }
-
- throw new Error(errorMessage);
}
-
- throw new Error("Video edit failed to start");
+ throw new Error("The media server acceptance is uncertain");
}
async function renderVideoEditOnMediaServer(
payload: EditVideoWorkflowPayload,
-): Promise<VideoEditRenderResult> {
+): Promise<EditDispatch> {
"use step";
- const { videoId, userId, sourceKey, keepRanges } = payload;
+ const { videoId, userId, sourceKey, keepRanges, operation } = payload;
const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
const webhookBaseUrl =
serverEnv().MEDIA_SERVER_WEBHOOK_URL || serverEnv().WEB_URL;
@@ -298,14 +280,14 @@ async function renderVideoEditOnMediaServer(
throw new FatalError("MEDIA_SERVER_URL is not configured");
}
- const [video] = await db()
- .select()
- .from(videos)
- .where(eq(videos.id, Video.VideoId.make(videoId)));
-
- if (!video) {
- throw new FatalError("Video does not exist");
- }
+ const current = await withEditOperation(
+ videoId,
+ sourceKey,
+ operation,
+ async (_tx, video, _upload, state) => ({ video, dispatch: state.dispatch }),
+ );
+ if (current.dispatch !== "pending") return { status: "accepted" };
+ const video = current.video;
const [bucket] = await Storage.getAccessForVideo(
decodeStorageVideo(video),
@@ -362,47 +344,91 @@ async function renderVideoEditOnMediaServer(
)
.pipe(runWorkflowPromise);
- const webhookUrl = `${webhookBaseUrl}/api/webhooks/media-server/progress?retryable=true`;
+ const webhookUrl = new URL(
+ "/api/webhooks/media-server/progress",
+ webhookBaseUrl,
+ );
+ webhookUrl.searchParams.set("editOperation", operation.token);
+ webhookUrl.searchParams.set("editStartedAt", operation.startedAt);
const webhookSecret = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;
-
- await db()
- .update(videoUploads)
- .set({
- phase: "processing",
- processingProgress: 0,
- processingMessage: "Starting video edit...",
- processingError: null,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, videoId as Video.VideoId));
-
- await startMediaServerEditJob(mediaServerUrl, {
+ const claimed = await withEditOperation(
videoId,
- userId,
- sourceUrl,
- outputPresignedUrl,
- outputVerificationUrl,
- thumbnailPresignedUrl,
- previewGifPresignedUrl,
- webhookUrl,
- webhookSecret: webhookSecret || undefined,
- keepRanges,
- });
-
- return await waitForEditCompletion(videoId);
+ sourceKey,
+ operation,
+ async (tx, current, upload, state) => {
+ if (state.dispatch !== "pending") return false;
+ if (upload.phase !== "processing")
+ throw new FatalError("Edit is no longer waiting for dispatch");
+ await tx
+ .update(videos)
+ .set({
+ metadata: {
+ ...current.metadata,
+ editProcessing: { ...state, dispatch: "dispatching" },
+ },
+ })
+ .where(eq(videos.id, current.id));
+ return true;
+ },
+ );
+ if (!claimed) return { status: "accepted" };
+ let dispatch: EditDispatch & { jobId?: string };
+ try {
+ dispatch = await startMediaServerEditJob(mediaServerUrl, {
+ videoId,
+ userId,
+ sourceUrl,
+ outputPresignedUrl,
+ outputVerificationUrl,
+ thumbnailPresignedUrl,
+ previewGifPresignedUrl,
+ webhookUrl: webhookUrl.toString(),
+ webhookSecret: webhookSecret || undefined,
+ keepRanges,
+ });
+ } catch {
+ return { status: "accepted" };
+ }
+ await withEditOperation(
+ videoId,
+ sourceKey,
+ operation,
+ async (tx, current, _upload, state) => {
+ if (state.dispatch !== "dispatching") return;
+ await tx
+ .update(videos)
+ .set({
+ metadata: {
+ ...current.metadata,
+ editProcessing: {
+ ...state,
+ dispatch: dispatch.status === "accepted" ? "accepted" : "pending",
+ ...(dispatch.jobId ? { jobId: dispatch.jobId } : {}),
+ },
+ },
+ })
+ .where(eq(videos.id, current.id));
+ },
+ );
+ return dispatch;
}
-async function markEditWaitingForCapacity(videoId: string): Promise<void> {
+async function markEditWaitingForCapacity(
+ videoId: string,
+ sourceKey: string,
+ operation: EditOperation,
+): Promise<void> {
"use step";
-
- await db()
- .update(videoUploads)
- .set({
- processingMessage: "Queued for video editing...",
- processingError: null,
- updatedAt: new Date(),
- })
- .where(eq(videoUploads.videoId, videoId as Video.VideoId));
+ await withEditOperation(videoId, sourceKey, operation, async (tx, video) => {
+ await tx
+ .update(videoUploads)
+ .set({
+ processingMessage: "Queued for video editing...",
+ processingError: null,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, video.id));
+ });
}
function getMetadataFromVideoRow(
@@ -432,22 +458,6 @@ function getMetadataFromVideoRow(
};
}
-async function getCompletedMetadata(
- videoId: string,
-): Promise<VideoEditRenderResult["metadata"] | null> {
- const [video] = await db()
- .select({
- duration: videos.duration,
- width: videos.width,
- height: videos.height,
- fps: videos.fps,
- })
- .from(videos)
- .where(eq(videos.id, videoId as Video.VideoId));
-
- return getMetadataFromVideoRow(video);
-}
-
async function probeVideoOnMediaServer(
mediaServerUrl: string,
videoUrl: string,
@@ -687,61 +697,32 @@ async function clearTranscriptObjects(video: typeof videos.$inferSelect) {
}
}
-async function waitForEditCompletion(
+async function readEditCompletion(
videoId: string,
-): Promise<VideoEditRenderResult> {
- let lastStatus = "processing";
-
- for (
- let attempt = 0;
- attempt < MEDIA_SERVER_COMPLETION_MAX_ATTEMPTS;
- attempt++
- ) {
- await waitForRetry(MEDIA_SERVER_COMPLETION_POLL_INTERVAL_MS);
-
- const [upload] = await db()
- .select({
- phase: videoUploads.phase,
- processingProgress: videoUploads.processingProgress,
- processingMessage: videoUploads.processingMessage,
- processingError: videoUploads.processingError,
- })
- .from(videoUploads)
- .where(eq(videoUploads.videoId, videoId as Video.VideoId));
-
- if (!upload) {
- throw new Error("Edit processing state disappeared");
- }
-
- if (upload.phase === "complete") {
- const metadata = await getCompletedMetadata(videoId);
- if (!metadata) {
- throw new Error("Edit completed but video metadata is missing");
+ sourceKey: string,
+ operation: EditOperation,
+): Promise<VideoEditRenderResult | undefined> {
+ "use step";
+ return withEditOperation(
+ videoId,
+ sourceKey,
+ operation,
+ async (_tx, video, upload) => {
+ if (upload.phase === "complete") {
+ const metadata = getMetadataFromVideoRow(video);
+ if (!metadata)
+ throw new FatalError("Edit completed but video metadata is missing");
+ return { metadata };
}
-
- return { metadata };
- }
-
- if (upload.processingError) {
- throw new Error(upload.processingError);
- }
-
- if (upload.phase === "error") {
- throw new Error(upload.processingMessage || "Video edit failed");
- }
-
- lastStatus = [
- upload.phase,
- typeof upload.processingProgress === "number"
- ? `${upload.processingProgress}%`
- : null,
- upload.processingMessage,
- ]
- .filter(Boolean)
- .join(" ");
- }
-
- throw new Error(`Video edit timed out while ${lastStatus}`);
+ if (upload.phase === "error" || upload.processingError)
+ throw new FatalError(
+ upload.processingError ||
+ upload.processingMessage ||
+ "Video edit failed",
+ );
+ return undefined;
+ },
+ );
}
function getEditInvalidationCallerReference(
@@ -821,6 +802,7 @@ export async function saveEditResultAndComplete(
previousSpec: VideoEditSpec,
editSpec: VideoEditSpec,
metadata: { duration: number; width: number; height: number; fps: number },
+ operation: EditOperation,
): Promise<{ transcriptRemapped: boolean }> {
"use step";
@@ -834,6 +816,14 @@ export async function saveEditResultAndComplete(
throw new FatalError("Video does not exist");
}
+ const completed = getCompletedEdit(video.metadata);
+ if (
+ completed?.token === operation.token &&
+ completed.startedAt === operation.startedAt
+ ) {
+ return { transcriptRemapped: completed.transcriptRemapped };
+ }
+
let originalTranscript: EditTranscript | null = null;
try {
originalTranscript = await loadOriginalEditTranscript(video, editSpec);
@@ -844,92 +834,79 @@ export 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({
- width: metadata.width,
- 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 }),
- ...(duration === undefined ? {} : { duration }),
- })
- .where(eq(videos.id, videoId as Video.VideoId));
+ await withEditOperation(
+ videoId,
+ sourceKey,
+ operation,
+ async (tx, lockedVideo, upload, state) => {
+ if (upload.phase !== "complete")
+ throw new FatalError("Edit output is not complete");
+ if (state.resultCommitted) return;
+ await retireDesktopRecordingJobForOutputReplacement(tx, {
+ videoId: video.id,
+ userId: video.ownerId,
+ });
+ const nextMetadata = clearAiMetadata(lockedVideo.metadata);
+ delete nextMetadata.desktopRecordingUpload;
+ await tx
+ .update(videos)
+ .set({
+ width: metadata.width,
+ height: metadata.height,
+ fps: metadata.fps,
+ metadata: {
+ ...nextMetadata,
+ editProcessing: { ...state, resultCommitted: true },
+ },
+ // Derivable captions keep the transcription COMPLETE; only legacy
+ // videos without a stored word transcript get re-transcribed.
+ ...(originalTranscript ? {} : { transcriptionStatus: null }),
+ ...(duration === undefined ? {} : { duration }),
+ })
+ .where(eq(videos.id, videoId as Video.VideoId));
- await tx
- .insert(videoEdits)
- .values({
- videoId: videoId as Video.VideoId,
- sourceKey,
- editSpec,
- updatedAt: new Date(),
- })
- .onDuplicateKeyUpdate({
- set: {
+ await tx
+ .insert(videoEdits)
+ .values({
+ videoId: videoId as Video.VideoId,
sourceKey,
editSpec,
updatedAt: new Date(),
- },
- });
-
- const timestampedComments = await tx
- .select({
- id: comments.id,
- timestamp: comments.timestamp,
- })
- .from(comments)
- .where(eq(comments.videoId, videoId as Video.VideoId));
-
- for (const comment of timestampedComments) {
- if (comment.timestamp === null) continue;
- const nextTimestamp = remapCurrentOutputTimeThroughEdit(
- comment.timestamp,
- previousSpec,
- editSpec,
- );
- if (nextTimestamp === comment.timestamp) continue;
- await tx
- .update(comments)
- .set({ timestamp: nextTimestamp })
- .where(eq(comments.id, comment.id));
- }
-
- await tx
- .delete(videoUploads)
- .where(
- and(
- eq(videoUploads.videoId, videoId as Video.VideoId),
- eq(videoUploads.phase, "complete"),
- eq(videoUploads.rawFileKey, sourceKey),
- ),
- );
- });
+ })
+ .onDuplicateKeyUpdate({
+ set: {
+ sourceKey,
+ editSpec,
+ updatedAt: new Date(),
+ },
+ });
+
+ const timestampedComments = await tx
+ .select({
+ id: comments.id,
+ timestamp: comments.timestamp,
+ })
+ .from(comments)
+ .where(eq(comments.videoId, videoId as Video.VideoId));
+
+ for (const comment of timestampedComments) {
+ if (comment.timestamp === null) continue;
+ const nextTimestamp = remapCurrentOutputTimeThroughEdit(
+ comment.timestamp,
+ previousSpec,
+ editSpec,
+ );
+ if (nextTimestamp === comment.timestamp) continue;
+ await tx
+ .update(comments)
+ .set({ timestamp: nextTimestamp })
+ .where(eq(comments.id, comment.id));
+ }
+ },
+ true,
+ );
+ let transcriptRemapped = false;
if (originalTranscript) {
try {
await rewriteTranscriptObjectsForEdit(
@@ -937,57 +914,72 @@ export async function saveEditResultAndComplete(
originalTranscript,
editSpec,
);
- return { transcriptRemapped: true };
+ transcriptRemapped = true;
} catch (error) {
console.warn(
"[editVideoWorkflow] Failed to remap transcript objects",
error,
);
- await db()
- .update(videos)
- .set({ transcriptionStatus: null })
- .where(eq(videos.id, videoId as Video.VideoId));
}
}
-
- try {
- await clearTranscriptObjects(video);
- } catch (error) {
- console.warn(
- "[editVideoWorkflow] Failed to clear transcript objects",
- error,
+ if (!transcriptRemapped) {
+ await withEditOperation(
+ videoId,
+ sourceKey,
+ operation,
+ async (tx, current) => {
+ await tx
+ .update(videos)
+ .set({ transcriptionStatus: null })
+ .where(eq(videos.id, current.id));
+ },
);
+ await clearTranscriptObjects(video);
}
+ await completeEditProcessing(
+ videoId,
+ sourceKey,
+ operation,
+ transcriptRemapped,
+ );
+ return { transcriptRemapped };
+}
- return { transcriptRemapped: false };
+async function completeEditProcessing(
+ videoId: string,
+ sourceKey: string,
+ operation: EditOperation,
+ transcriptRemapped: boolean,
+) {
+ await withEditOperation(
+ videoId,
+ sourceKey,
+ operation,
+ async (tx, video, upload, state) => {
+ if (!state.resultCommitted || upload.phase !== "complete")
+ throw new FatalError("Edit result has not been committed");
+ await tx
+ .update(videos)
+ .set({
+ metadata: {
+ ...withoutEditProcessing(video.metadata),
+ completedVideoEdit: { ...operation, transcriptRemapped },
+ },
+ ...(video.source.type === "desktopMP4"
+ ? { source: { type: "desktopMP4" as const } }
+ : {}),
+ })
+ .where(eq(videos.id, video.id));
+ await tx.delete(videoUploads).where(eq(videoUploads.videoId, video.id));
+ },
+ );
}
async function clearEditProcessingState(
videoId: string,
sourceKey: string,
- previousSpec: VideoEditSpec,
+ operation: EditOperation,
): Promise<void> {
"use step";
-
- const previousDuration = getValidDuration(
- getEditSpecOutputDuration(previousSpec),
- );
-
- await db().transaction(async (tx) => {
- if (previousDuration !== undefined) {
- await tx
- .update(videos)
- .set({ duration: previousDuration })
- .where(eq(videos.id, videoId as Video.VideoId));
- }
-
- await tx
- .delete(videoUploads)
- .where(
- and(
- eq(videoUploads.videoId, videoId as Video.VideoId),
- eq(videoUploads.rawFileKey, sourceKey),
- ),
- );
- });
+ await clearPendingEdit(videoId, sourceKey, operation);
}
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index 082c9ed56..672f5029d 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -6,6 +6,23 @@
* Video metadata structure
*/
export interface VideoMetadata {
+ editProcessing?: {
+ token: string;
+ startedAt: string;
+ ownerId: string;
+ bucket: string | null;
+ storageIntegrationId: string | null;
+ sourceKey: string;
+ source: string;
+ dispatch: "pending" | "dispatching" | "accepted";
+ jobId?: string;
+ resultCommitted?: boolean;
+ };
+ completedVideoEdit?: {
+ token: string;
+ startedAt: string;
+ transcriptRemapped: boolean;
+ };
desktopRecordingUpload?: {
version: 1;
artifact: