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.

wip cron logic

Kiran Kc7ca2712b011
diff --git a/apps/web/app/api/cron/domains/transfer/route.ts b/apps/web/app/api/cron/domains/transfer/route.ts
new file mode 100644
index 0000000000..729177609e
--- /dev/null
+++ b/apps/web/app/api/cron/domains/transfer/route.ts
@@ -0,0 +1,117 @@
+import { qstash, receiver } from "@/lib/cron";
+import prisma from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import z from "@/lib/zod";
+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { Link } from "@prisma/client";
+import { NextResponse } from "next/server";
+
+const schema = z.object({
+ currentWorkspaceId: z.string(),
+ newWorkspaceId: z.string(),
+ domain: z.string(),
+});
+
+export async function POST(req: Request) {
+ const body = await req.json();
+
+ if (process.env.VERCEL === "1") {
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(body),
+ });
+
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
+ const { currentWorkspaceId, newWorkspaceId, domain } = schema.parse(body);
+
+ const links = await prisma.link.findMany({
+ where: { domain, projectId: currentWorkspaceId },
+ take: 100,
+ });
+
+ if (!links || links.length === 0) {
+ return NextResponse.json({
+ response: "success",
+ });
+ }
+
+ const linksCount = links.length;
+
+ // Object.entries(linksByDomain).forEach(([domain, links]) => {
+ // pipeline.hdel(domain, ...links);
+ // });
+
+ // [link.key.toLowerCase()]: {
+ // ...(await formatRedisLink(link)),
+ // projectId: LEGAL_WORKSPACE_ID,
+ // },
+
+ try {
+ const updateLinksInRedis = async (links: Link[]) => {
+ const pipeline = redis.pipeline();
+
+ links.forEach((link) =>
+ pipeline.hset(domain, {
+ [link.key.toLowerCase()]: {
+ // ...(await formatRedisLink(link)),
+ projectId: newWorkspaceId,
+ },
+ }),
+ );
+
+ pipeline.exec();
+ };
+
+ await Promise.allSettled([
+ prisma.link.updateMany({
+ where: { domain, projectId: currentWorkspaceId },
+ data: { projectId: newWorkspaceId },
+ }),
+ prisma.project.update({
+ where: { id: currentWorkspaceId },
+ data: {
+ linksUsage: {
+ decrement: linksCount,
+ },
+ },
+ }),
+ prisma.project.update({
+ where: { id: newWorkspaceId },
+ data: {
+ linksUsage: {
+ increment: linksCount,
+ },
+ },
+ }),
+ updateLinksInRedis(links)
+ ]);
+
+ // wait 500 ms before making another request
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/transfer`,
+ body: {
+ currentWorkspaceId,
+ newWorkspaceId,
+ domain,
+ },
+ });
+ } catch (error) {
+ await log({
+ message: `Domain transfer cron for the workspace ${newWorkspaceId} failed. Error: ${error.message}`,
+ type: "errors",
+ });
+
+ return NextResponse.json({ error: error.message });
+ }
+
+ // TODO:
+ // Update redis
+ // Update TB
+ // Update analytics
+}
diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.ts
index 4d8eabd18c..cc5bb9945c 100644
--- a/apps/web/app/api/domains/[domain]/transfer/route.ts
+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts
@@ -1,7 +1,9 @@
import { DubApiError } from "@/lib/api/errors";
import { withAuth } from "@/lib/auth";
+import { qstash } from "@/lib/cron";
import prisma from "@/lib/prisma";
import z from "@/lib/zod";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
const transferDomainBodySchema = z.object({
@@ -15,12 +17,11 @@ const transferDomainBodySchema = z.object({
export const POST = withAuth(
async ({ req, headers, session, params, workspace }) => {
const { newWorkspaceId } = transferDomainBodySchema.parse(await req.json());
+ const { domain } = params;
const newWorkspace = await prisma.project.findUnique({
where: { id: newWorkspaceId },
select: {
- linksUsage: true,
- linksLimit: true,
users: {
where: {
userId: session.user.id,
@@ -39,15 +40,33 @@ export const POST = withAuth(
});
}
- const domain = await prisma.domain.findUniqueOrThrow({
- where: { slug: params.domain, projectId: workspace.id },
+ const domainFound = await prisma.domain.findUnique({
+ where: { slug: domain, projectId: workspace.id },
});
+ if (!domainFound) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Domain not found",
+ });
+ }
+
await prisma.domain.update({
- where: { slug: domain.slug, projectId: workspace.id },
+ where: { slug: domain, projectId: workspace.id },
data: { projectId: newWorkspaceId },
});
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/transfer`,
+ body: {
+ currentWorkspaceId: workspace.id,
+ newWorkspaceId,
+ domain,
+ },
+ });
+
+ return NextResponse.json({}, { headers });
+
// const link = await prisma.link.findUnique({
// where: {
// id: params.linkId,
@@ -124,12 +143,6 @@ export const POST = withAuth(
// },
// }),
// ]);
-
- return NextResponse.json(
- {},
- {
- headers,
- },
- );
},
+ { requiredRole: ["owner"] },
);
diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.ts
index 3e8ba6312e..ff93def141 100644
--- a/apps/web/lib/api/domains.ts
+++ b/apps/web/lib/api/domains.ts
@@ -271,9 +271,4 @@ export async function deleteDomainAndLinks(
},
}),
]);
-}
-
-// Transfer domain
-const transferDomain = async () => {
- //
}
\ No newline at end of file
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index ca3ff0b535..6a5a7f1228 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -436,6 +436,7 @@ export const withAuth = (
link,
});
} catch (error) {
+ console.log(error)
return handleAndReturnErrorResponse(error);
}
};