Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: isolate edit outputs before releasing failed operations

Richie McIlroydea829c592e7
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 59ac3893c..e3a417ef4 100644
--- a/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
+++ b/apps/web/__tests__/unit/desktop-recording-output-replacement.test.ts
@@ -252,7 +252,25 @@ describe("edited recording publication", () => {
);
});
- it("switches a completed edit to canonical output and retires old upload proof atomically", async () => {
+ it("verifies the current edit output independently of the published video", async () => {
+ await verifyRenderedEditOutput(
+ "video",
+ "user",
+ editSpec,
+ metadata,
+ operation,
+ );
+ expect(mocks.fetch).toHaveBeenCalledWith(
+ "https://media.test/video/probe",
+ expect.objectContaining({
+ body: JSON.stringify({
+ videoUrl: `https://storage.test/canonical/user/video/.recording/outputs/edit-${operation.token}/result.mp4`,
+ }),
+ }),
+ );
+ });
+
+ it("publishes a completed edit from its own output and retires old upload proof atomically", async () => {
video.metadata.editProcessing = {
...operation,
ownerId: video.ownerId,
@@ -270,7 +288,12 @@ describe("edited recording publication", () => {
metadata,
operation,
);
- expect(video.source).toEqual({ type: "desktopMP4" });
+ expect(video.source).toEqual({
+ type: "desktopMP4",
+ outputKey: `user/video/.recording/outputs/edit-${operation.token}/result.mp4`,
+ thumbnailKey: `user/video/.recording/outputs/edit-${operation.token}/thumbnail.jpg`,
+ previewKey: `user/video/.recording/outputs/edit-${operation.token}/preview.gif`,
+ });
expect(video.metadata).not.toHaveProperty("desktopRecordingUpload");
expect(video.metadata.customCreatedAt).toBe("2020-01-01T00:00:00Z");
expect(events.indexOf("lock-job")).toBeLessThan(
diff --git a/apps/web/__tests__/unit/video-edit-operation.test.ts b/apps/web/__tests__/unit/video-edit-operation.test.ts
index 659c84007..9900d434c 100644
--- a/apps/web/__tests__/unit/video-edit-operation.test.ts
+++ b/apps/web/__tests__/unit/video-edit-operation.test.ts
@@ -46,7 +46,9 @@ vi.mock("@cap/database", () => {
});
import {
+ clearFailedEdit,
clearPendingEdit,
+ getEditOutputKeys,
getEditProcessingState,
matchesEditOperation,
} from "@/lib/video-edit-operation";
@@ -179,7 +181,10 @@ describe("edit operation ownership", () => {
);
expect(mocks.writes).toEqual([]);
expect(mocks.upload?.phase).toBe("complete");
- expect(mocks.video?.duration).toBe(5);
+ expect(mocks.video?.duration).toBe(10);
+ expect(mocks.video?.metadata).toMatchObject({
+ editProcessing: { renderedMetadata: { duration: 5 } },
+ });
});
it("rejects invalid completion metadata without changing state", async () => {
await expect(
@@ -204,6 +209,42 @@ describe("edit operation ownership", () => {
await clearPendingEdit("video", sourceKey, operation);
expect(mocks.writes).toEqual([]);
});
+ it.each(["pending", "dispatching", "accepted"] as const)(
+ "releases a failed %s edit while preserving published media",
+ async (dispatch) => {
+ if (!mocks.video) throw new Error("Missing fixture");
+ mocks.video.metadata = { editProcessing: { ...state, dispatch } };
+ await clearFailedEdit("video", sourceKey, operation);
+ expect(mocks.upload).toBeUndefined();
+ expect(mocks.video.source).toEqual(source);
+ expect(mocks.video.duration).toBe(10);
+ mocks.writes = [];
+ await applyEditProgress(
+ {
+ ...progress,
+ phase: "complete",
+ metadata: { duration: 2, width: 320, height: 180, fps: 30 },
+ },
+ operation.token,
+ operation.startedAt,
+ );
+ expect(mocks.writes).toEqual([]);
+ },
+ );
+ it("isolates every worker output from earlier and later edits", () => {
+ const first = getEditOutputKeys("owner", "video", operation);
+ const second = getEditOutputKeys("owner", "video", {
+ ...operation,
+ token: "22222222-2222-4222-8222-222222222222",
+ });
+ expect(
+ new Set([...Object.values(first), ...Object.values(second)]).size,
+ ).toBe(6);
+ for (const key of Object.values(first))
+ expect(key).toContain(
+ `/video/.recording/outputs/edit-${operation.token}/`,
+ );
+ });
it("clears only an operation that has not dispatched", async () => {
if (!mocks.video) throw new Error("Missing fixture");
mocks.video.metadata = {
diff --git a/apps/web/__tests__/unit/video-edit-published-output.test.ts b/apps/web/__tests__/unit/video-edit-published-output.test.ts
new file mode 100644
index 000000000..39099e4ea
--- /dev/null
+++ b/apps/web/__tests__/unit/video-edit-published-output.test.ts
@@ -0,0 +1,67 @@
+import {
+ getPublishedRecordingCopyKeys,
+ getPublishedRecordingOutputKey,
+ resolveRecordingObjectKey,
+} from "@cap/web-backend/src/Storage/recording-output";
+import { describe, expect, it } from "vitest";
+
+const prefix = "owner/video/";
+const editPrefix = `${prefix}.recording/outputs/edit-11111111-1111-4111-8111-111111111111/`;
+
+describe.each(["desktopMP4", "webMP4"])("published %s edit output", (type) => {
+ const video = {
+ id: "video",
+ ownerId: "owner",
+ source: {
+ type,
+ outputKey: `${editPrefix}result.mp4`,
+ thumbnailKey: `${editPrefix}thumbnail.jpg`,
+ previewKey: `${editPrefix}preview.gif`,
+ },
+ };
+ it("resolves playback, thumbnails, previews and duplication to the current edit", () => {
+ expect(getPublishedRecordingOutputKey(video)).toBe(
+ `${editPrefix}result.mp4`,
+ );
+ expect(resolveRecordingObjectKey(video, `${prefix}result.mp4`)).toBe(
+ `${editPrefix}result.mp4`,
+ );
+ expect(
+ resolveRecordingObjectKey(
+ video,
+ `${prefix}screenshot/screen-capture.jpg`,
+ ),
+ ).toBe(`${editPrefix}thumbnail.jpg`);
+ expect(
+ resolveRecordingObjectKey(video, `${prefix}preview/animated-preview.gif`),
+ ).toBe(`${editPrefix}preview.gif`);
+ expect(getPublishedRecordingCopyKeys(video)).toEqual([
+ `${prefix}result.mp4`,
+ `${prefix}screenshot/screen-capture.jpg`,
+ `${prefix}preview/animated-preview.gif`,
+ ]);
+ });
+ it("preserves original source reads", () => {
+ const original = `${prefix}source/original.mp4`;
+ expect(resolveRecordingObjectKey(video, original)).toBe(original);
+ });
+ it("rejects another recording's output and asset pointers", () => {
+ const foreign = {
+ ...video,
+ source: {
+ type,
+ outputKey: "other/video/.recording/outputs/x/result.mp4",
+ thumbnailKey: "other/video/.recording/outputs/x/thumbnail.jpg",
+ },
+ };
+ expect(resolveRecordingObjectKey(foreign, `${prefix}result.mp4`)).toBe(
+ `${prefix}result.mp4`,
+ );
+ expect(
+ resolveRecordingObjectKey(
+ foreign,
+ `${prefix}screenshot/screen-capture.jpg`,
+ ),
+ ).toBe(`${prefix}screenshot/screen-capture.jpg`);
+ });
+});
diff --git a/apps/web/app/api/storage/object/route.ts b/apps/web/app/api/storage/object/route.ts
index 184b774f9..d20d974c6 100644
--- a/apps/web/app/api/storage/object/route.ts
+++ b/apps/web/app/api/storage/object/route.ts
@@ -165,7 +165,8 @@ export async function GET(request: NextRequest) {
isInternalRecordingKey(key) &&
!(tokenPayload?.videoId === videoIdParam && tokenPayload.key === key) &&
!(
- video.source.type === "desktopMP4" &&
+ (video.source.type === "desktopMP4" ||
+ video.source.type === "webMP4") &&
[
key === video.source.outputKey,
key === video.source.thumbnailKey,
diff --git a/apps/web/lib/video-edit-operation.ts b/apps/web/lib/video-edit-operation.ts
index c844987b1..7c2d853d6 100644
--- a/apps/web/lib/video-edit-operation.ts
+++ b/apps/web/lib/video-edit-operation.ts
@@ -26,6 +26,14 @@ const stateSchema = z.object({
dispatch: z.enum(["pending", "dispatching", "accepted"]),
jobId: z.string().optional(),
resultCommitted: z.boolean().optional(),
+ renderedMetadata: z
+ .object({
+ duration: z.number().positive(),
+ width: z.number().positive(),
+ height: z.number().positive(),
+ fps: z.number().positive(),
+ })
+ .optional(),
});
export type EditProcessingState = z.infer<typeof stateSchema>;
type Transaction = Parameters<
@@ -163,3 +171,46 @@ export async function clearPendingEdit(
await tx.delete(videoUploads).where(eq(videoUploads.videoId, video.id));
});
}
+
+export function getEditOutputKeys(
+ ownerId: string,
+ videoId: string,
+ operation: EditOperation,
+) {
+ const prefix = `${ownerId}/${videoId}/.recording/outputs/edit-${operation.token}`;
+ return {
+ outputKey: `${prefix}/result.mp4`,
+ thumbnailKey: `${prefix}/thumbnail.jpg`,
+ previewKey: `${prefix}/preview.gif`,
+ };
+}
+
+export async function clearFailedEdit(
+ 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);
+ await tx
+ .update(videos)
+ .set({
+ metadata: withoutEditProcessing(video.metadata),
+ ...(state?.resultCommitted ? { transcriptionStatus: null } : {}),
+ })
+ .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
index d35756dd6..5cde66c22 100644
--- a/apps/web/lib/video-edit-progress.ts
+++ b/apps/web/lib/video-edit-progress.ts
@@ -29,7 +29,28 @@ export async function applyEditProgress(
.where(eq(videos.id, payload.videoId as Video.VideoId))
.for("update");
const state = getEditProcessingState(video?.metadata ?? null);
- if (!token && !state) return false;
+ if (!token && !state) {
+ if (
+ video &&
+ "outputKey" in video.source &&
+ video.source.outputKey?.startsWith(
+ `${video.ownerId}/${video.id}/.recording/outputs/edit-`,
+ )
+ ) {
+ const [currentUpload] = await tx
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, video.id))
+ .for("update");
+ if (
+ !currentUpload ||
+ currentUpload.rawFileKey ===
+ `${video.ownerId}/${video.id}/source/original.mp4`
+ )
+ return true;
+ }
+ return false;
+ }
if (!video || !state || !token || !startedAt) return true;
const [upload] = await tx
.select()
@@ -70,18 +91,21 @@ export async function applyEditProgress(
...state,
dispatch: "accepted",
jobId: payload.jobId,
+ ...(complete && payload.metadata
+ ? {
+ renderedMetadata: {
+ duration: payload.metadata.duration,
+ width: payload.metadata.width,
+ height: payload.metadata.height,
+ fps: payload.metadata.fps,
+ },
+ }
+ : {}),
},
},
- ...(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({
diff --git a/apps/web/workflows/edit-video.ts b/apps/web/workflows/edit-video.ts
index 28112c471..b1e81d633 100644
--- a/apps/web/workflows/edit-video.ts
+++ b/apps/web/workflows/edit-video.ts
@@ -34,9 +34,10 @@ import { decryptEditTranscriptObject } from "@/lib/edit-transcript-storage";
import { startAiGeneration } from "@/lib/generate-ai";
import { transcribeVideo } from "@/lib/transcribe";
import {
- clearPendingEdit,
+ clearFailedEdit,
type EditOperation,
getCompletedEdit,
+ getEditOutputKeys,
matchesEditOperation,
withEditOperation,
withoutEditProcessing,
@@ -76,10 +77,6 @@ const MEDIA_SERVER_OUTPUT_VERIFICATION_MAX_ATTEMPTS = 4;
const MEDIA_SERVER_OUTPUT_VERIFICATION_RETRY_MS = 1000;
const EDIT_TRANSCRIPT_CURRENCY_TOLERANCE_MS = 250;
-function isPositiveNumber(value: number | null): value is number {
- return typeof value === "number" && Number.isFinite(value) && value > 0;
-}
-
function getValidDuration(duration: number) {
return Number.isFinite(duration) && duration > 0 ? duration : undefined;
}
@@ -143,9 +140,15 @@ export async function editVideoWorkflow(
}
if (!result)
throw new FatalError(
- "Video edit timed out; its worker must be reconciled before another edit can start",
+ "Video edit timed out. Your previous video is preserved; please try again.",
);
- await verifyRenderedEditOutput(videoId, userId, editSpec, result.metadata);
+ await verifyRenderedEditOutput(
+ videoId,
+ userId,
+ editSpec,
+ result.metadata,
+ operation,
+ );
await invalidateEditedVideoCache(videoId, editSpec);
const { transcriptRemapped } = await saveEditResultAndComplete(
videoId,
@@ -299,9 +302,11 @@ async function renderVideoEditOnMediaServer(
})
.pipe(runWorkflowPromise);
- const outputKey = `${userId}/${videoId}/result.mp4`;
- const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
- const previewGifKey = `${userId}/${videoId}/preview/animated-preview.gif`;
+ const {
+ outputKey,
+ thumbnailKey,
+ previewKey: previewGifKey,
+ } = getEditOutputKeys(userId, videoId, operation);
const outputPresignedUrl = await bucket
.getInternalPresignedPutUrl(
@@ -431,33 +436,6 @@ async function markEditWaitingForCapacity(
});
}
-function getMetadataFromVideoRow(
- video:
- | {
- duration: number | null;
- width: number | null;
- height: number | null;
- fps: number | null;
- }
- | undefined,
-): VideoEditRenderResult["metadata"] | null {
- if (
- !video ||
- !isPositiveNumber(video.width) ||
- !isPositiveNumber(video.height) ||
- !isPositiveNumber(video.fps)
- ) {
- return null;
- }
-
- return {
- duration: isPositiveNumber(video.duration) ? video.duration : 0,
- width: video.width,
- height: video.height,
- fps: video.fps,
- };
-}
-
async function probeVideoOnMediaServer(
mediaServerUrl: string,
videoUrl: string,
@@ -495,6 +473,7 @@ export async function verifyRenderedEditOutput(
userId: string,
editSpec: VideoEditSpec,
reportedMetadata: VideoEditRenderResult["metadata"],
+ operation?: EditOperation,
): Promise<void> {
"use step";
@@ -522,7 +501,9 @@ export async function verifyRenderedEditOutput(
const [bucket] = await Storage.getAccessForVideo(decodeStorageVideo(video), {
resolvePublishedOutput: false,
}).pipe(runWorkflowPromise);
- const outputKey = `${userId}/${videoId}/result.mp4`;
+ const outputKey = operation
+ ? getEditOutputKeys(userId, videoId, operation).outputKey
+ : `${userId}/${videoId}/result.mp4`;
const outputUrl = await bucket
.getInternalSignedObjectUrl(outputKey, {
expiresIn: MEDIA_SERVER_PRESIGNED_GET_EXPIRES_SECONDS,
@@ -707,9 +688,9 @@ async function readEditCompletion(
videoId,
sourceKey,
operation,
- async (_tx, video, upload) => {
+ async (_tx, _video, upload, state) => {
if (upload.phase === "complete") {
- const metadata = getMetadataFromVideoRow(video);
+ const metadata = state.renderedMetadata;
if (!metadata)
throw new FatalError("Edit completed but video metadata is missing");
return { metadata };
@@ -846,17 +827,26 @@ export async function saveEditResultAndComplete(
videoId: video.id,
userId: video.ownerId,
});
+ const source = {
+ ...lockedVideo.source,
+ ...getEditOutputKeys(lockedVideo.ownerId, videoId, operation),
+ };
const nextMetadata = clearAiMetadata(lockedVideo.metadata);
delete nextMetadata.desktopRecordingUpload;
await tx
.update(videos)
.set({
+ source,
width: metadata.width,
height: metadata.height,
fps: metadata.fps,
metadata: {
...nextMetadata,
- editProcessing: { ...state, resultCommitted: true },
+ editProcessing: {
+ ...state,
+ source: JSON.stringify(source),
+ resultCommitted: true,
+ },
},
// Derivable captions keep the transcription COMPLETE; only legacy
// videos without a stored word transcript get re-transcribed.
@@ -965,9 +955,6 @@ async function completeEditProcessing(
...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));
@@ -981,5 +968,5 @@ async function clearEditProcessingState(
operation: EditOperation,
): Promise<void> {
"use step";
- await clearPendingEdit(videoId, sourceKey, operation);
+ await clearFailedEdit(videoId, sourceKey, operation);
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index e54a4d60d..4d66fc0f5 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -431,7 +431,12 @@ export const videos = mysqlTable(
previewKey?: string;
}
| { type: "desktopSegments" }
- | { type: "webMP4" }
+ | {
+ type: "webMP4";
+ outputKey?: string;
+ thumbnailKey?: string;
+ previewKey?: string;
+ }
>()
.notNull()
.default({ type: "MediaConvert" }),
diff --git a/packages/database/types/metadata.ts b/packages/database/types/metadata.ts
index 672f5029d..b8e4c1df9 100644
--- a/packages/database/types/metadata.ts
+++ b/packages/database/types/metadata.ts
@@ -17,6 +17,12 @@ export interface VideoMetadata {
dispatch: "pending" | "dispatching" | "accepted";
jobId?: string;
resultCommitted?: boolean;
+ renderedMetadata?: {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ };
};
completedVideoEdit?: {
token: string;
diff --git a/packages/web-backend/src/Storage/recording-output.ts b/packages/web-backend/src/Storage/recording-output.ts
index fb91708aa..6258f7a83 100644
--- a/packages/web-backend/src/Storage/recording-output.ts
+++ b/packages/web-backend/src/Storage/recording-output.ts
@@ -16,7 +16,7 @@ export function isInternalRecordingKey(key: string) {
}
export function getPublishedRecordingOutputKey(video: RecordingVideo) {
- return video.source.type === "desktopMP4"
+ return video.source.type === "desktopMP4" || video.source.type === "webMP4"
? Video.getRetainedRecordingOutputKey(
video.ownerId,
video.id,
@@ -34,7 +34,7 @@ export function resolveRecordingObjectKey(video: RecordingVideo, key: string) {
? video.source.previewKey
: undefined;
if (
- video.source.type === "desktopMP4" &&
+ (video.source.type === "desktopMP4" || video.source.type === "webMP4") &&
asset?.startsWith(`${prefix}.recording/outputs/`) &&
!asset.includes("..") &&
/^[a-zA-Z0-9_./-]+$/.test(asset)