Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Fix the sync utm cron job

Kiran Kfceb828c3097
diff --git a/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts b/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
index 452d449e31..e015dfc0c5 100644
--- a/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
+++ b/apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
@@ -1,57 +1,65 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
+import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { recordLink } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
-import { chunk, constructURLFromUTMParams, log } from "@dub/utils";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ chunk,
+ constructURLFromUTMParams,
+ isFulfilled,
+ log,
+} from "@dub/utils";
import { z } from "zod";
import { logAndRespond } from "../../utils";
export const dynamic = "force-dynamic";
const PAGE_SIZE = 100;
+const MAX_BATCH = 10;
-const payloadSchema = z.object({
- groupId: z.string(),
+const schema = z.object({
+ utmTemplateId: z.string(),
+ cursor: z.string().optional(),
});
+/**
+ * Syncs UTM parameters from a UTM template to all partner links in a group.
+ * This job is triggered when a UTM template associated with a partner group is updated.
+ */
+
// POST /api/cron/groups/sync-utm
export async function POST(req: Request) {
try {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- const { groupId } = payloadSchema.parse(JSON.parse(rawBody));
+ const { utmTemplateId, cursor } = schema.parse(JSON.parse(rawBody));
- // Find the group
- const group = await prisma.partnerGroup.findUnique({
+ // Find the UTM template
+ const utmTemplate = await prisma.utmTemplate.findUnique({
where: {
- id: groupId,
+ id: utmTemplateId,
+ },
+ include: {
+ partnerGroup: true,
},
});
- if (!group) {
- return logAndRespond(`Group ${groupId} not found. Skipping...`, {
- logLevel: "error",
- });
- }
-
- if (!group.utmTemplateId) {
+ if (!utmTemplate) {
return logAndRespond(
- `Group ${groupId} does not have a UTM template. Skipping...`,
- { logLevel: "error" },
+ `UTM template ${utmTemplateId} not found. Skipping...`,
+ {
+ logLevel: "error",
+ },
);
}
- // Find the UTM template
- const utmTemplate = await prisma.utmTemplate.findUnique({
- where: {
- id: group.utmTemplateId,
- },
- });
+ const { partnerGroup: group } = utmTemplate;
- if (!utmTemplate) {
+ if (!group) {
return logAndRespond(
- `UTM template ${group.utmTemplateId} not found. Skipping...`,
+ `UTM template ${utmTemplateId} doesn't associate with a group. Skipping...`,
{
logLevel: "error",
},
@@ -68,15 +76,21 @@ export async function POST(req: Request) {
ref: utmTemplate.ref,
} as Record<string, string>;
- let currentPage = 0;
+ let hasMore = true;
+ let currentCursor = cursor;
+ let processedBatches = 0;
- while (true) {
- // Find the partners in the group along with their links
+ while (processedBatches < MAX_BATCH) {
+ // Find partners in the group
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
+ ...(currentCursor && {
+ id: {
+ gt: currentCursor,
+ },
+ }),
groupId: group.id,
},
- skip: currentPage * PAGE_SIZE,
take: PAGE_SIZE,
orderBy: {
id: "asc",
@@ -91,24 +105,21 @@ export async function POST(req: Request) {
},
});
- // If no more enrollments, break
if (programEnrollments.length === 0) {
+ hasMore = false;
break;
}
- currentPage = currentPage + 1;
-
- // Array of partner links
+ // Extract links from the program enrollments
const links = programEnrollments.flatMap((enrollment) =>
enrollment.links.map((link) => link),
);
- // Split this into chunks of 100 links
const linkChunks = chunk(links, 100);
// Update the UTM for each partner links in the group
for (const linkChunk of linkChunks) {
- const updatedLinks = await Promise.all(
+ const updatedLinksPromises = await Promise.allSettled(
linkChunk.map((link) =>
prisma.link.update({
where: {
@@ -122,21 +133,47 @@ export async function POST(req: Request) {
utm_term: utmTemplate.utm_term || null,
utm_content: utmTemplate.utm_content || null,
},
+ include: {
+ tags: {
+ select: {
+ tag: true,
+ },
+ },
+ },
}),
),
);
+ const updatedLinks = updatedLinksPromises
+ .filter(isFulfilled)
+ .map(({ value }) => value);
+
await Promise.allSettled([
recordLink(updatedLinks),
linkCache.expireMany(updatedLinks),
]);
}
+
+ // Update cursor to the last processed record
+ currentCursor = programEnrollments[programEnrollments.length - 1].id;
+ processedBatches++;
+ }
+
+ if (hasMore) {
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/sync-utm`,
+ method: "POST",
+ body: {
+ utmTemplateId,
+ cursor: currentCursor,
+ },
+ });
}
- return logAndRespond(`Synced UTM for group ${groupId}.`);
+ return logAndRespond(`Finished syncing UTM for the partner's links.`);
} catch (error) {
await log({
- message: `Error handling "groups/sync-utm" ${error.message}.`,
+ message: `Error updating UTM for the partner's links: ${error.message}.`,
type: "errors",
});
diff --git a/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts b/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts
index 6027a38ba9..1ba7242e18 100644
--- a/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts
+++ b/apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts
@@ -2,6 +2,7 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { recordLink } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
import {
APP_DOMAIN_WITH_NGROK,
@@ -78,16 +79,6 @@ export async function POST(req: Request) {
`Updating default links for the partners (defaultLinkId=${defaultLink.id}, groupId=${group.id}).`,
);
- // Find the workspace & program
- const { workspace, ...program } = await prisma.program.findUniqueOrThrow({
- where: {
- id: group.programId,
- },
- include: {
- workspace: true,
- },
- });
-
let hasMore = true;
let currentCursor = cursor;
let processedBatches = 0;
@@ -161,9 +152,12 @@ export async function POST(req: Request) {
domain: link.domain,
shortLink: link.shortLink,
},
- select: {
- domain: true,
- key: true,
+ include: {
+ tags: {
+ select: {
+ tag: true,
+ },
+ },
},
}),
),
@@ -173,7 +167,10 @@ export async function POST(req: Request) {
.filter(isFulfilled)
.map((link) => link.value);
- await linkCache.expireMany(updatedLinks);
+ await Promise.allSettled([
+ recordLink(updatedLinks),
+ linkCache.expireMany(updatedLinks),
+ ]);
// Update cursor to the last processed record
currentCursor = links[links.length - 1].id;
diff --git a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
index cc1cedac10..0abce47dcf 100644
--- a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
+++ b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
@@ -152,7 +152,7 @@ export const PATCH = withWorkspace(
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/sync-utm`,
body: {
- groupId: group.id,
+ utmTemplateId: group.utmTemplateId,
},
}),
]),
diff --git a/apps/web/app/api/utm/[id]/route.ts b/apps/web/app/api/utm/[id]/route.ts
index 21ddc61b17..7ebc0981a9 100644
--- a/apps/web/app/api/utm/[id]/route.ts
+++ b/apps/web/app/api/utm/[id]/route.ts
@@ -51,7 +51,7 @@ export const PATCH = withWorkspace(
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/groups/sync-utm`,
body: {
- groupId: template.partnerGroup.id,
+ utmTemplateId: template.id,
},
}),
);