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.

Migrate link tag deletion to new background job (#4188)

Kiran Kf2cfe12226e0
diff --git a/apps/web/app/(ee)/api/cron/tags/delete-link-tag/route.ts b/apps/web/app/(ee)/api/cron/tags/delete-link-tag/route.ts
index a0ca59347f..da6ec252e5 100644
--- a/apps/web/app/(ee)/api/cron/tags/delete-link-tag/route.ts
+++ b/apps/web/app/(ee)/api/cron/tags/delete-link-tag/route.ts
@@ -1,11 +1,5 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { includeProgramEnrollment } from "@/lib/api/links/include-program-enrollment";
-import { includeTags } from "@/lib/api/links/include-tags";
-import { queueLinkTagDeletion } from "@/lib/api/tags/queue-tag-deletion";
-import { CRON_BATCH_SIZE } from "@/lib/cron";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { prisma } from "@/lib/prisma";
-import { recordLink } from "@/lib/tinybird/record-link";
+import { withCron } from "@/lib/cron/with-cron";
+import { linkTagDeletedJob } from "@/lib/jobs/handlers/link-tag-deleted-job";
import * as z from "zod/v4";
import { logAndRespond } from "../../utils";
@@ -15,83 +9,20 @@ const schema = z.object({
id: z.string(),
});
-// POST /api/cron/tags/delete-link-tag
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- const { id: tagId } = schema.parse(JSON.parse(rawBody));
-
- const tag = await prisma.tag.findUnique({
- where: {
- id: tagId,
- },
- });
-
- if (!tag || tag.projectId !== null) {
- return logAndRespond(
- `Link tag ${tagId} not found or not marked for deletion. Skipping...`,
- );
- }
-
- const linkTags = await prisma.linkTag.findMany({
- where: {
- tagId,
- },
- select: {
- id: true,
- linkId: true,
- },
- take: CRON_BATCH_SIZE,
- });
-
- if (linkTags.length === 0) {
- await prisma.tag.delete({
- where: {
- id: tagId,
- },
- });
+// Legacy QStash endpoint kept for in-flight messages published before the
+// jobs migration. Forwards to linkTagDeletedJob;
- return logAndRespond(
- `No LinkTag rows left. Link tag ${tagId} deleted from database.`,
- );
- }
+// TODO: Remove this route after old QStash traffic has drained.
- const linkIds = [...new Set(linkTags.map((lt) => lt.linkId))];
-
- const { count } = await prisma.linkTag.deleteMany({
- where: {
- id: {
- in: linkTags.map((lt) => lt.id),
- },
- },
- });
-
- console.log(`Deleted ${count} link–tag associations`);
-
- const linksToUpdate = await prisma.link.findMany({
- where: {
- id: {
- in: linkIds,
- },
- },
- include: {
- ...includeTags,
- ...includeProgramEnrollment,
- },
- });
-
- console.log(`Found ${linksToUpdate.length} links to update in Tinybird`);
+// POST /api/cron/tags/delete-link-tag
+export const POST = withCron(async ({ rawBody }) => {
+ const { id: tagId } = schema.parse(JSON.parse(rawBody));
- await recordLink(linksToUpdate);
+ await linkTagDeletedJob.execute({
+ tagId,
+ });
- await queueLinkTagDeletion({
- tagId,
- delay: 2,
- });
- return logAndRespond("Batch completed, starting next batch...");
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
+ return logAndRespond(
+ `Forwarded link tag ${tagId} deletion to linkTagDeletedJob.`,
+ );
+});
diff --git a/apps/web/app/api/tags/[id]/route.ts b/apps/web/app/api/tags/[id]/route.ts
index e76ec63e4a..ec9946820d 100644
--- a/apps/web/app/api/tags/[id]/route.ts
+++ b/apps/web/app/api/tags/[id]/route.ts
@@ -1,8 +1,9 @@
import { DubApiError } from "@/lib/api/errors";
-import { markLinkTagDeleted } from "@/lib/api/tags/mark-link-tag-deleted";
import { withWorkspace } from "@/lib/auth";
+import { linkTagDeletedJob } from "@/lib/jobs/handlers/link-tag-deleted-job";
import { prisma } from "@/lib/prisma";
import { LinkTagSchema, updateTagBodySchema } from "@/lib/zod/schemas/tags";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// PATCH /api/tags/[id] – update a tag for a workspace
@@ -58,21 +59,39 @@ export const PUT = PATCH;
// DELETE /api/tags/[id] – delete a tag for a workspace
export const DELETE = withWorkspace(
async ({ params, workspace }) => {
- const { id } = params;
+ const { id: tagId } = params;
- const deleted = await markLinkTagDeleted({
- tagId: id,
- projectId: workspace.id,
+ const { count } = await prisma.tag.updateMany({
+ where: {
+ id: tagId,
+ projectId: workspace.id,
+ },
+ data: {
+ projectId: null,
+ },
});
- if (!deleted) {
+ if (count === 0) {
throw new DubApiError({
code: "not_found",
message: "Tag not found.",
});
}
- return NextResponse.json({ id });
+ waitUntil(
+ linkTagDeletedJob.dispatch(
+ {
+ tagId,
+ },
+ {
+ label: tagId,
+ },
+ ),
+ );
+
+ return NextResponse.json({
+ id: tagId,
+ });
},
{
requiredPermissions: ["tags.write"],
diff --git a/apps/web/lib/api/tags/mark-link-tag-deleted.ts b/apps/web/lib/api/tags/mark-link-tag-deleted.ts
deleted file mode 100644
index 793fecbec5..0000000000
--- a/apps/web/lib/api/tags/mark-link-tag-deleted.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { queueLinkTagDeletion } from "./queue-tag-deletion";
-
-// Mark the link tag as deleted (orphan from workspace). LinkTag rows and the
-// Tag row are removed asynchronously via a cron job.
-export async function markLinkTagDeleted({
- tagId,
- projectId,
-}: {
- tagId: string;
- projectId: string;
-}): Promise<boolean> {
- try {
- const updated = await prisma.tag.update({
- where: {
- id: tagId,
- projectId,
- },
- data: {
- projectId: null,
- },
- });
-
- if (!updated) {
- return false;
- }
-
- await queueLinkTagDeletion({
- tagId,
- });
-
- return true;
- } catch (error) {
- console.error("markLinkTagDeleted", {
- reason: error,
- tagId,
- projectId,
- });
- return false;
- }
-}
diff --git a/apps/web/lib/api/tags/queue-tag-deletion.ts b/apps/web/lib/api/tags/queue-tag-deletion.ts
deleted file mode 100644
index 6e9af100df..0000000000
--- a/apps/web/lib/api/tags/queue-tag-deletion.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { qstash } from "@/lib/cron";
-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-
-export async function queueLinkTagDeletion({
- tagId,
- delay,
-}: {
- tagId: string;
- delay?: number;
-}) {
- return await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/tags/delete-link-tag`,
- ...(delay && { delay }),
- body: {
- id: tagId,
- },
- });
-}
diff --git a/apps/web/lib/jobs/handlers/link-tag-deleted-job.ts b/apps/web/lib/jobs/handlers/link-tag-deleted-job.ts
new file mode 100644
index 0000000000..f89812ebb4
--- /dev/null
+++ b/apps/web/lib/jobs/handlers/link-tag-deleted-job.ts
@@ -0,0 +1,107 @@
+import * as z from "zod/v4";
+import { includeProgramEnrollment } from "../../api/links/include-program-enrollment";
+import { includeTags } from "../../api/links/include-tags";
+import { CRON_BATCH_SIZE } from "../../cron";
+import { prisma } from "../../prisma";
+import { recordLink } from "../../tinybird";
+import { defineJob } from "../index";
+
+const inputSchema = z.object({
+ tagId: z.string(),
+});
+
+// Job to delete a link tag and all its link associations
+export const linkTagDeletedJob = defineJob({
+ name: "link-tag-deleted-job",
+ schema: inputSchema,
+ async handle(input) {
+ const { tagId } = input;
+
+ const tag = await prisma.tag.findUnique({
+ where: {
+ id: tagId,
+ },
+ select: {
+ projectId: true,
+ },
+ });
+
+ if (!tag) {
+ console.error(
+ `[linkTagDeletedJob] Link tag ${tagId} not found. Skipping...`,
+ );
+ return;
+ }
+
+ if (tag.projectId !== null) {
+ console.error(
+ `[linkTagDeletedJob] Link tag ${tagId} not marked for deletion. Skipping...`,
+ );
+ return;
+ }
+
+ const linkTags = await prisma.linkTag.findMany({
+ where: {
+ tagId,
+ },
+ select: {
+ id: true,
+ linkId: true,
+ },
+ take: CRON_BATCH_SIZE,
+ });
+
+ if (linkTags.length > 0) {
+ const { count } = await prisma.linkTag.deleteMany({
+ where: {
+ id: {
+ in: linkTags.map((linkTag) => linkTag.id),
+ },
+ },
+ });
+
+ console.log(
+ `[linkTagDeletedJob] Deleted ${count} link–tag associations.`,
+ );
+
+ const links = await prisma.link.findMany({
+ where: {
+ id: {
+ in: [...new Set(linkTags.map((linkTag) => linkTag.linkId))],
+ },
+ },
+ include: {
+ ...includeTags,
+ ...includeProgramEnrollment,
+ },
+ });
+
+ if (links.length > 0) {
+ await recordLink(links);
+ }
+
+ // More associations remain — queue the next batch.
+ if (linkTags.length === CRON_BATCH_SIZE) {
+ await linkTagDeletedJob.dispatch(
+ {
+ tagId,
+ },
+ {
+ delay: 1,
+ label: tagId,
+ },
+ );
+ return;
+ }
+ }
+
+ // No more link–tag associations left. Delete the tag.
+ await prisma.tag.delete({
+ where: {
+ id: tagId,
+ },
+ });
+
+ console.log(`[linkTagDeletedJob] Link tag ${tagId} deleted from database.`);
+ },
+});
diff --git a/apps/web/lib/jobs/registry.ts b/apps/web/lib/jobs/registry.ts
index 3b3c97169f..4d74c6e1cc 100644
--- a/apps/web/lib/jobs/registry.ts
+++ b/apps/web/lib/jobs/registry.ts
@@ -13,6 +13,9 @@ const jobLoaders = {
"unban-partner-job": () =>
import("./handlers/unban-partner-job").then((m) => m.unbanPartnerJob),
+
+ "link-tag-deleted-job": () =>
+ import("./handlers/link-tag-deleted-job").then((m) => m.linkTagDeletedJob),
} as const satisfies Record<string, () => Promise<JobDefinition>>;
const jobCache = new Map<string, JobDefinition>();