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.

delete the domain

Kiran K7bd3504ffd93
diff --git a/apps/web/app/api/cron/cleanup/route.ts b/apps/web/app/api/cron/cleanup/route.ts
index 132e933b5b..965dc20752 100644
--- a/apps/web/app/api/cron/cleanup/route.ts
+++ b/apps/web/app/api/cron/cleanup/route.ts
@@ -1,4 +1,4 @@
-import { deleteDomainAndLinks } from "@/lib/api/domains";
+import { markDomainAsDeleted } from "@/lib/api/domains";
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { bulkDeleteLinks } from "@/lib/api/links/bulk-delete-links";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
@@ -69,7 +69,12 @@ export async function GET(req: Request) {
// Delete the domains
if (domains.length > 0) {
await Promise.all(
- domains.map((domain) => deleteDomainAndLinks(domain.slug)),
+ domains.map(({ slug }) =>
+ markDomainAsDeleted({
+ domain: slug,
+ workspaceId: E2E_WORKSPACE_ID,
+ }),
+ ),
);
}
diff --git a/apps/web/app/api/cron/domains/delete/route.ts b/apps/web/app/api/cron/domains/delete/route.ts
new file mode 100644
index 0000000000..b2b2d6586a
--- /dev/null
+++ b/apps/web/app/api/cron/domains/delete/route.ts
@@ -0,0 +1,41 @@
+import { deleteDomainAndLinks } from "@/lib/api/domains/delete-domain-links";
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { prisma } from "@/lib/prisma";
+import { z } from "zod";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ domain: z.string(),
+ workspaceId: z.string(),
+});
+
+export async function POST(req: Request) {
+ try {
+ const body = await req.json();
+
+ await verifyQstashSignature(req, body);
+
+ const { domain, workspaceId } = schema.parse(body);
+
+ const domainRecord = await prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ });
+
+ if (!domainRecord) {
+ return new Response(`Domain ${domain} not found. Skipping...`);
+ }
+
+ await deleteDomainAndLinks({
+ domain,
+ workspaceId,
+ });
+
+ return new Response("Domain deleted.");
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/cron/domains/verify/utils.ts b/apps/web/app/api/cron/domains/verify/utils.ts
index b8b818c031..50147719ef 100644
--- a/apps/web/app/api/cron/domains/verify/utils.ts
+++ b/apps/web/app/api/cron/domains/verify/utils.ts
@@ -1,4 +1,4 @@
-import { deleteDomainAndLinks } from "@/lib/api/domains";
+import { markDomainAsDeleted } from "@/lib/api/domains";
import { limiter } from "@/lib/cron/limiter";
import { prisma } from "@/lib/prisma";
import { log } from "@dub/utils";
@@ -99,9 +99,13 @@ export const handleDomainUpdates = async ({
type: "cron",
});
}
+
// else, delete the domain
return await Promise.allSettled([
- deleteDomainAndLinks(domain).then(async () => {
+ markDomainAsDeleted({
+ domain,
+ workspaceId: workspace.id,
+ }).then(async () => {
// if the deleted domain was primary, make another domain primary
if (primary) {
const anotherDomain = await prisma.domain.findFirst({
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index e4052a60c7..a5b178f079 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -1,6 +1,6 @@
import {
addDomainToVercel,
- deleteDomainAndLinks,
+ markDomainAsDeleted,
removeDomainFromVercel,
validateDomain,
} from "@/lib/api/domains";
@@ -155,7 +155,10 @@ export const DELETE = withWorkspace(
});
}
- await deleteDomainAndLinks(domain);
+ await markDomainAsDeleted({
+ domain,
+ workspaceId: workspace.id,
+ });
return NextResponse.json({ slug: domain });
},
diff --git a/apps/web/lib/api/domains/claim-dot-link-domain.ts b/apps/web/lib/api/domains/claim-dot-link-domain.ts
index a568dde7bb..b0349a1705 100644
--- a/apps/web/lib/api/domains/claim-dot-link-domain.ts
+++ b/apps/web/lib/api/domains/claim-dot-link-domain.ts
@@ -13,7 +13,7 @@ import { waitUntil } from "@vercel/functions";
import { sendEmail } from "emails";
import DomainClaimed from "emails/domain-claimed";
import { addDomainToVercel } from "./add-domain-vercel";
-import { deleteDomainAndLinks } from "./delete-domain-links";
+import { markDomainAsDeleted } from "./delete-domain-links";
export async function claimDotLinkDomain({
domain,
@@ -69,7 +69,12 @@ export async function claimDotLinkDomain({
// if the domain was added to a different workspace but is not verified
// we should remove it to free up the domain for the current workspace
if (matchingUnverifiedDomain) {
- await deleteDomainAndLinks(matchingUnverifiedDomain.slug);
+ const { projectId, slug } = matchingUnverifiedDomain;
+
+ await markDomainAsDeleted({
+ domain: slug,
+ workspaceId: projectId!,
+ });
}
await Promise.all([
diff --git a/apps/web/lib/api/domains/delete-domain-links.ts b/apps/web/lib/api/domains/delete-domain-links.ts
index 70fed26417..7d0c68a4c2 100644
--- a/apps/web/lib/api/domains/delete-domain-links.ts
+++ b/apps/web/lib/api/domains/delete-domain-links.ts
@@ -1,82 +1,179 @@
+import { qstash } from "@/lib/cron";
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/upstash";
-import { R2_URL } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
+import { APP_DOMAIN_WITH_NGROK, R2_URL } from "@dub/utils";
import { storage } from "../../storage";
import { recordLink } from "../../tinybird";
import { removeDomainFromVercel } from "./remove-domain-vercel";
-/* Delete a domain and all links & images associated with it */
-export async function deleteDomainAndLinks(domain: string) {
- const [domainData, allLinks] = await Promise.all([
- prisma.domain.findUnique({
- where: {
- slug: domain,
- },
- select: {
- id: true,
- projectId: true,
- createdAt: true,
- },
- }),
- prisma.link.findMany({
+// Delete a domain and all links & images associated with it
+export async function deleteDomainAndLinks({
+ domain,
+ workspaceId,
+}: {
+ domain: string;
+ workspaceId: string;
+}) {
+ const links = await prisma.link.findMany({
+ where: {
+ domain,
+ },
+ include: {
+ tags: true,
+ },
+ take: 1,
+ });
+
+ if (links.length === 0) {
+ return;
+ }
+
+ const pipeline = redis.pipeline();
+
+ links.forEach((link) => {
+ pipeline.del(`${link.domain}:${link.key}`.toLowerCase());
+ });
+
+ const response = await Promise.allSettled([
+ // Record link in the Tinybird
+ recordLink(
+ links.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tag_ids: link.tags.map((tag) => tag.id),
+ workspace_id: workspaceId,
+ created_at: link.createdAt,
+ deleted: true,
+ })),
+ ),
+
+ // Remove image from R2 storage if it exists
+ links
+ .filter((link) => link.image?.startsWith(`${R2_URL}/images/${link.id}`))
+ .map((link) => storage.delete(link.image!.replace(`${R2_URL}/`, ""))),
+
+ // Remove the link from Redis
+ pipeline.exec(),
+
+ // Remove the link from MySQL
+ prisma.link.deleteMany({
where: {
- domain,
- },
- select: {
- id: true,
- domain: true,
- key: true,
- url: true,
- image: true,
- projectId: true,
- tags: true,
- createdAt: true,
+ id: { in: links.map((link) => link.id) },
},
}),
]);
- if (!domainData) {
- return null;
+ response.forEach((promise) => {
+ if (promise.status === "rejected") {
+ console.error("Error deleting domain and links", {
+ reason: promise.reason,
+ domain,
+ workspaceId,
+ });
+ }
+ });
+
+ const remainingLinks = await prisma.link.count({
+ where: {
+ domain,
+ },
+ });
+
+ if (remainingLinks > 0) {
+ return await queueDomainDeletion({
+ workspaceId,
+ domain,
+ delay: 2,
+ });
}
- const response = await prisma.domain.delete({
+ // After all links are deleted, delete the domain
+ await prisma.domain.delete({
where: {
slug: domain,
},
});
+}
+
+// Mark the domain as deleted
+// We'll delete the domain and its links via a cron job
+export async function markDomainAsDeleted({
+ domain,
+ workspaceId,
+}: {
+ domain: string;
+ workspaceId: string;
+}) {
+ const [vercelResponse, prismaResponse, qstashResponse] =
+ await Promise.allSettled([
+ removeDomainFromVercel(domain),
+
+ prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ projectId: null,
+ },
+ }),
+
+ prisma.link.updateMany({
+ where: {
+ domain,
+ },
+ data: {
+ projectId: null,
+ },
+ }),
+
+ queueDomainDeletion({
+ workspaceId,
+ domain,
+ }),
+ ]);
+
+ if (vercelResponse.status === "rejected") {
+ console.error("Error deleting domain from Vercel", {
+ reason: vercelResponse.reason,
+ domain,
+ workspaceId,
+ });
+ }
+
+ if (prismaResponse.status === "rejected") {
+ console.error("Error deleting domain from Prisma", {
+ reason: prismaResponse.reason,
+ domain,
+ workspaceId,
+ });
+ }
- waitUntil(
- (async () => {
- await Promise.allSettled([
- // delete all links from redis
- redis.del(domain.toLowerCase()),
- // record deletes in tinybird for domain & links
- recordLink([
- ...allLinks.map((link) => ({
- link_id: link.id,
- domain: link.domain,
- key: link.key,
- url: link.url,
- tag_ids: link.tags.map((tag) => tag.tagId),
- workspace_id: link.projectId,
- created_at: link.createdAt,
- deleted: true,
- })),
- ]),
- ...allLinks.map((link) => {
- if (
- link.image &&
- link.image.startsWith(`${R2_URL}/images/${link.id}`)
- ) {
- storage.delete(link.image.replace(`${R2_URL}/`, ""));
- }
- }),
- // remove the domain from Vercel
- removeDomainFromVercel(domain),
- ]);
- })(),
- );
-
- return response;
+ if (qstashResponse.status === "rejected") {
+ console.error("Error publishing to Qstash", {
+ reason: qstashResponse.reason,
+ domain,
+ workspaceId,
+ });
+ }
+}
+
+async function queueDomainDeletion({
+ workspaceId,
+ domain,
+ delay,
+}: {
+ workspaceId: string;
+ domain: string;
+ delay?: number;
+}) {
+ return await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/delete`,
+ ...(delay && { delay }),
+ body: {
+ workspaceId,
+ domain,
+ },
+ });
}
diff --git a/apps/web/lib/api/workspaces.ts b/apps/web/lib/api/workspaces.ts
index 7d24aa4bbb..6112b6fbfa 100644
--- a/apps/web/lib/api/workspaces.ts
+++ b/apps/web/lib/api/workspaces.ts
@@ -1,4 +1,4 @@
-import { deleteDomainAndLinks } from "@/lib/api/domains";
+import { markDomainAsDeleted } from "@/lib/api/domains";
import { dub } from "@/lib/dub";
import { prisma } from "@/lib/prisma";
import { storage } from "@/lib/storage";
@@ -80,7 +80,12 @@ export async function deleteWorkspace(
// delete all domains, links, and uploaded images associated with the workspace
await Promise.allSettled([
- ...customDomains.map(({ slug }) => deleteDomainAndLinks(slug)),
+ ...customDomains.map(({ slug }) =>
+ markDomainAsDeleted({
+ domain: slug,
+ workspaceId: workspace.id,
+ }),
+ ),
// delete all default domain links from redis
pipeline.exec(),
// record deletes in Tinybird for default domain links
@@ -193,7 +198,12 @@ export async function deleteWorkspaceAdmin(
// delete all domains, links, and uploaded images associated with the workspace
const deleteDomainsLinksResponse = await Promise.allSettled([
- ...customDomains.map(({ slug }) => deleteDomainAndLinks(slug)),
+ ...customDomains.map(({ slug }) =>
+ markDomainAsDeleted({
+ domain: slug,
+ workspaceId: workspace.id,
+ }),
+ ),
]);
const deleteWorkspaceResponse = await Promise.allSettled([
diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prisma
index 536c6e9638..0e7f264d84 100644
--- a/apps/web/prisma/schema/webhook.prisma
+++ b/apps/web/prisma/schema/webhook.prisma
@@ -2,6 +2,7 @@ enum WebhookReceiver {
user
zapier
make
+ slack
}
model Webhook {