Merge pull request 'fix(archive): recover from P2002 race on cloud create in walk (BIT-33532)' (#323) from fix/BIT-33532-cloudfile-p2002-race into main
ci / rust (push) Successful in 5m44s
ci / typescript (push) Successful in 12m43s

This commit was merged in pull request #323.
This commit is contained in:
spark committed 2026-12-04 10:02:58 +00:00
commit 7b1596d8fa
2 files changed
+127 -7

No files matched your search

+94
View File
@@ -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<void> }).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<void> }).walk(
{ id: "src-1", rootPath: "/root", secretEnc: "x" },
client,
"/root",
null,
{ folders: 0, queued: 0 },
false,
),
).rejects.toThrow("boom");
});
});
+33 -7
View File
@@ -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 } });