Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: hold a per-video claim while moving a Loom import

Richie McIlroy2b8c3d37a32e
diff --git a/apps/web/__tests__/unit/loom-operator-tools.test.ts b/apps/web/__tests__/unit/loom-operator-tools.test.ts
index bb61e5314..357e03434 100644
--- a/apps/web/__tests__/unit/loom-operator-tools.test.ts
+++ b/apps/web/__tests__/unit/loom-operator-tools.test.ts
@@ -18,6 +18,8 @@ const mocks = vi.hoisted(() => ({
puts: [] as Array<[string, string]>,
stored: new Map<string, string>(),
deleteFails: false,
+ claims: [] as Array<Record<string, unknown>>,
+ claimRows: 1,
}));
vi.mock("server-only", () => ({}));
@@ -47,6 +49,14 @@ vi.mock("@cap/database", () => {
return {
db: () => ({
select: () => selection,
+ update: () => ({
+ set: (values: Record<string, unknown>) => ({
+ where: async () => {
+ mocks.claims.push(values);
+ return [{ affectedRows: mocks.claimRows }];
+ },
+ }),
+ }),
transaction: async (run: (handle: typeof tx) => Promise<unknown>) =>
run(tx),
}),
@@ -202,6 +212,8 @@ beforeEach(() => {
mocks.puts = [];
mocks.stored = new Map();
mocks.deleteFails = false;
+ mocks.claims = [];
+ mocks.claimRows = 1;
});
describe("operator CSV import", () => {
@@ -310,6 +322,24 @@ describe("reassignLoomImport", () => {
expect(mocks.updates).toEqual([]);
});
+ it("does not touch a video another move has claimed", async () => {
+ mocks.selects = [[importedVideo()], [{ userId: ids.to }]];
+ mocks.claimRows = 0;
+ await expect(reassignLoomImport(input)).resolves.toMatchObject({
+ status: "skipped",
+ reason: "another move is running",
+ });
+ expect(mocks.copies).toEqual([]);
+ expect(mocks.removed).toEqual([]);
+ });
+
+ it("releases its claim after a failed move", async () => {
+ mocks.selects = [[importedVideo()], [{ userId: ids.to }]];
+ mocks.headSize = 1;
+ await expect(reassignLoomImport(input)).rejects.toThrow();
+ expect(mocks.claims).toHaveLength(2);
+ });
+
it("re-encrypts the word transcript for the new owner", async () => {
const key = getEditTranscriptObjectKey(ids.from, ids.video);
mocks.objects.push({ Key: key, Size: 50 });
diff --git a/apps/web/lib/loom-import-reassign.ts b/apps/web/lib/loom-import-reassign.ts
index 9cc65c4d3..66365f47b 100644
--- a/apps/web/lib/loom-import-reassign.ts
+++ b/apps/web/lib/loom-import-reassign.ts
@@ -1,5 +1,6 @@
import "server-only";
+import { randomUUID } from "node:crypto";
import { db } from "@cap/database";
import {
importedVideos,
@@ -11,7 +12,7 @@ import {
} from "@cap/database/schema";
import { Storage } from "@cap/web-backend";
import { Organisation, User, Video } from "@cap/web-domain";
-import { and, eq } from "drizzle-orm";
+import { and, eq, sql } from "drizzle-orm";
import { Option } from "effect";
import { getEditTranscriptObjectKey } from "@/lib/edit-transcript";
import {
@@ -29,6 +30,8 @@ export type LoomReassignOutcome =
}
| { videoId: string; status: "skipped" | "failed"; reason: string };
+const CLAIM_TTL_MS = 60 * 60 * 1000;
+
function getAffectedRows(result: unknown) {
const header = Array.isArray(result) ? result[0] : result;
return (header as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
@@ -139,6 +142,61 @@ export async function reassignLoomImport({
if (!member)
return { videoId, status: "skipped", reason: "new owner not a member" };
+ const token = randomUUID();
+ const claimedAt = new Date();
+ const claim = await db()
+ .update(videos)
+ .set({
+ metadata: sql`JSON_SET(COALESCE(${videos.metadata}, JSON_OBJECT()), '$.loomReassignClaim', JSON_OBJECT('token', ${token}, 'at', ${claimedAt.toISOString()}))`,
+ })
+ .where(
+ and(
+ eq(videos.id, id),
+ eq(videos.ownerId, User.UserId.make(fromUserId)),
+ sql`(JSON_EXTRACT(${videos.metadata}, '$.loomReassignClaim') IS NULL OR JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.loomReassignClaim.at')) < ${new Date(claimedAt.getTime() - CLAIM_TTL_MS).toISOString()})`,
+ ),
+ );
+ if (getAffectedRows(claim) !== 1)
+ return { videoId, status: "skipped", reason: "another move is running" };
+ try {
+ return await moveClaimedVideo({
+ id,
+ videoId,
+ organizationId,
+ fromUserId,
+ toUserId,
+ token,
+ });
+ } finally {
+ await db()
+ .update(videos)
+ .set({
+ metadata: sql`JSON_REMOVE(${videos.metadata}, '$.loomReassignClaim')`,
+ })
+ .where(
+ and(
+ eq(videos.id, id),
+ sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.loomReassignClaim.token')) = ${token}`,
+ ),
+ );
+ }
+}
+
+async function moveClaimedVideo({
+ id,
+ videoId,
+ organizationId,
+ fromUserId,
+ toUserId,
+ token,
+}: {
+ id: Video.VideoId;
+ videoId: string;
+ organizationId: string;
+ fromUserId: string;
+ toUserId: string;
+ token: string;
+}): Promise<LoomReassignOutcome> {
const source = await listObjects(videoId, fromUserId, organizationId);
if (source.objects.length === 0)
return { videoId, status: "failed", reason: "no media found" };
@@ -213,6 +271,7 @@ export async function reassignLoomImport({
and(
eq(videos.id, id),
eq(videos.ownerId, User.UserId.make(fromUserId)),
+ sql`JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.loomReassignClaim.token')) = ${token}`,
),
);
if (getAffectedRows(result) !== 1) return false;