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.

Refactor discount link cache invalidation to use groupId

Kiran Kaced3f8782fa
diff --git a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
index b34f601adc..94bebec23d 100644
--- a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
+++ b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
@@ -1,17 +1,14 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { redis } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
+import { chunk } 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(),
- action: z.enum(["discount-created", "discount-updated", "discount-deleted"]),
+ groupId: z.string(),
});
// This route is used to invalidate the partnerlink cache when a discount is created/updated/deleted.
@@ -21,103 +18,52 @@ export async function POST(req: Request) {
const rawBody = await req.text();
await verifyQstashSignature({ req, rawBody });
- const body = schema.parse(JSON.parse(rawBody));
- const { programId, discountId, isDefault, action } = body;
+ const { groupId } = schema.parse(JSON.parse(rawBody));
- if (action === "discount-created" || action === "discount-updated") {
- const discount = await prisma.discount.findUnique({
- where: {
- id: discountId,
- },
- });
+ // Find the group
+ const group = await prisma.partnerGroup.findUnique({
+ where: {
+ id: groupId,
+ },
+ });
- if (!discount) {
- return new Response("Discount not found.");
- }
-
- let page = 0;
- let total = 0;
- const take = 1000;
-
- while (true) {
- const links = await prisma.link.findMany({
- where: {
- programEnrollment: { discountId },
- },
- select: {
- domain: true,
- key: true,
- },
- take,
- skip: page * take,
- });
-
- if (links.length === 0) {
- break;
- }
-
- await linkCache.expireMany(links);
-
- page += 1;
- total += links.length;
- }
-
- return new Response(`Invalidated ${total} links.`);
+ if (!group) {
+ console.error(`Group ${groupId} not found.`);
+ return new Response("OK");
}
- if (action === "discount-deleted") {
- let page = 0;
- let total = 0;
- const take = 1000;
-
- while (true) {
- let partnerIds: string[] = [];
-
- if (!isDefault) {
- partnerIds =
- (await redis.lpop<string[]>(
- `discount-partners:${discountId}`,
- take,
- )) || [];
-
- // There won't be any entries in Redis for the default discount
- if (!partnerIds || partnerIds.length === 0) {
- await redis.del(`discount-partners:${discountId}`);
- break;
- }
- }
+ // Find all the links of the partners in the group
+ const programEnrollments = await prisma.programEnrollment.findMany({
+ where: {
+ groupId,
+ },
+ include: {
+ links: true,
+ },
+ });
+
+ if (programEnrollments.length === 0) {
+ console.log(`No program enrollments found for group ${groupId}.`);
+ return new Response("OK");
+ }
- const links = await prisma.link.findMany({
- where: {
- programId,
- programEnrollment: {
- ...(partnerIds.length > 0 && {
- partnerId: {
- in: partnerIds,
- },
- }),
- discountId: null,
- },
- },
- select: {
- domain: true,
- key: true,
- },
- take,
- skip: page * take,
- });
+ const links = programEnrollments.flatMap((enrollment) => enrollment.links);
- if (links.length === 0) {
- break;
- }
+ if (links.length === 0) {
+ console.log(`No links found for partners in the group ${groupId}.`);
+ return new Response("OK");
+ }
- await linkCache.expireMany(links);
+ console.log(`Found ${links.length} links to invalidate the cache for.`);
- page += 1;
- total += links.length;
- }
+ const linkChunks = chunk(links, 100);
- return new Response(`Invalidated ${total} links.`);
+ // Expire the cache for the links
+ for (const linkChunk of linkChunks) {
+ const toExpire = linkChunk.map(({ domain, key }) => ({ domain, key }));
+ await linkCache.expireMany(toExpire);
+ console.log(toExpire);
+ console.log(`Expired cache for ${toExpire.length} links.`);
}
return new Response("OK");
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 3f68170621..9686c237e1 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -65,9 +65,7 @@ export const createDiscountAction = authActionClient
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
body: {
- programId,
- discountId: discount.id,
- action: "discount-created",
+ groupId,
},
}),
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index c2d4695cc0..e4397c41a7 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -28,8 +28,8 @@ export const deleteDiscountAction = authActionClient
discountId,
});
- await prisma.$transaction(async (tx) => {
- await tx.partnerGroup.update({
+ const group = await prisma.$transaction(async (tx) => {
+ const group = await tx.partnerGroup.update({
where: {
discountId: discount.id,
},
@@ -52,6 +52,8 @@ export const deleteDiscountAction = authActionClient
id: discount.id,
},
});
+
+ return group;
});
waitUntil(
@@ -59,10 +61,7 @@ export const deleteDiscountAction = authActionClient
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
body: {
- programId,
- discountId,
- isDefault: discount.default,
- action: "discount-deleted",
+ groupId: group.id,
},
}),
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index d4c5134953..9c757708a5 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -24,7 +24,7 @@ export const updateDiscountAction = authActionClient
discountId,
});
- const updatedDiscount = await prisma.discount.update({
+ const { partnerGroup, ...updatedDiscount } = await prisma.discount.update({
where: {
id: discountId,
},
@@ -35,6 +35,9 @@ export const updateDiscountAction = authActionClient
couponId,
couponTestId,
},
+ include: {
+ partnerGroup: true,
+ },
});
waitUntil(
@@ -57,10 +60,7 @@ export const updateDiscountAction = authActionClient
? qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
body: {
- programId,
- discountId,
- isDefault: updatedDiscount.default,
- action: "discount-updated",
+ groupId: partnerGroup?.id,
},
})
: Promise.resolve(),