Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: resume recordings after daily transfer capacity resets
Richie McIlroyb5ed02ca55c9
diff --git a/apps/web/__tests__/unit/desktop-recording-jobs.test.ts b/apps/web/__tests__/unit/desktop-recording-jobs.test.tsindex 5a87cf19a..1cd3f06f4 100644--- a/apps/web/__tests__/unit/desktop-recording-jobs.test.ts+++ b/apps/web/__tests__/unit/desktop-recording-jobs.test.ts@@ -5,6 +5,7 @@ import {claimProcessingAttempt,type DesktopRecordingAttemptFence,type DesktopRecordingJob,+ deferForDailyProcessingBudget,ensureSegmentProcessingJob,getDesktopRecordingRetryDelay,getDesktopRecordingWorkerCheckpoint,@@ -600,6 +601,69 @@ describe("late verification and source commitment", () => {});describe("retained-source retry policy", () => {+ it("waits for the next UTC allowance without spending the final attempt", async () => {+ await createAttempt();+ Object.assign(getJobRow(), {+ state: "processing",+ source,+ attemptId: "budget-attempt",+ attemptCount: 5,+ remoteJobId: null,+ });+ const fence = {+ videoId,+ generation: String(getJobRow().generation),+ attemptId: "budget-attempt",+ };+ expect(await deferForDailyProcessingBudget({ ...fence, now })).toBe(true);+ expect(await deferForDailyProcessingBudget({ ...fence, now })).toBe(false);+ expect(getJobRow()).toMatchObject({+ state: "retry",+ attemptCount: 4,+ source,+ nextRetryAt: new Date("2026-09-03T00:00:00Z"),+ leaseExpiresAt: null,+ });+ expect(+ await claimProcessingAttempt({+ videoId,+ generation: fence.generation,+ now,+ }),+ ).toBeNull();+ expect(+ await claimProcessingAttempt({+ videoId,+ generation: fence.generation,+ now: new Date("2026-09-03T00:00:00Z"),+ }),+ ).toMatchObject({ attemptCount: 5, state: "processing", source });+ });++ it("does not defer an attempt already owned by a remote worker", async () => {+ await createAttempt();+ Object.assign(getJobRow(), {+ state: "processing",+ source,+ attemptId: "owned",+ attemptCount: 5,+ remoteJobId: "worker",+ });+ expect(+ await deferForDailyProcessingBudget({+ videoId,+ generation: String(getJobRow().generation),+ attemptId: "owned",+ now,+ }),+ ).toBe(false);+ expect(getJobRow()).toMatchObject({+ state: "processing",+ attemptCount: 5,+ remoteJobId: "worker",+ });+ });+it.each([null, source])("does not recreate a recording while deletion is pending",async (retainedSource) => {diff --git a/apps/web/__tests__/unit/finalize-desktop-recording.test.ts b/apps/web/__tests__/unit/finalize-desktop-recording.test.tsindex d4745e61f..5dd648595 100644--- a/apps/web/__tests__/unit/finalize-desktop-recording.test.ts+++ b/apps/web/__tests__/unit/finalize-desktop-recording.test.ts@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({retry: vi.fn(),attach: vi.fn(),defer: vi.fn(),+ deferBudget: vi.fn(),commitSource: vi.fn(),checkpoint: vi.fn(),saveCheckpoint: vi.fn(),@@ -32,7 +33,11 @@ const mocks = vi.hoisted(() => ({}));vi.mock("@/lib/media-processing-budget", () => ({reserveMediaProcessingBudget: mocks.reserveBudget,- MediaProcessingBudgetError: class extends Error {},+ MediaProcessingBudgetError: class extends Error {+ constructor(readonly scope: "daily" | "recording") {+ super(scope);+ }+ },}));vi.mock("@cap/database", () => ({db: () => ({@@ -59,6 +64,7 @@ vi.mock("@/lib/desktop-recording-jobs", () => ({scheduleRetry: mocks.retry,attachRemoteJob: mocks.attach,deferWithoutMediaServer: mocks.defer,+ deferForDailyProcessingBudget: mocks.deferBudget,}));vi.mock("@/lib/desktop-recording-source", () => ({advanceDesktopRecordingSourceCommit: mocks.commitSource,@@ -197,6 +203,17 @@ beforeEach(() => {withCurrent({ remoteJobId });return true;});+ mocks.deferBudget.mockImplementation(async () => {+ const nextRetryAt = new Date();+ nextRetryAt.setUTCHours(24, 0, 0, 0);+ withCurrent({+ state: "retry",+ leaseExpiresAt: null,+ nextRetryAt,+ attemptCount: (current?.attemptCount ?? 1) - 1,+ });+ return true;+ });mocks.defer.mockImplementation(async () => {withCurrent({ state: "queued", leaseExpiresAt: null });return true;@@ -508,8 +525,44 @@ describe("source commitment and media request compatibility", () => {expect(mocks.fetch).not.toHaveBeenCalled();});+ it("sleeps through exhausted days and resumes processing automatically", async () => {+ withCurrent({ state: "retry", leaseExpiresAt: null, attemptCount: 4 });+ for (let day = 0; day < 7; day++) {+ mocks.reserveBudget.mockRejectedValueOnce(+ new MediaProcessingBudgetError("daily"),+ );+ }+ await expect(+ finalizeDesktopRecordingWorkflow({+ videoId,+ userId,+ generation: fixture.generation,+ }),+ ).resolves.toMatchObject({ success: true });+ expect(mocks.deferBudget).toHaveBeenCalledTimes(7);+ expect(+ mocks.sleep.mock.calls.filter(([delay]) => delay instanceof Date),+ ).toHaveLength(7);+ expect(current?.attemptCount).toBe(5);+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ expect(mocks.blocked).not.toHaveBeenCalled();+ });++ it("defers daily exhaustion without dispatching or permanently blocking the source", async () => {+ mocks.reserveBudget.mockRejectedValueOnce(+ new MediaProcessingBudgetError("daily"),+ );+ await expect(startDesktopRecordingJob(fixture)).resolves.toEqual({+ status: "deferred",+ });+ expect(mocks.deferBudget).toHaveBeenCalledWith(fixture);+ expect(mocks.blocked).not.toHaveBeenCalled();+ expect(mocks.fetch).not.toHaveBeenCalled();+ expect(mocks.put).not.toHaveBeenCalled();+ });+it("blocks an exhausted transfer budget before dispatching media work", async () => {- const error = new MediaProcessingBudgetError("daily");+ const error = new MediaProcessingBudgetError("recording");mocks.reserveBudget.mockRejectedValueOnce(error);await expect(startDesktopRecordingJob(fixture)).rejects.toBe(error);expect(mocks.blocked).toHaveBeenCalledWith(diff --git a/apps/web/lib/desktop-recording-jobs.ts b/apps/web/lib/desktop-recording-jobs.tsindex fef2fb35f..dd95f644b 100644--- a/apps/web/lib/desktop-recording-jobs.ts+++ b/apps/web/lib/desktop-recording-jobs.ts@@ -677,6 +677,54 @@ export async function heartbeatAttempt({});}+export async function deferForDailyProcessingBudget({+ now = new Date(),+ ...fence+}: DesktopRecordingAttemptFence & { now?: Date }): Promise<boolean> {+ return db().transaction(async (tx) => {+ const condition = and(+ attemptCondition(fence),+ isNull(videoProcessingJobs.remoteJobId),+ );+ const [row] = await tx+ .select()+ .from(videoProcessingJobs)+ .where(condition)+ .for("update");+ if (+ !row ||+ getDesktopRecordingWorkerCheckpoint(parseDesktopRecordingJob(row))+ )+ return false;+ const nextRetryAt = new Date(now);+ nextRetryAt.setUTCHours(24, 0, 0, 0);+ await tx+ .update(videoProcessingJobs)+ .set({+ state: "retry",+ attemptCount: Math.max(0, row.attemptCount - 1),+ leaseExpiresAt: null,+ nextRetryAt,+ errorCode: "processing-daily-budget-exhausted",+ errorMessage:+ "Processing will resume when the daily transfer allowance resets.",+ updatedAt: now,+ })+ .where(condition);+ await tx+ .update(videoUploads)+ .set({+ phase: "processing",+ processingMessage:+ "Waiting for processing capacity. Your recording is safely stored.",+ processingError: null,+ updatedAt: now,+ })+ .where(eq(videoUploads.videoId, fence.videoId));+ return true;+ });+}+export async function scheduleRetry({errorCode,errorMessage,diff --git a/apps/web/workflows/finalize-desktop-recording.ts b/apps/web/workflows/finalize-desktop-recording.tsindex ac42c38a7..94d086f4a 100644--- a/apps/web/workflows/finalize-desktop-recording.ts+++ b/apps/web/workflows/finalize-desktop-recording.ts@@ -13,6 +13,7 @@ import {claimProcessingAttempt,type DesktopRecordingAttempt,type DesktopRecordingAttemptFence,+ deferForDailyProcessingBudget,deferWithoutMediaServer,ensureSegmentProcessingJob,getProcessingState,@@ -138,7 +139,9 @@ export async function finalizeDesktopRecordingWorkflow(mediaServerUnavailable = true;break;}- const jobId = await startDesktopRecordingJob(attempt);+ const started = await startDesktopRecordingJob(attempt);+ if (typeof started === "object") continue;+ const jobId = started;for (;;) {await sleep(COMPLETION_POLL_INTERVAL_MS);const status = await pollDesktopRecordingAttempt({@@ -406,7 +409,7 @@ async function buildDesktopSegmentsOutput({export async function startDesktopRecordingJob(attempt: DesktopRecordingAttempt,-): Promise<string | undefined> {+): Promise<string | undefined | { status: "deferred" }> {"use step";const current = await getProcessingState(attempt);@@ -414,6 +417,7 @@ export async function startDesktopRecordingJob(throw new Error("Recording processing attempt was superseded");}if (current.remoteJobId) return current.remoteJobId;+ if (current.state === "retry") return { status: "deferred" };const [video] = await db().select().from(videos)@@ -452,6 +456,10 @@ export async function startDesktopRecordingJob(});} catch (error) {if (error instanceof MediaProcessingBudgetError) {+ if (error.scope === "daily") {+ await deferForDailyProcessingBudget(attempt);+ return { status: "deferred" };+ }await markSourceBlocked({videoId: current.videoId,generation: current.generation,