|
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"; |
4 | 2 | import { prisma } from "~/db.server";
|
| 3 | +import { generateFriendlyId } from "~/v3/friendlyIdentifiers"; |
5 | 4 |
|
6 | 5 | export const MAX_TAGS_PER_RUN = 10;
|
| 6 | +const MAX_RETRIES = 3; |
7 | 7 |
|
8 | 8 | export async function createTag({ tag, projectId }: { tag: string; projectId: string }) {
|
9 | 9 | if (tag.trim().length === 0) return;
|
10 | 10 |
|
| 11 | + let attempts = 0; |
11 | 12 | const friendlyId = generateFriendlyId("runtag");
|
12 |
| - const now = new Date(); |
13 |
| - const id = cuid(); |
14 | 13 |
|
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 | + } |
26 | 42 | }
|
27 | 43 |
|
28 | 44 | export async function getTagsForRunId({
|
|
0 commit comments