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.

queueFolderDeletion

Steven Teyfc5abbb831a6
diff --git a/apps/web/app/api/cron/domains/delete/route.ts b/apps/web/app/api/cron/domains/delete/route.ts
index 28baee2c7d..702f62e86f 100644
--- a/apps/web/app/api/cron/domains/delete/route.ts
+++ b/apps/web/app/api/cron/domains/delete/route.ts
@@ -12,7 +12,6 @@ export const dynamic = "force-dynamic";
const schema = z.object({
domain: z.string(),
- workspaceId: z.string(),
});
// POST /api/cron/domains/delete
@@ -21,7 +20,7 @@ export async function POST(req: Request) {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- const { domain, workspaceId } = schema.parse(JSON.parse(rawBody));
+ const { domain } = schema.parse(JSON.parse(rawBody));
const domainRecord = await prisma.domain.findUnique({
where: {
@@ -78,7 +77,6 @@ export async function POST(req: Request) {
console.error("deleteDomainAndLinks", {
reason: promise.reason,
domain,
- workspaceId,
});
}
});
@@ -93,7 +91,6 @@ export async function POST(req: Request) {
if (remainingLinks > 0) {
await queueDomainDeletion({
- workspaceId,
domain,
delay: 2,
});
diff --git a/apps/web/app/api/cron/folders/delete/route.ts b/apps/web/app/api/cron/folders/delete/route.ts
new file mode 100644
index 0000000000..c628cf94d6
--- /dev/null
+++ b/apps/web/app/api/cron/folders/delete/route.ts
@@ -0,0 +1,79 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { queueFolderDeletion } from "@/lib/api/folders/queue-folder-deletion";
+import { includeTags } from "@/lib/api/links/include-tags";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { recordLink } from "@/lib/tinybird";
+import { prisma } from "@dub/prisma";
+import { z } from "zod";
+
+export const dynamic = "force-dynamic";
+
+const MAX_LINKS_PER_BATCH = 500;
+
+const schema = z.object({
+ folderId: z.string(),
+});
+
+// POST /api/cron/folders/delete
+// Recursively remove the `folderId` association in all the links of a folder from Tinybird
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+ await verifyQstashSignature({ req, rawBody });
+
+ const { folderId } = schema.parse(JSON.parse(rawBody));
+
+ const linksToUpdate = await prisma.link.findMany({
+ where: {
+ folderId,
+ },
+ take: MAX_LINKS_PER_BATCH,
+ include: includeTags,
+ });
+
+ if (linksToUpdate.length === 0) {
+ await prisma.folder.delete({
+ where: {
+ id: folderId,
+ },
+ });
+
+ return new Response("No more links to process. Deleting folder...");
+ }
+
+ const recordLinkResponse = await recordLink(
+ linksToUpdate.map((link) => ({
+ ...link,
+ folderId: null,
+ })),
+ );
+
+ console.log("recordLinkResponse", recordLinkResponse);
+
+ const updateLinksResponse = await prisma.link.updateMany({
+ where: {
+ id: {
+ in: linksToUpdate.map((link) => link.id),
+ },
+ },
+ data: {
+ folderId: null,
+ },
+ });
+
+ console.log("updateLinksResponse", updateLinksResponse);
+
+ // TODO: technically we can check if linksToUpdate.length < MAX_LINKS_PER_BATCH
+ // because that means all the links have been updated and we can delete the folder
+ await queueFolderDeletion({
+ folderId,
+ delay: 2,
+ });
+
+ return new Response(
+ `Processed ${linksToUpdate.length} links in the folder.`,
+ );
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/cron/links/sync-tinybird/route.ts b/apps/web/app/api/cron/links/sync-tinybird/route.ts
deleted file mode 100644
index ae08ad8053..0000000000
--- a/apps/web/app/api/cron/links/sync-tinybird/route.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { scheduleLinkSync } from "@/lib/api/links/utils/sync-links";
-import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { recordLink } from "@/lib/tinybird";
-import { prisma } from "@dub/prisma";
-import { z } from "zod";
-
-export const dynamic = "force-dynamic";
-
-const MAX_LINKS_PER_BATCH = 500;
-
-const schema = z.object({
- folderId: z.string(),
-});
-
-// POST /api/cron/links/sync-tinybird
-// Sync the link changes to the Tinybird datasource
-export async function POST(req: Request) {
- try {
- const rawBody = await req.text();
- await verifyQstashSignature({ req, rawBody });
-
- const { folderId } = schema.parse(JSON.parse(rawBody));
-
- const folder = await prisma.folder.findUnique({
- where: {
- id: folderId,
- },
- select: {
- _count: {
- select: {
- links: true,
- },
- },
- },
- });
-
- if (!folder) {
- return new Response("Folder not found. Skipping...");
- }
-
- const countOfLinks = folder._count.links;
-
- if (countOfLinks === 0) {
- await prisma.folder.delete({
- where: {
- id: folderId,
- },
- });
-
- return new Response("No more links to process. Deleting folder...");
- }
-
- const processedLinks = await prisma.$transaction(
- async (tx) => {
- const links = await tx.link.findMany({
- where: {
- folderId,
- },
- include: {
- tags: {
- select: {
- tag: true,
- },
- },
- },
- orderBy: {
- id: "asc",
- },
- take: MAX_LINKS_PER_BATCH,
- });
-
- await recordLink(
- links.map((link) => ({
- ...link,
- folderId: null,
- })),
- );
-
- await tx.link.updateMany({
- where: {
- id: {
- in: links.map((link) => link.id),
- },
- },
- data: {
- folderId: null,
- },
- });
-
- return links;
- },
- {
- timeout: 10000,
- },
- );
-
- await scheduleLinkSync({
- folderId,
- delay: 2,
- });
-
- return new Response(
- `Processed ${processedLinks.length} links in the folder.`,
- );
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
diff --git a/apps/web/app/api/folders/[folderId]/route.ts b/apps/web/app/api/folders/[folderId]/route.ts
index 1fbb4a5bf6..51d2196d22 100644
--- a/apps/web/app/api/folders/[folderId]/route.ts
+++ b/apps/web/app/api/folders/[folderId]/route.ts
@@ -1,5 +1,5 @@
import { DubApiError } from "@/lib/api/errors";
-import { scheduleLinkSync } from "@/lib/api/links/utils/sync-links";
+import { queueFolderDeletion } from "@/lib/api/folders/queue-folder-deletion";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { verifyFolderAccess } from "@/lib/folder/permissions";
@@ -118,26 +118,31 @@ export const DELETE = withWorkspace(
folderId,
},
});
-
- await prisma.$transaction(async (tx) => {
- if (linksCount === 0) {
- await tx.folder.delete({
- where: {
- id: folderId,
- },
- });
- } else {
- await tx.folder.update({
+ // if there are no links associated with the folder, we can just delete it
+ if (linksCount === 0) {
+ await prisma.folder.delete({
+ where: {
+ id: folderId,
+ },
+ });
+ } else {
+ await Promise.all([
+ prisma.folder.update({
where: {
id: folderId,
},
data: {
projectId: "",
},
- });
- }
+ }),
+ queueFolderDeletion({
+ folderId,
+ }),
+ ]);
+ }
- await tx.project.update({
+ waitUntil(
+ prisma.project.update({
where: {
id: workspace.id,
},
@@ -146,16 +151,8 @@ export const DELETE = withWorkspace(
decrement: 1,
},
},
- });
- });
-
- if (linksCount > 0) {
- waitUntil(
- scheduleLinkSync({
- folderId,
- }),
- );
- }
+ }),
+ );
return NextResponse.json({ id: folderId });
},
diff --git a/apps/web/app/api/folders/route.ts b/apps/web/app/api/folders/route.ts
index 9c4bd2e0db..61eac5703b 100644
--- a/apps/web/app/api/folders/route.ts
+++ b/apps/web/app/api/folders/route.ts
@@ -9,6 +9,7 @@ import {
listFoldersQuerySchema,
} from "@/lib/zod/schemas/folders";
import { prisma } from "@dub/prisma";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// GET /api/folders - get all folders for a workspace
@@ -70,26 +71,27 @@ export const POST = withWorkspace(
}
try {
- const [newFolder] = await prisma.$transaction([
- prisma.folder.create({
- data: {
- id: createId({ prefix: "fold_" }),
- projectId: workspace.id,
- name,
- accessLevel,
- users: {
- create: {
- userId: session.user.id,
- role: "owner",
- },
+ const newFolder = await prisma.folder.create({
+ data: {
+ id: createId({ prefix: "fold_" }),
+ projectId: workspace.id,
+ name,
+ accessLevel,
+ users: {
+ create: {
+ userId: session.user.id,
+ role: "owner",
},
},
- }),
+ },
+ });
+
+ waitUntil(
prisma.project.update({
where: { id: workspace.id },
data: { foldersUsage: { increment: 1 } },
}),
- ]);
+ );
return NextResponse.json(FolderSchema.parse(newFolder), {
headers,
diff --git a/apps/web/lib/api/domains/mark-domain-deleted.ts b/apps/web/lib/api/domains/mark-domain-deleted.ts
index cb5392c6fe..4eadec2572 100644
--- a/apps/web/lib/api/domains/mark-domain-deleted.ts
+++ b/apps/web/lib/api/domains/mark-domain-deleted.ts
@@ -7,11 +7,9 @@ import { removeDomainFromVercel } from "./remove-domain-vercel";
export async function markDomainAsDeleted({
domain,
workspaceId,
- delay,
}: {
domain: string;
workspaceId: string;
- delay?: number; // delay the cron job to avoid hitting rate limits
}) {
await prisma.link.updateMany({
where: {
@@ -36,9 +34,7 @@ export async function markDomainAsDeleted({
]);
await queueDomainDeletion({
- workspaceId,
domain,
- delay,
});
response.forEach((promise) => {
diff --git a/apps/web/lib/api/domains/queue.ts b/apps/web/lib/api/domains/queue.ts
index 8584580532..88e115da8b 100644
--- a/apps/web/lib/api/domains/queue.ts
+++ b/apps/web/lib/api/domains/queue.ts
@@ -27,11 +27,9 @@ export async function queueDomainUpdate({
}
export async function queueDomainDeletion({
- workspaceId,
domain,
delay,
}: {
- workspaceId: string;
domain: string;
delay?: number;
}) {
@@ -39,7 +37,6 @@ export async function queueDomainDeletion({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/delete`,
...(delay && { delay }),
body: {
- workspaceId,
domain,
},
});
diff --git a/apps/web/lib/api/links/utils/sync-links.ts b/apps/web/lib/api/folders/queue-folder-deletion.ts
similarity index 71%
rename from apps/web/lib/api/links/utils/sync-links.ts
rename to apps/web/lib/api/folders/queue-folder-deletion.ts
index 21ea956418..0bcaa4ff5b 100644
--- a/apps/web/lib/api/links/utils/sync-links.ts
+++ b/apps/web/lib/api/folders/queue-folder-deletion.ts
@@ -1,7 +1,7 @@
import { qstash } from "@/lib/cron";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-export async function scheduleLinkSync({
+export async function queueFolderDeletion({
folderId,
delay,
}: {
@@ -9,7 +9,7 @@ export async function scheduleLinkSync({
delay?: number;
}) {
return await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/sync-tinybird`,
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/folders/delete`,
...(delay && { delay }),
body: {
folderId,