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.

Sync the partner link discounts to Redis

Kiran K5b06e69c0a45
diff --git a/apps/web/app/api/cron/partners/sync-discounts/route.ts b/apps/web/app/api/cron/partners/sync-discounts/route.ts
new file mode 100644
index 0000000000..7914a0f063
--- /dev/null
+++ b/apps/web/app/api/cron/partners/sync-discounts/route.ts
@@ -0,0 +1,172 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { linkCache } from "@/lib/api/links/cache";
+import { qstash } from "@/lib/cron";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { redis } from "@/lib/upstash";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { z } from "zod";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ programId: z.string(),
+ discountId: z.string(),
+ isDefault: z.boolean(),
+ page: z.number().optional().default(1),
+ action: z.enum(["discount-created", "discount-updated", "discount-deleted"]),
+});
+
+const PAGE_SIZE = 100;
+
+// POST /api/cron/partners/sync-discounts - Sync the partner link discounts to Redis
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+ await verifyQstashSignature({ req, rawBody });
+
+ const body = schema.parse(JSON.parse(rawBody));
+ const { discountId, page, action, isDefault, programId } = body;
+
+ // If the discount is created or updated, we need to add it to the Redis cache
+ if (action === "discount-created" || action === "discount-updated") {
+ const discount = await prisma.discount.findUnique({
+ where: {
+ id: discountId,
+ },
+ });
+
+ if (!discount) {
+ return new Response("Discount not found.");
+ }
+
+ const links = await prisma.link.findMany({
+ where: {
+ programId,
+ programEnrollment: {
+ discountId: isDefault ? null : discountId,
+ },
+ },
+ include: {
+ webhooks: {
+ select: {
+ id: true,
+ },
+ },
+ programEnrollment: {
+ select: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ },
+ },
+ },
+ },
+ take: PAGE_SIZE,
+ skip: (page - 1) * PAGE_SIZE,
+ });
+
+ if (links.length === 0) {
+ return new Response("No more links to process. Exiting...");
+ }
+
+ await linkCache.mset(
+ links.map((link) => ({
+ ...link,
+ webhooks: link.webhooks.map(({ id }) => ({ webhookId: id })),
+ partner: link.programEnrollment?.partner,
+ discount,
+ })),
+ );
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/sync-discounts`,
+ body: {
+ ...body,
+ page: page + 1,
+ },
+ });
+
+ return new Response("OK");
+ }
+
+ // If the discount is deleted, we need to remove it from the Redis cache
+ if (action === "discount-deleted") {
+ let page = 0;
+
+ while (true) {
+ let partnerIds: string[] = [];
+
+ if (!isDefault) {
+ partnerIds =
+ (await redis.lpop<string[]>(
+ `discount-partners:${discountId}`,
+ PAGE_SIZE,
+ )) || [];
+
+ // There won't be any entries in Redis for the default discount
+ if (!partnerIds || partnerIds.length === 0) {
+ await redis.del(`discount-partners:${discountId}`);
+ break;
+ }
+ }
+
+ const links = await prisma.link.findMany({
+ where: {
+ programId,
+ programEnrollment: {
+ ...(partnerIds.length > 0 && {
+ partnerId: {
+ in: partnerIds,
+ },
+ }),
+ discountId: null,
+ },
+ },
+ include: {
+ webhooks: {
+ select: {
+ id: true,
+ },
+ },
+ programEnrollment: {
+ select: {
+ partner: {
+ select: {
+ id: true,
+ name: true,
+ image: true,
+ },
+ },
+ },
+ },
+ },
+ take: PAGE_SIZE,
+ skip: page * PAGE_SIZE,
+ });
+
+ if (links.length === 0) {
+ break;
+ }
+
+ await linkCache.mset(
+ links.map((link) => ({
+ ...link,
+ webhooks: link.webhooks.map(({ id }) => ({ webhookId: id })),
+ partner: link.programEnrollment?.partner,
+ discount: null,
+ })),
+ );
+
+ page += 1;
+ }
+ }
+
+ return new Response("OK");
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index a87d33ee2e..26d526957d 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -2,8 +2,11 @@
import { createId } from "@/lib/api/create-id";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { qstash } from "@/lib/cron";
import { createDiscountSchema } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { authActionClient } from "../safe-action";
export const createDiscountAction = authActionClient
@@ -96,4 +99,16 @@ export const createDiscountAction = authActionClient
},
});
}
+
+ waitUntil(
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/sync-discounts`,
+ body: {
+ programId,
+ discountId: discount.id,
+ isDefault,
+ action: "discount-created",
+ },
+ }),
+ );
});
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index c20ae69c86..77814f5ac3 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -2,7 +2,11 @@
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { qstash } from "@/lib/cron";
+import { redis } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { z } from "zod";
import { authActionClient } from "../safe-action";
@@ -28,14 +32,48 @@ export const deleteDiscountAction = authActionClient
discountId,
});
- await prisma.$transaction(async (tx) => {
+ // Backup the partners data before deleting the discount
+ // We'll use this data to update the link cache for the partner links
+ const isDefault = program.defaultDiscountId === discountId;
+
+ if (!isDefault) {
+ let offset = 0;
+
+ while (true) {
+ const partners = await prisma.programEnrollment.findMany({
+ where: {
+ programId,
+ discountId,
+ },
+ select: {
+ partnerId: true,
+ },
+ skip: offset,
+ take: 1000,
+ });
+
+ if (partners.length === 0) {
+ break;
+ }
+
+ await redis.lpush(
+ `discount-partners:${discountId}`,
+ partners.map((partner) => partner.partnerId),
+ );
+
+ offset += 1000;
+ }
+ }
+
+ const deletedDiscountId = await prisma.$transaction(async (tx) => {
// if this is the default discount, set the program default discount to null
- if (program.defaultDiscountId === discountId) {
+ if (isDefault) {
await tx.program.update({
where: { id: programId },
data: { defaultDiscountId: null },
});
}
+
// update all program enrollments to have no discount
await tx.programEnrollment.updateMany({
where: {
@@ -45,11 +83,28 @@ export const deleteDiscountAction = authActionClient
discountId: null,
},
});
+
// delete the discount
await tx.discount.delete({
where: {
id: discountId,
},
});
+
+ return discountId;
});
+
+ if (deletedDiscountId) {
+ waitUntil(
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/sync-discounts`,
+ body: {
+ programId,
+ discountId,
+ isDefault,
+ action: "discount-deleted",
+ },
+ }),
+ );
+ }
});
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index ee5d48ceab..2610b83a2e 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -2,8 +2,11 @@
import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
+import { qstash } from "@/lib/cron";
import { updateDiscountSchema } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { authActionClient } from "../safe-action";
export const updateDiscountAction = authActionClient
@@ -97,4 +100,16 @@ export const updateDiscountAction = authActionClient
}),
]);
}
+
+ waitUntil(
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/sync-discounts`,
+ body: {
+ programId,
+ discountId,
+ isDefault,
+ action: "discount-updated",
+ },
+ }),
+ );
});