The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
sync discounts changes
Kiran K4029868bec87
diff --git a/apps/web/app/api/cron/partners/sync-discounts/route.ts b/apps/web/app/api/cron/partners/sync-discounts/route.tsindex 7914a0f063..8721d6e1db 100644--- a/apps/web/app/api/cron/partners/sync-discounts/route.ts+++ b/apps/web/app/api/cron/partners/sync-discounts/route.ts@@ -1,10 +1,8 @@import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { linkCache } from "@/lib/api/links/cache";-import { qstash } from "@/lib/cron";+import { CACHE_EXPIRATION, linkCache } from "@/lib/api/links/cache";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";@@ -13,22 +11,19 @@ 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+// This route is used to invalidate the partnerlink cache when a discount is created/updated/deleted.+// POST /api/cron/partners/sync-discountsexport 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;+ const { programId, discountId, isDefault, action } = body;- // If the discount is created or updated, we need to add it to the Redis cacheif (action === "discount-created" || action === "discount-updated") {const discount = await prisma.discount.findUnique({where: {@@ -40,62 +35,56 @@ export async function POST(req: Request) {return new Response("Discount not found.");}- const links = await prisma.link.findMany({- where: {- programId,- programEnrollment: {- discountId: isDefault ? null : discountId,- },- },- include: {- webhooks: {- select: {- id: true,+ let page = 0;+ let total = 0;+ const take = 1000;++ while (true) {+ const links = await prisma.link.findMany({+ where: {+ programId,+ programEnrollment: {+ discountId: isDefault ? null : discountId,},- },- programEnrollment: {- select: {- partner: {- select: {- id: true,- name: true,- image: true,+ OR: [+ {+ updatedAt: {+ gt: new Date(Date.now() - CACHE_EXPIRATION * 1000),},},- },+ {+ lastClicked: {+ gt: new Date(Date.now() - CACHE_EXPIRATION * 1000),+ },+ },+ ],},- },- take: PAGE_SIZE,- skip: (page - 1) * PAGE_SIZE,- });+ select: {+ id: true,+ domain: true,+ key: true,+ },+ take,+ skip: page * take,+ });- if (links.length === 0) {- return new Response("No more links to process. Exiting...");- }+ if (links.length === 0) {+ break;+ }- 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,- },- });+ await linkCache.expireMany(links);- return new Response("OK");+ page += 1;+ total += links.length;+ }++ return new Response(`Invalidated ${total} links.`);}- // If the discount is deleted, we need to remove it from the Redis cacheif (action === "discount-deleted") {let page = 0;+ let total = 0;+ const take = 1000;while (true) {let partnerIds: string[] = [];@@ -104,7 +93,7 @@ export async function POST(req: Request) {partnerIds =(await redis.lpop<string[]>(`discount-partners:${discountId}`,- PAGE_SIZE,+ take,)) || [];// There won't be any entries in Redis for the default discount@@ -125,44 +114,39 @@ export async function POST(req: Request) {}),discountId: null,},- },- include: {- webhooks: {- select: {- id: true,+ OR: [+ {+ updatedAt: {+ gt: new Date(Date.now() - CACHE_EXPIRATION * 1000),+ },},- },- programEnrollment: {- select: {- partner: {- select: {- id: true,- name: true,- image: true,- },+ {+ lastClicked: {+ gt: new Date(Date.now() - CACHE_EXPIRATION * 1000),},},- },+ ],},- take: PAGE_SIZE,- skip: page * PAGE_SIZE,+ select: {+ id: true,+ domain: true,+ key: true,+ },+ take,+ skip: page * take,});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,- })),- );+ await linkCache.expireMany(links);page += 1;+ total += links.length;}++ return new Response(`Invalidated ${total} links.`);}return new Response("OK");diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.tsindex 2610b83a2e..46de1bb8b5 100644--- a/apps/web/lib/actions/partners/update-discount.ts+++ b/apps/web/lib/actions/partners/update-discount.ts@@ -5,7 +5,7 @@ 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 { APP_DOMAIN_WITH_NGROK, deepEqual } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { authActionClient } from "../safe-action";@@ -29,7 +29,7 @@ export const updateDiscountAction = authActionClientprogramId,});- await getDiscountOrThrow({+ const discount = await getDiscountOrThrow({programId,discountId,});@@ -58,7 +58,7 @@ export const updateDiscountAction = authActionClientthrow new Error("Default discount cannot be updated with partners.");}- await prisma.discount.update({+ const updatedDiscount = await prisma.discount.update({where: {id: discountId,},@@ -85,6 +85,7 @@ export const updateDiscountAction = authActionClientdiscountId,},}),+// remove discountId from partners not in partnerIdsprisma.programEnrollment.updateMany({where: {@@ -102,14 +103,33 @@ export const updateDiscountAction = authActionClient}waitUntil(- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/sync-discounts`,- body: {- programId,- discountId,- isDefault,- action: "discount-updated",- },- }),+ (async () => {+ const shouldExpireCache = !deepEqual(+ {+ amount: discount.amount,+ type: discount.type,+ maxDuration: discount.maxDuration,+ },+ {+ amount: updatedDiscount.amount,+ type: updatedDiscount.type,+ maxDuration: updatedDiscount.maxDuration,+ },+ );++ if (!shouldExpireCache) {+ return;+ }++ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/sync-discounts`,+ body: {+ programId,+ discountId,+ isDefault,+ action: "discount-updated",+ },+ });+ })(),);});diff --git a/apps/web/lib/api/links/cache.ts b/apps/web/lib/api/links/cache.tsindex a6721f59cc..2e581d3c8c 100644--- a/apps/web/lib/api/links/cache.ts+++ b/apps/web/lib/api/links/cache.ts@@ -8,7 +8,7 @@ import { ExpandedLink } from "./utils/transform-link";* Caveat: we don't set expiration for links with webhooks since it's expensive* to fetch and set on-demand inside link middleware.*/-const CACHE_EXPIRATION = 60 * 60 * 24;+export const CACHE_EXPIRATION = 60 * 60 * 24;class LinkCache {async mset(links: ExpandedLink[]) {