Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(web): only treat storage 404s as missing in Loom reimport and media comment thumbnails
Richie McIlroy8e2b5ecaff2f
diff --git a/apps/web/__tests__/unit/media-processing-workflows.test.ts b/apps/web/__tests__/unit/media-processing-workflows.test.tsindex 57deff5af..dcfb779fb 100644--- a/apps/web/__tests__/unit/media-processing-workflows.test.ts+++ b/apps/web/__tests__/unit/media-processing-workflows.test.ts@@ -83,6 +83,17 @@ const video = {const metadata = { duration: 30, width: 1920, height: 1080, fps: 30 };const pending = { phase: "processing", processingProgress: 25 };+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 },+ });+}+describe("media processing workflows", () => {beforeEach(() => {mocks.rows = [];@@ -213,6 +224,56 @@ describe("media processing workflows", () => {);});+ it("does not re-import from Loom when the preserved upload check fails transiently", async () => {+ mocks.head.mockReturnValue(+ Effect.fail(storageError(s3Error("ServiceUnavailable", 503))),+ );+ mocks.rows = [[video]];+ await expect(+ importLoomVideoWorkflow({ ...payload, reuseExistingRawUpload: true }),+ ).rejects.toThrow();+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(mocks.put).not.toHaveBeenCalled();+ });++ it("does not re-import from Loom when the preserved upload check hits a network error", async () => {+ mocks.head.mockReturnValue(+ Effect.fail(storageError(new Error("socket hang up"))),+ );+ mocks.rows = [[video]];+ await expect(+ importLoomVideoWorkflow({ ...payload, reuseExistingRawUpload: true }),+ ).rejects.toThrow();+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(mocks.put).not.toHaveBeenCalled();+ });++ it.each([+ ["storage", storageError(s3Error("NotFound", 404))],+ [+ "Google Drive",+ {+ _tag: "StorageError",+ cause: Object.assign(new Error("Storage object not found"), {+ name: "GoogleDriveRequestError",+ status: 404,+ }),+ },+ ],+ ])(+ "re-imports from Loom when %s reports the preserved upload missing",+ async (_, error) => {+ mocks.head.mockReturnValue(Effect.fail(error));+ mocks.rows = [[video], [video], [pending], [], [metadata]];+ await expect(+ importLoomVideoWorkflow({ ...payload, reuseExistingRawUpload: true }),+ ).resolves.toMatchObject({ success: true });+ expect(mocks.fetch.mock.calls.at(-1)?.[0]).toBe(+ "https://worker.example.com/video/import",+ );+ },+ );+it("retries a failed Loom worker from its preserved original", async () => {mocks.rows = [[video],diff --git a/apps/web/__tests__/unit/new-media-comment-thumbnail.test.ts b/apps/web/__tests__/unit/new-media-comment-thumbnail.test.tsnew file mode 100644index 000000000..2f44c42ce--- /dev/null+++ b/apps/web/__tests__/unit/new-media-comment-thumbnail.test.ts@@ -0,0 +1,152 @@+import { Effect, Option } from "effect";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ head: vi.fn(),+ insert: vi.fn(),+}));++const video = { id: "video-1", ownerId: "owner-1" };+const mediaKey = "owner-1/video-1/comments/comment-1/media.webm";+const thumbnailKey = "owner-1/video-1/comments/comment-1/thumbnail.jpg";++vi.mock("@cap/database", () => ({+ db: () => ({+ insert: () => ({ values: mocks.insert }),+ }),+}));+vi.mock("@cap/database/schema", () => ({ comments: {} }));+vi.mock("@cap/database/auth/session", () => ({+ getCurrentUser: async () => ({ id: "user-1", name: "User" }),+}));+vi.mock("@cap/web-domain", () => ({+ Policy: { withPublicPolicy: () => (effect: unknown) => effect },+}));+vi.mock("@cap/web-backend", () => ({+ provideOptionalAuth: (effect: unknown) => effect,+ verifyCommentMediaUploadToken: () => ({+ userId: "user-1",+ videoId: "video-1",+ commentId: "comment-1",+ kind: "video",+ key: mediaKey,+ thumbnailKey,+ contentType: "video/webm",+ }),+ VideosRepo: Effect.succeed({+ getById: () => Effect.succeed(Option.some([video])),+ }),+ VideosPolicy: Effect.succeed({ canView: () => Effect.void }),+ Storage: {+ getAccessForVideo: () =>+ Effect.succeed([+ {+ headObject: (key: string) =>+ key === thumbnailKey+ ? mocks.head()+ : Effect.succeed({ ContentLength: 4096 }),+ },+ ]),+ },+}));+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));+vi.mock("@/lib/comment-media", () => ({ sanitizeWaveform: () => undefined }));+vi.mock("@/lib/media-comments", () => ({+ canUseMediaComments: async () => true,+}));+vi.mock("@/lib/Notification", () => ({ createNotification: vi.fn() }));+vi.mock("@/lib/server", () => ({ runPromiseExit: Effect.runPromiseExit }));++import { newMediaComment } from "@/actions/videos/new-media-comment";++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 },+ });+}++async function postComment() {+ return newMediaComment({+ videoId: "video-1" as never,+ commentId: "comment-1" as never,+ uploadToken: "token",+ kind: "video",+ durationSeconds: 5,+ parentCommentId: "" as never,+ timestamp: null,+ hasThumbnail: true,+ authorImage: null,+ });+}++function savedThumbnailKey() {+ return mocks.insert.mock.calls[0]?.[0]?.mediaMeta?.thumbnailKey;+}++describe("newMediaComment thumbnail check", () => {+ beforeEach(() => {+ mocks.head.mockReset();+ mocks.insert.mockReset().mockResolvedValue(undefined);+ });++ it("keeps the thumbnail when its HEAD request fails transiently", async () => {+ mocks.head.mockReturnValue(+ Effect.fail(storageError(s3Error("ServiceUnavailable", 503))),+ );++ await postComment();++ expect(savedThumbnailKey()).toBe(thumbnailKey);+ });++ it("keeps the thumbnail when its HEAD request hits a network error", async () => {+ mocks.head.mockReturnValue(+ Effect.fail(storageError(new Error("socket hang up"))),+ );++ await postComment();++ expect(savedThumbnailKey()).toBe(thumbnailKey);+ });++ it("drops a thumbnail that storage reports missing", async () => {+ mocks.head.mockReturnValue(+ Effect.fail(storageError(s3Error("NotFound", 404))),+ );++ await postComment();++ expect(mocks.insert).toHaveBeenCalledOnce();+ expect(savedThumbnailKey()).toBeUndefined();+ });++ it("drops a thumbnail that Google Drive reports missing", async () => {+ mocks.head.mockReturnValue(+ Effect.fail({+ _tag: "StorageError",+ cause: Object.assign(new Error("Storage object not found"), {+ name: "GoogleDriveRequestError",+ status: 404,+ }),+ }),+ );++ await postComment();++ expect(mocks.insert).toHaveBeenCalledOnce();+ expect(savedThumbnailKey()).toBeUndefined();+ });++ it("keeps a thumbnail that exists", async () => {+ mocks.head.mockReturnValue(Effect.succeed({ ContentLength: 128 }));++ await postComment();++ expect(savedThumbnailKey()).toBe(thumbnailKey);+ });+});diff --git a/apps/web/actions/videos/new-media-comment.ts b/apps/web/actions/videos/new-media-comment.tsindex 70b562927..2461b0a6c 100644--- a/apps/web/actions/videos/new-media-comment.ts+++ b/apps/web/actions/videos/new-media-comment.ts@@ -18,6 +18,7 @@ import { sanitizeWaveform } from "@/lib/comment-media";import { canUseMediaComments } from "@/lib/media-comments";import { createNotification } from "@/lib/Notification";import * as EffectRuntime from "@/lib/server";+import { isStorageObjectNotFound } from "@/lib/storage-not-found";export async function newMediaComment(data: {videoId: Video.VideoId;@@ -87,7 +88,9 @@ export async function newMediaComment(data: {// A missing thumbnail degrades the card, it doesn't block the comment.const thumbnailExists = yield* bucket.headObject(thumbnailKey).pipe(Effect.map(() => true),- Effect.catchAll(() => Effect.succeed(false)),+ Effect.catchAll((error) =>+ Effect.succeed(!isStorageObjectNotFound(error)),+ ),);if (!thumbnailExists) thumbnailKey = null;}diff --git a/apps/web/lib/storage-not-found.ts b/apps/web/lib/storage-not-found.tsnew file mode 100644index 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;+}diff --git a/apps/web/workflows/import-loom-video.ts b/apps/web/workflows/import-loom-video.tsindex e821e92d8..369f62464 100644--- a/apps/web/workflows/import-loom-video.ts+++ b/apps/web/workflows/import-loom-video.ts@@ -11,6 +11,7 @@ import {createMediaServerCapacityError,isMediaServerCapacityError,} from "@/lib/media-server-backpressure";+import { isStorageObjectNotFound } from "@/lib/storage-not-found";import { runWorkflowPromise } from "@/lib/workflow-runtime";import {type ProcessedVideoMetadata,@@ -290,12 +291,11 @@ async function hasExistingLoomUpload(metadata: video.metadata,});const [bucket] = yield* Storage.getAccessForVideo(videoDomain);- const object = yield* bucket.headObject(payload.rawFileKey);- return (object.ContentLength ?? 0) >= MINIMUM_VIDEO_SIZE;- }).pipe(- Effect.catchAll(() => Effect.succeed(false)),- runWorkflowPromise,- );+ return yield* bucket.headObject(payload.rawFileKey).pipe(+ Effect.map((object) => (object.ContentLength ?? 0) >= MINIMUM_VIDEO_SIZE),+ Effect.catchIf(isStorageObjectNotFound, () => Effect.succeed(false)),+ );+ }).pipe(runWorkflowPromise);}async function waitForRetry(delayMs: number): Promise<void> {