From 5287afb508a3759041df63bc6912bed1885851d5 Mon Sep 17 00:00:00 2001 From: paula-alves Date: Fri, 4 Dec 2026 09:43:33 +0000 Subject: [PATCH] fix(archive): recover from P2002 race on cloud create in walk (BIT-33532) ArchiveService.walk used a check-then-create pattern for cloudFolder, cloudFile and cloudVideo. When two concurrent passes (overlapping scans or a folder reachable through two paths) both query existing rows before either creates, the second create hits P2002 on @@unique([sourceId, fileId]) and aborts the whole scan, marking the source ERROR. Wrap each create in try/catch for P2002 and fall back to an update on the sourceId_fileId compound key, so a race no longer fails the scan. Adds vitest cases proving the cloudFile fallback updates the compound key and requeues, and that non-P2002 errors still rethrow. Paperclip-Issue: BIT-33532 --- apps/api/src/archive/service.test.ts | 94 ++++++++++++++++++++++++++++ apps/api/src/archive/service.ts | 40 +++++++++--- 2 files changed, 127 insertions(+), 7 deletions(-) diff --git a/apps/api/src/archive/service.test.ts b/apps/api/src/archive/service.test.ts index 09d5b8d..22d1ab1 100644 --- a/apps/api/src/archive/service.test.ts +++ b/apps/api/src/archive/service.test.ts @@ -206,3 +206,97 @@ describe("takeOffFutureGames stops and downgrades an unreachable database (BIT-3 expect(log.calls.some((c) => c.level === "warn" && /not moved/.test(c.msg))).toBe(false); }); }); + +describe("walk recovers from a P2002 race on cloudFile.create (BIT-33532)", () => { + it("falls back to update on the compound key and still queues", async () => { + const createCalls: unknown[] = []; + const updateCalls: unknown[] = []; + const db = { + cloudFolder: { + findUnique: async () => null, + create: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }), + update: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }), + findMany: async () => [], + }, + cloudFile: { + findMany: async () => [], + create: async (args: unknown) => { + createCalls.push(args); + throw Object.assign(new Error("Unique constraint failed on the constraint: cloud_files_source_id_file_id_key"), { code: "P2002" }); + }, + update: async (args: unknown) => { + updateCalls.push(args); + return { id: "cf-1" }; + }, + deleteMany: async () => ({ count: 0 }), + }, + cloudVideo: { + findMany: async () => [], + deleteMany: async () => ({ count: 0 }), + }, + }; + const client = { + list: async () => ({ + self: { path: "/root", name: "root", fileId: "fld-1", etag: "fe1", size: 0, isDir: true, contentType: null, modifiedAt: null }, + children: [{ path: "/root/a.jpg", name: "a.jpg", fileId: "img-1", etag: "ie1", size: 100, isDir: false, contentType: "image/jpeg", modifiedAt: null }], + }), + }; + const service = new ArchiveService({ db, log: { info() {}, debug() {}, error() {}, warn() {} } } as never); + const stats = { folders: 0, queued: 0 }; + await (service as unknown as { walk: (source: unknown, client: unknown, folderPath: string, parent: unknown, stats: { folders: number; queued: number }, full: boolean, seen?: unknown) => Promise }).walk( + { id: "src-1", rootPath: "/root", secretEnc: "x" }, + client, + "/root", + null, + stats, + false, + ); + expect(createCalls).toHaveLength(1); + expect(updateCalls).toHaveLength(1); + const update = updateCalls[0] as { where: { sourceId_fileId: { sourceId: string; fileId: string } }; data: { folderId: string; etag: string } }; + expect(update.where.sourceId_fileId).toEqual({ sourceId: "src-1", fileId: "img-1" }); + expect(update.data.folderId).toBe("fld-1"); + expect(update.data.etag).toBe("ie1"); + expect(stats.queued).toBe(1); + }); + + it("rethrows non-P2002 errors from cloudFile.create", async () => { + const db = { + cloudFolder: { + findUnique: async () => null, + create: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }), + update: async () => ({ id: "fld-1", eventId: "evt-1", matchedBy: null, path: "/root", parentId: null }), + findMany: async () => [], + }, + cloudFile: { + findMany: async () => [], + create: async () => { + throw Object.assign(new Error("boom"), { code: "P2025" }); + }, + update: async () => ({ id: "cf-1" }), + deleteMany: async () => ({ count: 0 }), + }, + cloudVideo: { + findMany: async () => [], + deleteMany: async () => ({ count: 0 }), + }, + }; + const client = { + list: async () => ({ + self: { path: "/root", name: "root", fileId: "fld-1", etag: "fe1", size: 0, isDir: true, contentType: null, modifiedAt: null }, + children: [{ path: "/root/a.jpg", name: "a.jpg", fileId: "img-1", etag: "ie1", size: 100, isDir: false, contentType: "image/jpeg", modifiedAt: null }], + }), + }; + const service = new ArchiveService({ db, log: { info() {}, debug() {}, error() {}, warn() {} } } as never); + await expect( + (service as unknown as { walk: (source: unknown, client: unknown, folderPath: string, parent: unknown, stats: { folders: number; queued: number }, full: boolean, seen?: unknown) => Promise }).walk( + { id: "src-1", rootPath: "/root", secretEnc: "x" }, + client, + "/root", + null, + { folders: 0, queued: 0 }, + false, + ), + ).rejects.toThrow("boom"); + }); +}); diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index f3207e6..3dfde94 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -371,11 +371,19 @@ export class ArchiveService { if (known.parentId !== (parent?.id ?? null)) await db.cloudFolder.update({ where: { id: known.id }, data: { parentId: parent?.id ?? null } }); return; } - let folder = known - ? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } }) - : await db.cloudFolder.create({ - data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) }, - }); + let folder: CloudFolder; + if (known) { + folder = await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } }); + } else { + const data = { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) }; + try { + folder = await db.cloudFolder.create({ data }); + } catch (err) { + // A concurrent walk pass may have inserted this folder between our findUnique and create (BIT-33532). + if ((err as { code?: string }).code !== "P2002") throw err; + folder = await db.cloudFolder.update({ where: { sourceId_fileId: { sourceId: source.id, fileId: self.fileId } }, data }); + } + } const dirs = children.filter((c) => c.isDir); const images = children.filter((c) => !c.isDir && IMAGE.test(c.name)); @@ -387,7 +395,16 @@ export class ArchiveService { for (const img of images) { const f = byId.get(img.fileId); if (!f) { - await db.cloudFile.create({ data: { sourceId: source.id, folderId: folder.id, fileId: img.fileId, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size) } }); + try { + await db.cloudFile.create({ data: { sourceId: source.id, folderId: folder.id, fileId: img.fileId, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size) } }); + } catch (err) { + // A concurrent walk pass may have inserted this file between our findMany and create (BIT-33532). + if ((err as { code?: string }).code !== "P2002") throw err; + await db.cloudFile.update({ + where: { sourceId_fileId: { sourceId: source.id, fileId: img.fileId } }, + data: { folderId: folder.id, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size) }, + }); + } stats.queued++; } else if (f.etag !== img.etag) { await db.cloudFile.update({ where: { id: f.id }, data: { folderId: folder.id, path: img.path, etag: img.etag, size: img.size === null ? null : BigInt(img.size), status: "PENDING", attempts: 0, error: null } }); @@ -405,7 +422,16 @@ export class ArchiveService { const v = videoById.get(vid.fileId); const size = vid.size === null ? null : BigInt(vid.size); if (!v) { - await db.cloudVideo.create({ data: { sourceId: source.id, folderId: folder.id, fileId: vid.fileId, path: vid.path, etag: vid.etag, size } }); + try { + await db.cloudVideo.create({ data: { sourceId: source.id, folderId: folder.id, fileId: vid.fileId, path: vid.path, etag: vid.etag, size } }); + } catch (err) { + // A concurrent walk pass may have inserted this video between our findMany and create (BIT-33532). + if ((err as { code?: string }).code !== "P2002") throw err; + await db.cloudVideo.update({ + where: { sourceId_fileId: { sourceId: source.id, fileId: vid.fileId } }, + data: { folderId: folder.id, path: vid.path, etag: vid.etag, size }, + }); + } stats.queued++; } else if (v.etag !== vid.etag) { await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path, etag: vid.etag, size, status: "PENDING", attempts: 0, error: null } }); -- 2.47.3