The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
delete workspace
Kiran Kc4ab92b6b0c9
diff --git a/apps/web/app/api/cron/workspaces/delete/route.ts b/apps/web/app/api/cron/workspaces/delete/route.tsnew file mode 100644index 0000000000..aa88511047--- /dev/null+++ b/apps/web/app/api/cron/workspaces/delete/route.ts@@ -0,0 +1,102 @@+import { removeDomainFromVercel } from "@/lib/api/domains";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { bulkDeleteLinks } from "@/lib/api/links/bulk-delete-links";+import { queueWorkspaceDeletion } from "@/lib/api/workspaces";+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({+ workspaceId: z.string(),+});++export async function POST(req: Request) {+ try {+ const body = await req.json();++ await verifyQstashSignature(req, body);++ const { workspaceId } = schema.parse(body);++ const workspace = await prisma.project.findUnique({+ where: {+ id: workspaceId,+ },+ });++ if (!workspace) {+ return new Response(`Workspace ${workspaceId} not found. Skipping...`);+ }++ // Delete links in batches+ const links = await prisma.link.findMany({+ where: {+ projectId: workspace.id,+ },+ include: {+ tags: true,+ },+ take: 100,+ });++ if (links.length > 0) {+ await prisma.link.deleteMany({+ where: {+ id: {+ in: links.map((link) => link.id),+ },+ },+ });++ await bulkDeleteLinks({+ workspaceId: workspace.id,+ links,+ });+ }++ const remainingLinks = await prisma.link.count({+ where: {+ projectId: workspace.id,+ },+ });++ if (remainingLinks > 0) {+ await queueWorkspaceDeletion({+ workspaceId: workspace.id,+ delay: 2,+ });++ return new Response("Workspace links deletion queued.");+ }++ // Delete the custom domains+ const domains = await prisma.domain.findMany({+ where: {+ projectId: workspace.id,+ },+ });++ if (domains.length > 0) {+ await Promise.all([+ prisma.domain.deleteMany({+ where: {+ projectId: workspace.id,+ },+ }),++ domains.map(({ slug }) => removeDomainFromVercel(slug)),+ ]);+ }++ // Delete the workspace+ await prisma.project.delete({+ where: { id: workspace.id },+ });++ return new Response("Workspace deleted.");+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/lib/api/domains/delete-domain-links.ts b/apps/web/lib/api/domains/delete-domain-links.tsindex 806ec73a2e..37b076512d 100644--- a/apps/web/lib/api/domains/delete-domain-links.ts+++ b/apps/web/lib/api/domains/delete-domain-links.ts@@ -102,9 +102,11 @@ export async function deleteDomainAndLinks({export async function markDomainAsDeleted({domain,workspaceId,+ delay,}: {domain: string;workspaceId: string;+ delay?: number; // delay the cron job to avoid hitting rate limits}) {const links = await prisma.link.updateMany({where: {@@ -137,13 +139,14 @@ export async function markDomainAsDeleted({},},}),-- queueDomainDeletion({- workspaceId,- domain,- }),]);+ await queueDomainDeletion({+ workspaceId,+ domain,+ delay,+ });+response.forEach((promise) => {if (promise.status === "rejected") {console.error("markDomainAsDeleted", {diff --git a/apps/web/lib/api/workspaces.ts b/apps/web/lib/api/workspaces.tsindex 6112b6fbfa..feb77f3707 100644--- a/apps/web/lib/api/workspaces.ts+++ b/apps/web/lib/api/workspaces.ts@@ -3,16 +3,16 @@ import { dub } from "@/lib/dub";import { prisma } from "@/lib/prisma";import { storage } from "@/lib/storage";import { cancelSubscription } from "@/lib/stripe";-import { recordLink } from "@/lib/tinybird";import { WorkspaceProps } from "@/lib/types";import { formatRedisLink, redis } from "@/lib/upstash";import {+ APP_DOMAIN_WITH_NGROK,DUB_DOMAINS_ARRAY,LEGAL_USER_ID,LEGAL_WORKSPACE_ID,R2_URL,} from "@dub/utils";-import { waitUntil } from "@vercel/functions";+import { qstash } from "../cron";export async function deleteWorkspace(workspace: Pick<@@ -20,128 +20,51 @@ export async function deleteWorkspace("id" | "slug" | "logo" | "stripeId" | "referralLinkId">,) {- const [customDomains, defaultDomainLinks] = await Promise.all([- prisma.domain.findMany({+ await Promise.all([+ // Remove the users+ prisma.projectUsers.deleteMany({where: {projectId: workspace.id,},- select: {- slug: true,- },}),- prisma.link.findMany({++ // Remove the default workspace+ prisma.user.updateMany({where: {- projectId: workspace.id,- domain: {- in: DUB_DOMAINS_ARRAY,- },+ defaultWorkspace: workspace.slug,},- select: {- id: true,- domain: true,- key: true,- url: true,- tags: {- select: {- tagId: true,- },- },- proxy: true,- image: true,- projectId: true,- createdAt: true,+ data: {+ defaultWorkspace: null,},}),- ]);-- const response = await prisma.projectUsers.deleteMany({- where: {- projectId: workspace.id,- },- });-- waitUntil(- (async () => {- const linksByDomain: Record<string, string[]> = {};- defaultDomainLinks.forEach(async (link) => {- const { domain, key } = link;-- if (!linksByDomain[domain]) {- linksByDomain[domain] = [];- }- linksByDomain[domain].push(key.toLowerCase());- });- const pipeline = redis.pipeline();+ // Remove the API keys+ prisma.restrictedToken.deleteMany({+ where: {+ projectId: workspace.id,+ },+ }),- Object.entries(linksByDomain).forEach(([domain, links]) => {- pipeline.hdel(domain.toLowerCase(), ...links);- });+ // Cancel the workspace's Stripe subscription+ workspace.stripeId && cancelSubscription(workspace.stripeId),- // delete all domains, links, and uploaded images associated with the workspace- await Promise.allSettled([- ...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- recordLink(- defaultDomainLinks.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,- })),- ),- // remove all images from R2- ...defaultDomainLinks.map(({ id, image }) =>- image && image.startsWith(`${R2_URL}/images/${id}`)- ? storage.delete(image.replace(`${R2_URL}/`, ""))- : Promise.resolve(),- ),- ]);+ // Delete workspace logo if it's a custom logo stored in R2+ workspace.logo &&+ workspace.logo.startsWith(`${R2_URL}/logos/${workspace.id}`) &&+ storage.delete(workspace.logo.replace(`${R2_URL}/`, "")),- await Promise.allSettled([- // delete workspace logo if it's a custom logo stored in R2- workspace.logo &&- workspace.logo.startsWith(`${R2_URL}/logos/${workspace.id}`) &&- storage.delete(workspace.logo.replace(`${R2_URL}/`, "")),- // if they have a Stripe subscription, cancel it- workspace.stripeId && cancelSubscription(workspace.stripeId),- // set the referral link to `/deleted/[slug]`- workspace.referralLinkId &&- dub.links.update(workspace.referralLinkId, {- key: `/deleted/${workspace.slug}-${workspace.id}`,- archived: true,- identifier: `/deleted/${workspace.slug}-${workspace.id}`,- }),- // delete the workspace- prisma.project.delete({- where: {- slug: workspace.slug,- },- }),- prisma.user.updateMany({- where: {- defaultWorkspace: workspace.slug,- },- data: {- defaultWorkspace: null,- },- }),- ]);- })(),- );+ // Set the referral link to `/deleted/[slug]`+ workspace.referralLinkId &&+ dub.links.update(workspace.referralLinkId, {+ key: `/deleted/${workspace.slug}-${workspace.id}`,+ archived: true,+ identifier: `/deleted/${workspace.slug}-${workspace.id}`,+ }),+ ]);- return response;+ await queueWorkspaceDeletion({+ workspaceId: workspace.id,+ });}export async function deleteWorkspaceAdmin(@@ -235,3 +158,19 @@ export async function deleteWorkspaceAdmin(deleteWorkspaceResponse,};}++export async function queueWorkspaceDeletion({+ workspaceId,+ delay,+}: {+ workspaceId: string;+ delay?: number;+}) {+ return await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/workspaces/delete`,+ ...(delay && { delay }),+ body: {+ workspaceId,+ },+ });+}