Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): keep the original recording when its storage check fails

Zorion Arrillagac29a7fcb8157
diff --git a/apps/web/__tests__/unit/save-video-edits-original-source.test.ts b/apps/web/__tests__/unit/save-video-edits-original-source.test.ts
new file mode 100644
index 000000000..4218049e8
--- /dev/null
+++ b/apps/web/__tests__/unit/save-video-edits-original-source.test.ts
@@ -0,0 +1,212 @@
+import { Effect } from "effect";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const tables = vi.hoisted(() => ({
+ videos: { id: "videos.id" },
+ videoUploads: { videoId: "videoUploads.videoId" },
+ videoEdits: { videoId: "videoEdits.videoId" },
+}));
+
+const state = vi.hoisted(() => ({
+ rows: new Map<unknown, unknown[]>(),
+}));
+
+const headObjectMock = vi.fn();
+const copyObjectMock = vi.fn();
+const clearPendingEditMock = vi.fn();
+const startMock = vi.fn();
+
+function selectFromRows() {
+ return {
+ from: (table: unknown) => ({
+ where: () => {
+ const rows = state.rows.get(table) ?? [];
+ return Object.assign(Promise.resolve(rows), {
+ for: () => Promise.resolve(rows),
+ });
+ },
+ }),
+ };
+}
+
+vi.mock("@cap/database", () => ({
+ db: () => ({
+ select: selectFromRows,
+ transaction: async (run: (tx: Record<string, unknown>) => Promise<void>) =>
+ run({
+ select: selectFromRows,
+ insert: () => ({ values: async () => undefined }),
+ update: () => ({
+ set: () => ({ where: async () => undefined }),
+ }),
+ delete: () => ({ where: async () => undefined }),
+ }),
+ }),
+}));
+
+vi.mock("@cap/database/schema", () => tables);
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: async () => ({ id: "user-1", isPro: true }),
+}));
+
+vi.mock("@cap/env", () => ({ serverEnv: () => ({}) }));
+
+vi.mock("@cap/utils", () => ({
+ userIsPro: (user?: { isPro?: boolean } | null) => Boolean(user?.isPro),
+}));
+
+vi.mock("@cap/web-backend", () => ({
+ Storage: {
+ getAccessForVideo: () =>
+ Effect.succeed([
+ {
+ bucketName: "cap-bucket",
+ headObject: headObjectMock,
+ copyObject: copyObjectMock,
+ },
+ ]),
+ },
+}));
+
+vi.mock("drizzle-orm", () => ({ eq: () => undefined }));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+vi.mock("workflow/api", () => ({ start: startMock }));
+vi.mock("server-only", () => ({}));
+vi.mock("@/lib/server", () => ({ runPromise: Effect.runPromise }));
+vi.mock("@/lib/video-storage", () => ({ decodeStorageVideo: vi.fn() }));
+vi.mock("@/lib/legacy-video-edit-recovery", () => ({
+ assertLegacyEditsQuiescent: vi.fn(),
+}));
+vi.mock("@/lib/video-edit-operation", () => ({
+ clearPendingEdit: clearPendingEditMock,
+}));
+vi.mock("@/utils/flags", () => ({ isAiGenerationEnabled: async () => false }));
+vi.mock("@/workflows/edit-video", () => ({ editVideoWorkflow: {} }));
+
+const sourceKey = "user-1/video-1/source/original.mp4";
+
+function storageError(cause: unknown) {
+ return { _tag: "StorageError", cause: { _tag: "S3Error", cause } };
+}
+
+function s3Error(name: string, httpStatusCode: number) {
+ return Object.assign(new Error(name), {
+ name,
+ $metadata: { httpStatusCode },
+ });
+}
+
+function setUpVideo({ edited }: { edited: boolean }) {
+ const video = {
+ id: "video-1",
+ ownerId: "user-1",
+ duration: edited ? 120 : 600,
+ source: { type: "webMP4" },
+ bucket: null,
+ storageIntegrationId: null,
+ isScreenshot: false,
+ metadata: null,
+ };
+ state.rows.set(tables.videos, [video]);
+ state.rows.set(tables.videoUploads, []);
+ state.rows.set(
+ tables.videoEdits,
+ edited
+ ? [
+ {
+ videoId: "video-1",
+ sourceKey,
+ editSpec: {
+ version: 1,
+ sourceDuration: 600,
+ keepRanges: [{ start: 0, end: 120 }],
+ },
+ },
+ ]
+ : [],
+ );
+}
+
+async function saveTrim(end: number) {
+ const { saveVideoEdits } = await import("@/actions/videos/save-edits");
+ return saveVideoEdits("video-1" as never, {
+ version: 1,
+ sourceDuration: 600,
+ keepRanges: [{ start: 0, end }],
+ });
+}
+
+describe("saveVideoEdits original source copy", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ state.rows.clear();
+ copyObjectMock.mockReturnValue(Effect.succeed({}));
+ });
+
+ it("keeps the preserved original when its HEAD request fails transiently", async () => {
+ setUpVideo({ edited: true });
+ headObjectMock.mockReturnValue(
+ Effect.fail(storageError(s3Error("SlowDown", 503))),
+ );
+
+ await expect(saveTrim(60)).rejects.toBeDefined();
+
+ expect(copyObjectMock).not.toHaveBeenCalled();
+ expect(startMock).not.toHaveBeenCalled();
+ expect(clearPendingEditMock).toHaveBeenCalledOnce();
+ });
+
+ it("keeps the preserved original when the HEAD request hits a network error", async () => {
+ setUpVideo({ edited: true });
+ headObjectMock.mockReturnValue(
+ Effect.fail(storageError(new Error("socket hang up"))),
+ );
+
+ await expect(saveTrim(60)).rejects.toBeDefined();
+
+ expect(copyObjectMock).not.toHaveBeenCalled();
+ });
+
+ it("preserves the current result as the original on the first edit", async () => {
+ setUpVideo({ edited: false });
+ headObjectMock.mockReturnValue(
+ Effect.fail(storageError(s3Error("NotFound", 404))),
+ );
+
+ await expect(saveTrim(300)).resolves.toEqual({ success: true });
+
+ expect(copyObjectMock).toHaveBeenCalledWith(
+ "cap-bucket/user-1/video-1/result.mp4",
+ sourceKey,
+ );
+ expect(startMock).toHaveBeenCalledOnce();
+ });
+
+ it("treats a Google Drive 404 as a missing original", async () => {
+ setUpVideo({ edited: false });
+ headObjectMock.mockReturnValue(
+ Effect.fail(
+ storageError(
+ Object.assign(new Error("Storage object not found"), {
+ name: "GoogleDriveRequestError",
+ status: 404,
+ }),
+ ),
+ ),
+ );
+
+ await expect(saveTrim(300)).resolves.toEqual({ success: true });
+
+ expect(copyObjectMock).toHaveBeenCalledOnce();
+ });
+
+ it("does not copy when the preserved original exists", async () => {
+ setUpVideo({ edited: true });
+ headObjectMock.mockReturnValue(Effect.succeed({ ContentLength: 1 }));
+
+ await expect(saveTrim(60)).resolves.toEqual({ success: true });
+
+ expect(copyObjectMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/video-edit-actions.test.ts b/apps/web/__tests__/unit/video-edit-actions.test.ts
index 4294a303d..c1ba0f9aa 100644
--- a/apps/web/__tests__/unit/video-edit-actions.test.ts
+++ b/apps/web/__tests__/unit/video-edit-actions.test.ts
@@ -166,7 +166,9 @@ function legacyUpload() {
describe("video edit claims and recovery", () => {
it("claims the recording before copying its original source", async () => {
- mocks.head.mockReturnValue(Effect.fail(new Error("Missing")));
+ mocks.head.mockReturnValue(
+ Effect.fail(Object.assign(new Error("Missing"), { name: "NotFound" })),
+ );
mocks.copy.mockImplementation(() => {
expect(mocks.upload?.phase).toBe("processing");
return Effect.void;
diff --git a/apps/web/actions/videos/save-edits.ts b/apps/web/actions/videos/save-edits.ts
index 2ba3c7cc3..b58f687a8 100644
--- a/apps/web/actions/videos/save-edits.ts
+++ b/apps/web/actions/videos/save-edits.ts
@@ -15,6 +15,7 @@ import { revalidatePath } from "next/cache";
import { start } from "workflow/api";
import { assertLegacyEditsQuiescent } from "@/lib/legacy-video-edit-recovery";
import { runPromise } from "@/lib/server";
+import { isStorageObjectNotFound } from "@/lib/storage-not-found";
import {
clearPendingEdit,
type EditOperation,
@@ -53,7 +54,7 @@ async function objectExists(
) {
return await bucket.headObject(key).pipe(
Effect.as(true),
- Effect.catchAll(() => Effect.succeed(false)),
+ Effect.catchIf(isStorageObjectNotFound, () => Effect.succeed(false)),
runPromise,
);
}
diff --git a/apps/web/lib/storage-not-found.ts b/apps/web/lib/storage-not-found.ts
new file mode 100644
index 000000000..642ff1873
--- /dev/null
+++ b/apps/web/lib/storage-not-found.ts
@@ -0,0 +1,25 @@
+// A transient HEAD failure (5xx, SlowDown, network) must not read as "missing":
+// save-edits would then copy the edited result over the preserved original.
+export function isStorageObjectNotFound(error: unknown): boolean {
+ const visited = new Set<unknown>();
+ let value: unknown = error;
+ for (let depth = 0; depth < 16; depth++) {
+ if (typeof value !== "object" || value === null || visited.has(value))
+ return false;
+ visited.add(value);
+ const record = value as Record<string, unknown>;
+ if (record.name === "NoSuchKey" || record.name === "NotFound") return true;
+ if (record.name === "GoogleDriveRequestError" && record.status === 404)
+ return true;
+ const metadata = record.$metadata;
+ if (
+ typeof metadata === "object" &&
+ metadata !== null &&
+ "httpStatusCode" in metadata &&
+ metadata.httpStatusCode === 404
+ )
+ return true;
+ value = record.cause;
+ }
+ return false;
+}