Skip to content

Commit 68d8c3e

Browse files
committed
Another attempt at fixing createTag, this time doing retries in code on conflicts
1 parent 07ae802 commit 68d8c3e

File tree

1 file changed

+32
-16
lines changed

1 file changed

+32
-16
lines changed

apps/webapp/app/models/taskRunTag.server.ts

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,44 @@
1-
import { Prisma, type PrismaClientOrTransaction } from "@trigger.dev/database";
2-
import { generateFriendlyId } from "~/v3/friendlyIdentifiers";
3-
import cuid from "cuid";
1+
import { Prisma } from "@trigger.dev/database";
42
import { prisma } from "~/db.server";
3+
import { generateFriendlyId } from "~/v3/friendlyIdentifiers";
54

65
export const MAX_TAGS_PER_RUN = 10;
6+
const MAX_RETRIES = 3;
77

88
export async function createTag({ tag, projectId }: { tag: string; projectId: string }) {
99
if (tag.trim().length === 0) return;
1010

11+
let attempts = 0;
1112
const friendlyId = generateFriendlyId("runtag");
12-
const now = new Date();
13-
const id = cuid();
1413

15-
return await prisma
16-
.$queryRaw<Array<{ id: string; friendlyId: string; name: string; projectId: string }>>(
17-
Prisma.sql`
18-
INSERT INTO "TaskRunTag" ("id", "friendlyId", "name", "projectId", "createdAt")
19-
VALUES (${id}, ${friendlyId}, ${tag}, ${projectId}, ${now})
20-
ON CONFLICT ("projectId", "name")
21-
DO UPDATE SET "friendlyId" = "TaskRunTag"."friendlyId"
22-
RETURNING "id", "friendlyId", "name", "projectId"
23-
`
24-
)
25-
.then((rows) => rows[0]);
14+
while (attempts < MAX_RETRIES) {
15+
try {
16+
return await prisma.taskRunTag.upsert({
17+
where: {
18+
projectId_name: {
19+
projectId,
20+
name: tag,
21+
},
22+
},
23+
create: {
24+
friendlyId,
25+
name: tag,
26+
projectId,
27+
},
28+
update: {},
29+
});
30+
} catch (error) {
31+
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") {
32+
// Handle unique constraint violation (conflict)
33+
attempts++;
34+
if (attempts >= MAX_RETRIES) {
35+
throw new Error(`Failed to create tag after ${MAX_RETRIES} attempts due to conflicts.`);
36+
}
37+
} else {
38+
throw error; // Re-throw other errors
39+
}
40+
}
41+
}
2642
}
2743

2844
export async function getTagsForRunId({

0 commit comments

Comments
 (0)