The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Simplify discount link cache invalidation to by partners or discount
Kiran K54675572a4e5
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.tsindex 05497b249a..eff6cc3474 100644--- a/apps/web/lib/actions/partners/update-discount.ts+++ b/apps/web/lib/actions/partners/update-discount.ts@@ -55,7 +55,11 @@ export const updateDiscountAction = authActionClient...(shouldExpireCache? [invalidateLinksForDiscountsJob.dispatch(- { type: "discount", discountId: discount.id },+ {+ by: "discount",+ programId,+ discountId: discount.id,+ },{ label: discount.id },),]diff --git a/apps/web/lib/discounts/attach-discount.ts b/apps/web/lib/discounts/attach-discount.tsindex 9e2554ce92..16ad7e9e55 100644--- a/apps/web/lib/discounts/attach-discount.ts+++ b/apps/web/lib/discounts/attach-discount.ts@@ -179,7 +179,11 @@ export async function attachDiscount({await Promise.all([invalidateLinksForDiscountsJob.dispatch(- { type: "discount", discountId: discount.id },+ {+ by: "discount",+ programId: discount.programId,+ discountId: discount.id,+ },{ label: discount.id },),diff --git a/apps/web/lib/discounts/detach-discount.ts b/apps/web/lib/discounts/detach-discount.tsindex 723754f354..e448582925 100644--- a/apps/web/lib/discounts/detach-discount.ts+++ b/apps/web/lib/discounts/detach-discount.ts@@ -85,7 +85,7 @@ export async function detachDiscountFromProgramEnrollments({await invalidateLinksForDiscountsJob.dispatch({- type: "partners",+ by: "partners",programId,partnerIds: pluck(enrollments, "partnerId"),},@@ -161,7 +161,7 @@ export async function detachDiscountFromLinkRewards({if (partnerIds.length > 0) {await invalidateLinksForDiscountsJob.dispatch({- type: "partners",+ by: "partners",programId,partnerIds,});diff --git a/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.ts b/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.tsindex 7459f20519..6b5bbb0106 100644--- a/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.ts+++ b/apps/web/lib/jobs/handlers/invalidate-links-for-discounts-job.ts@@ -1,172 +1,141 @@import { linkCache } from "@/lib/api/links/cache";import { CRON_BATCH_SIZE } from "@/lib/cron";import { prisma } from "@/lib/prisma";-import { LinkProps } from "@/lib/types";-import { chunk } from "@dub/utils";+import { chunk, pluck } from "@dub/utils";import * as z from "zod/v4";import { defineJob } from "../index";-const inputSchema = z.discriminatedUnion("type", [- // Discount is still assigned to enrollments or link overrides.+const inputSchema = z.discriminatedUnion("by", [+ // Known partners — enrollment/link discount already updated for these ids.z.object({- type: z.literal("discount"),- discountId: z.string(),- phase: z.enum(["enrollment", "linkReward"]).optional(),- startingAfter: z.string().optional(),+ by: z.literal("partners"),+ programId: z.string(),+ partnerIds: z.array(z.string()).min(1),}),- // Discount was unassigned or deleted; expire these partners' program links.+ // Discover who still references this discountId within a program.z.object({- type: z.literal("partners"),+ by: z.literal("discount"),programId: z.string(),- partnerIds: z.array(z.string()).min(1),+ discountId: z.string(),+ source: z.enum(["enrollment", "linkReward"]).optional(),+ startingAfter: z.string().optional(),}),]);type InvalidateLinksForDiscountsInput = z.infer<typeof inputSchema>;-type DiscountInput = Extract<+type PartnersInput = Extract<InvalidateLinksForDiscountsInput,- { type: "discount" }+ { by: "partners" }>;-type PartnersInput = Extract<+type DiscountInput = Extract<InvalidateLinksForDiscountsInput,- { type: "partners" }+ { by: "discount" }>;-// Clears Redis cache for partner links affected by a discount change.-// - "discount": find links via enrollments/link rewards that still have this discount-// - "partners": find links by partner ids (used after the discount was removed)+// Clears Redis cache when a link's resolved discount would change+// (COALESCE(LinkReward.discountId, ProgramEnrollment.discountId)):+// 1. Enrollment discount changed → by: "partners" (or expireMany at call site)+// 2. Link override changed → expireMany at call site (or by: "partners")+// 3. Discount fields changed while still assigned → by: "discount"+// 4. Discount already unassigned → by: "partners"export const invalidateLinksForDiscountsJob = defineJob({name: "invalidate-links-for-discounts-job",schema: inputSchema,async handle(input) {- if (input.type === "partners") {- await invalidateLinksByPartnerIds(input);+ if (input.by === "partners") {+ await expirePartners(input);return;}- await invalidateLinksByDiscountId(input);+ await scanDiscount(input);},});-async function invalidateLinksByPartnerIds({- programId,- partnerIds,-}: PartnersInput) {+async function expirePartners({ programId, partnerIds }: PartnersInput) {const partnerIdBatch = partnerIds.slice(0, CRON_BATCH_SIZE);const remainingPartnerIds = partnerIds.slice(CRON_BATCH_SIZE);- const links = await prisma.link.findMany({- where: {- programId,- partnerId: {- in: partnerIdBatch,- },- },- select: {- domain: true,- key: true,- },+ await expirePartnerLinks({+ programId,+ partnerIds: partnerIdBatch,});- await expireLinkCache(links);-if (remainingPartnerIds.length > 0) {await invalidateLinksForDiscountsJob.dispatch({- type: "partners",+ by: "partners",programId,partnerIds: remainingPartnerIds,});}}-async function invalidateLinksByDiscountId({+// Page enrollments then linkRewards within one program; expire those partners' links.+async function scanDiscount({+ programId,discountId,- phase = "enrollment",+ source = "enrollment",startingAfter,}: DiscountInput) {- if (phase === "enrollment") {- await invalidateEnrollmentLinks({- discountId,- startingAfter,- });- return;- }-- await invalidateLinkRewardLinks({- discountId,- startingAfter,- });-}--async function invalidateEnrollmentLinks({- discountId,- startingAfter,-}: {- discountId: string;- startingAfter?: string;-}) {- const enrollments = await prisma.programEnrollment.findMany({- where: {- discountId,- },- select: {- id: true,- links: {- select: {- domain: true,- key: true,- },+ if (source === "enrollment") {+ const enrollments = await prisma.programEnrollment.findMany({+ where: {+ programId,+ discountId,},- },- orderBy: {- id: "asc",- },- take: CRON_BATCH_SIZE,- ...(startingAfter && {- skip: 1,- cursor: {- id: startingAfter,+ select: {+ id: true,+ partnerId: true,},- }),- });+ orderBy: {+ id: "asc",+ },+ take: CRON_BATCH_SIZE,+ ...(startingAfter && {+ skip: 1,+ cursor: {+ id: startingAfter,+ },+ }),+ });++ await expirePartnerLinks({+ programId,+ partnerIds: pluck(enrollments, "partnerId"),+ });- await expireLinkCache(enrollments.flatMap((enrollment) => enrollment.links));+ if (enrollments.length === CRON_BATCH_SIZE) {+ await invalidateLinksForDiscountsJob.dispatch({+ by: "discount",+ programId,+ discountId,+ source: "enrollment",+ startingAfter: enrollments[enrollments.length - 1].id,+ });+ return;+ }- if (enrollments.length === CRON_BATCH_SIZE) {await invalidateLinksForDiscountsJob.dispatch({- type: "discount",+ by: "discount",+ programId,discountId,- phase: "enrollment",- startingAfter: enrollments[enrollments.length - 1].id,+ source: "linkReward",});return;}- await invalidateLinksForDiscountsJob.dispatch({- type: "discount",- discountId,- phase: "linkReward",- });-}--async function invalidateLinkRewardLinks({- discountId,- startingAfter,-}: {- discountId: string;- startingAfter?: string;-}) {const linkRewards = await prisma.linkReward.findMany({where: {discountId,+ link: {+ programId,+ },},select: {id: true,link: {select: {- domain: true,- key: true,+ partnerId: true,},},},@@ -182,26 +151,57 @@ async function invalidateLinkRewardLinks({}),});- await expireLinkCache(linkRewards.map(({ link }) => link));+ await expirePartnerLinks({+ programId,+ partnerIds: [+ ...new Set(+ linkRewards+ .map(({ link }) => link.partnerId)+ .filter((id): id is string => Boolean(id)),+ ),+ ],+ });if (linkRewards.length === CRON_BATCH_SIZE) {await invalidateLinksForDiscountsJob.dispatch({- type: "discount",+ by: "discount",+ programId,discountId,- phase: "linkReward",+ source: "linkReward",startingAfter: linkRewards[linkRewards.length - 1].id,});}}-async function expireLinkCache(links: Pick<LinkProps, "domain" | "key">[]) {- if (links.length === 0) {+async function expirePartnerLinks({+ programId,+ partnerIds,+}: {+ programId: string;+ partnerIds: string[];+}) {+ if (partnerIds.length === 0) {return;}- const linkChunks = chunk(links, 100);+ const links = await prisma.link.findMany({+ where: {+ programId,+ partnerId: {+ in: partnerIds,+ },+ },+ select: {+ domain: true,+ key: true,+ },+ });++ if (links.length === 0) {+ return;+ }- for (const linkChunk of linkChunks) {+ for (const linkChunk of chunk(links, 100)) {await linkCache.expireMany(linkChunk);}