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.

Page discount link cache invalidation and route coupon deletes through detach.

Kiran Ka28b2711139f
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
deleted file mode 100644
index aa11b873b9..0000000000
--- a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { withCron } from "@/lib/cron/with-cron";
-import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
-import { prisma } from "@/lib/prisma";
-import * as z from "zod/v4";
-import { logAndRespond } from "../../utils";
-
-export const dynamic = "force-dynamic";
-
-const schema = z.object({
- groupId: z.string(),
- partnerIds: z
- .array(z.string())
- .optional()
- .describe(
- "If provided, only invalidate the cache for the given partner ids.",
- ),
-});
-
-// Shim for in-flight QStash messages published to the old cron URL.
-// New callers should dispatch invalidateLinksForDiscountsJob.
-// POST /api/cron/links/invalidate-for-discounts
-export const POST = withCron(async ({ rawBody }) => {
- const { groupId, partnerIds } = schema.parse(JSON.parse(rawBody));
-
- const group = await prisma.partnerGroup.findUnique({
- where: {
- id: groupId,
- },
- select: {
- programId: true,
- },
- });
-
- if (!group) {
- return logAndRespond(`Group ${groupId} not found.`, {
- logLevel: "error",
- });
- }
-
- const resolvedPartnerIds =
- partnerIds ??
- (
- await prisma.programEnrollment.findMany({
- where: {
- groupId,
- },
- select: {
- partnerId: true,
- },
- })
- ).map(({ partnerId }) => partnerId);
-
- if (resolvedPartnerIds.length === 0) {
- return logAndRespond(`No program enrollments found for group ${groupId}.`);
- }
-
- await invalidateLinksForDiscountsJob.dispatch({
- type: "partners",
- programId: group.programId,
- partnerIds: resolvedPartnerIds,
- });
-
- return logAndRespond(`Expired cache for partners in group ${groupId}.`);
-});
diff --git a/apps/web/app/(ee)/api/cron/rewards/process/route.ts b/apps/web/app/(ee)/api/cron/rewards/process/route.ts
index 1b1213ad28..47a6b7a531 100644
--- a/apps/web/app/(ee)/api/cron/rewards/process/route.ts
+++ b/apps/web/app/(ee)/api/cron/rewards/process/route.ts
@@ -135,9 +135,13 @@ export const POST = withCron(async ({ rawBody }) => {
const programEnrollments = await prisma.programEnrollment.findMany({
where: {
groupId: group.id,
- status: {
- notIn: INACTIVE_ENROLLMENT_STATUSES,
- },
+ // reward-deleted must also clear banned/deactivated/rejected enrollments.
+ // Those FKs block orphan hard-delete. Notifications stay active-only below.
+ ...(event !== "reward-deleted" && {
+ status: {
+ notIn: INACTIVE_ENROLLMENT_STATUSES,
+ },
+ }),
...(startAfterProgramEnrollmentId && {
id: {
gt: startAfterProgramEnrollmentId,
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
index fab9622987..d4eb6e765c 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts
@@ -1,13 +1,11 @@
import { getWorkspaceUsers } from "@/lib/api/get-workspace-users";
-import { getPartnersByDiscountIds } from "@/lib/discounts/get-partners-by-discount-ids";
-import { invalidateLinksForDiscountsJob } from "@/lib/jobs/handlers/invalidate-links-for-discounts-job";
+import { dispatchWorkflows } from "@/lib/jobs/publish-workflows";
import { prisma } from "@/lib/prisma";
import { sendBatchEmail } from "@dub/email";
import { VARIANT_TO_FROM_MAP } from "@dub/email/resend/constants";
import DiscountDeleted from "@dub/email/templates/discount-deleted";
import { pluck } from "@dub/utils";
import { DiscountProvider } from "@prisma/client";
-import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
@@ -44,8 +42,6 @@ export async function couponDeleted({
}
const discountIds = pluck(discounts, "id");
- const partners = await getPartnersByDiscountIds({ discountIds });
- const partnerIds = pluck(partners, "id");
await prisma.$transaction(async (tx) => {
await tx.partnerGroup.updateMany({
@@ -59,72 +55,50 @@ export async function couponDeleted({
},
});
- await tx.programEnrollment.updateMany({
+ // Soft delete the discounts
+ await tx.discount.updateMany({
where: {
- discountId: {
+ id: {
in: discountIds,
},
},
data: {
- discountId: null,
+ programId: null,
},
});
+ });
- await tx.discountCode.deleteMany({
- where: {
- discountId: {
- in: discountIds,
- },
+ await dispatchWorkflows(
+ discountIds.map((discountId) => ({
+ name: "detach-discount-workflow" as const,
+ payload: {
+ programId,
+ discountId,
},
- });
-
- await tx.discount.deleteMany({
- where: {
- id: {
- in: discountIds,
- },
+ options: {
+ label: discountId,
+ deduplicationId: `detach-discount-${discountId}`,
},
- });
- });
-
- waitUntil(
- (async () => {
- const { users } = await getWorkspaceUsers({
- workspaceId: workspace.id,
- role: "owner",
- });
+ })),
+ );
- await Promise.allSettled([
- ...(partnerIds.length > 0
- ? [
- invalidateLinksForDiscountsJob.dispatch(
- {
- type: "partners",
- programId,
- partnerIds,
- },
- {
- label: coupon.id,
- },
- ),
- ]
- : []),
+ const { users } = await getWorkspaceUsers({
+ workspaceId: workspace.id,
+ role: "owner",
+ });
- sendBatchEmail(
- users.map((user) => ({
- from: VARIANT_TO_FROM_MAP.notifications,
- to: user.email,
- subject: "Your discount has been deleted",
- react: DiscountDeleted({
- email: user.email,
- coupon: {
- id: coupon.id,
- },
- }),
- })),
- ),
- ]);
- })(),
+ await sendBatchEmail(
+ users.map((user) => ({
+ from: VARIANT_TO_FROM_MAP.notifications,
+ to: user.email,
+ subject: "Your discount has been deleted",
+ react: DiscountDeleted({
+ email: user.email,
+ coupon: {
+ id: coupon.id,
+ },
+ }),
+ })),
);
return {
diff --git a/apps/web/lib/api/partners/update-partner-link.ts b/apps/web/lib/api/partners/update-partner-link.ts
index 1d02c6e77f..0d536bb1e6 100644
--- a/apps/web/lib/api/partners/update-partner-link.ts
+++ b/apps/web/lib/api/partners/update-partner-link.ts
@@ -164,6 +164,7 @@ export async function updatePartnerLink({
waitUntil(
Promise.allSettled([
linkCache.expireMany([link]),
+
trackLinkRewardOverrideLog({
workspaceId: workspace.id,
programId,
diff --git a/apps/web/lib/discounts/attach-discount.ts b/apps/web/lib/discounts/attach-discount.ts
index d161621a71..d4df6f86e0 100644
--- a/apps/web/lib/discounts/attach-discount.ts
+++ b/apps/web/lib/discounts/attach-discount.ts
@@ -58,34 +58,72 @@ export async function attachDiscount({
if (enrollments.length > 0) {
const enrollmentIds = pluck(enrollments, "id");
- const [{ count }] = await prisma.$transaction([
- prisma.programEnrollment.updateMany({
+ // Re-check liveness inside the transaction so a concurrent soft-delete
+ // (clears PartnerGroup.discountId / Discount.programId) cannot stamp this id
+ const count = await prisma.$transaction(async (tx) => {
+ const stillValid = await tx.discount.findFirst({
+ where: {
+ id: discount.id,
+ programId: {
+ not: null,
+ },
+ defaultForPartnerGroup: {
+ is: {
+ id: groupId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!stillValid) {
+ return null;
+ }
+
+ const { count } = await tx.programEnrollment.updateMany({
where: {
id: {
in: enrollmentIds,
},
groupId,
discountId: null,
+ partnerGroup: {
+ discountId: discount.id,
+ },
},
data: {
discountId: discount.id,
},
- }),
+ });
- prisma.discountCode.updateMany({
+ // Only stamp codes for enrollments that still point at this discount
+ // (skips partners who received a partner-level override mid-batch)
+ await tx.discountCode.updateMany({
where: {
discountId: null,
programEnrollment: {
id: {
in: enrollmentIds,
},
+ discountId: discount.id,
},
},
data: {
discountId: discount.id,
},
- }),
- ]);
+ });
+
+ return count;
+ });
+
+ if (count === null) {
+ console.info(
+ `Discount ${discount.id} is no longer the group default. Skipping...`,
+ );
+ return null;
+ }
console.info(
`Attached discount ${discount.id} to ${count} enrollments in group ${groupId}.`,
@@ -98,6 +136,31 @@ export async function attachDiscount({
};
}
+ // Final liveness check before side effects (invalidate / auto-provision)
+ const stillValid = await prisma.discount.findFirst({
+ where: {
+ id: discount.id,
+ programId: {
+ not: null,
+ },
+ defaultForPartnerGroup: {
+ is: {
+ id: groupId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (!stillValid) {
+ console.info(
+ `Discount ${discount.id} is no longer the group default. Skipping...`,
+ );
+ return null;
+ }
+
await Promise.all([
invalidateLinksForDiscountsJob.dispatch(
{ type: "discount", discountId: discount.id },
diff --git a/apps/web/lib/discounts/get-partners-by-discount-ids.ts b/apps/web/lib/discounts/get-partners-by-discount-ids.ts
deleted file mode 100644
index debb55abe9..0000000000
--- a/apps/web/lib/discounts/get-partners-by-discount-ids.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { Partner } from "@prisma/client";
-
-export async function getPartnersByDiscountIds({
- discountIds,
-}: {
- discountIds: string[];
-}): Promise<Pick<Partner, "id">[]> {
- if (discountIds.length === 0) {
- return [];
- }
-
- const [enrollments, linkRewards] = await Promise.all([
- prisma.programEnrollment.findMany({
- where: {
- discountId: {
- in: discountIds,
- },
- },
- select: {
- partnerId: true,
- },
- }),
-
- prisma.linkReward.findMany({
- where: {
- discountId: {
- in: discountIds,
- },
- },
- select: {
- link: {
- select: {
- partnerId: true,
- },
- },
- },
- }),
- ]);
-
- return [
- ...new Set([
- ...enrollments.map((enrollment) => enrollment.partnerId),
- ...linkRewards.flatMap((linkReward) =>
- linkReward.link.partnerId ? [linkReward.link.partnerId] : [],
- ),
- ]),
- ].map((id) => ({ id }));
-}
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.ts
index a3e56d5ef2..7459f20519 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,5 +1,7 @@
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 * as z from "zod/v4";
import { defineJob } from "../index";
@@ -9,6 +11,8 @@ const inputSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("discount"),
discountId: z.string(),
+ phase: z.enum(["enrollment", "linkReward"]).optional(),
+ startingAfter: z.string().optional(),
}),
// Discount was unassigned or deleted; expire these partners' program links.
@@ -20,62 +24,43 @@ const inputSchema = z.discriminatedUnion("type", [
]);
type InvalidateLinksForDiscountsInput = z.infer<typeof inputSchema>;
+type DiscountInput = Extract<
+ InvalidateLinksForDiscountsInput,
+ { type: "discount" }
+>;
+type PartnersInput = Extract<
+ InvalidateLinksForDiscountsInput,
+ { type: "partners" }
+>;
-// Invalidates the partner link cache when a discount is created/updated/deleted.
+// 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)
export const invalidateLinksForDiscountsJob = defineJob({
name: "invalidate-links-for-discounts-job",
schema: inputSchema,
async handle(input) {
- const links = await findLinksToInvalidate(input);
-
- if (links.length === 0) {
- console.info(`No links found to invalidate for discount. Skipping...`);
+ if (input.type === "partners") {
+ await invalidateLinksByPartnerIds(input);
return;
}
- const linkChunks = chunk(links, 100);
-
- for (const linkChunk of linkChunks) {
- await linkCache.expireMany(linkChunk);
- }
-
- console.info(`Expired cache for ${links.length} links.`);
+ await invalidateLinksByDiscountId(input);
},
});
-async function findLinksToInvalidate(input: InvalidateLinksForDiscountsInput) {
- if (input.type === "discount") {
- return prisma.link.findMany({
- where: {
- OR: [
- {
- programEnrollment: {
- is: {
- discountId: input.discountId,
- },
- },
- },
- {
- linkReward: {
- is: {
- discountId: input.discountId,
- },
- },
- },
- ],
- },
- select: {
- domain: true,
- key: true,
- },
- });
- }
+async function invalidateLinksByPartnerIds({
+ programId,
+ partnerIds,
+}: PartnersInput) {
+ const partnerIdBatch = partnerIds.slice(0, CRON_BATCH_SIZE);
+ const remainingPartnerIds = partnerIds.slice(CRON_BATCH_SIZE);
- return prisma.link.findMany({
+ const links = await prisma.link.findMany({
where: {
- programId: input.programId,
+ programId,
partnerId: {
- in: input.partnerIds,
+ in: partnerIdBatch,
},
},
select: {
@@ -83,4 +68,142 @@ async function findLinksToInvalidate(input: InvalidateLinksForDiscountsInput) {
key: true,
},
});
+
+ await expireLinkCache(links);
+
+ if (remainingPartnerIds.length > 0) {
+ await invalidateLinksForDiscountsJob.dispatch({
+ type: "partners",
+ programId,
+ partnerIds: remainingPartnerIds,
+ });
+ }
+}
+
+async function invalidateLinksByDiscountId({
+ discountId,
+ phase = "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,
+ },
+ },
+ },
+ orderBy: {
+ id: "asc",
+ },
+ take: CRON_BATCH_SIZE,
+ ...(startingAfter && {
+ skip: 1,
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ });
+
+ await expireLinkCache(enrollments.flatMap((enrollment) => enrollment.links));
+
+ if (enrollments.length === CRON_BATCH_SIZE) {
+ await invalidateLinksForDiscountsJob.dispatch({
+ type: "discount",
+ discountId,
+ phase: "enrollment",
+ startingAfter: enrollments[enrollments.length - 1].id,
+ });
+ 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,
+ },
+ select: {
+ id: true,
+ link: {
+ select: {
+ domain: true,
+ key: true,
+ },
+ },
+ },
+ orderBy: {
+ id: "asc",
+ },
+ take: CRON_BATCH_SIZE,
+ ...(startingAfter && {
+ skip: 1,
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ });
+
+ await expireLinkCache(linkRewards.map(({ link }) => link));
+
+ if (linkRewards.length === CRON_BATCH_SIZE) {
+ await invalidateLinksForDiscountsJob.dispatch({
+ type: "discount",
+ discountId,
+ phase: "linkReward",
+ startingAfter: linkRewards[linkRewards.length - 1].id,
+ });
+ }
+}
+
+async function expireLinkCache(links: Pick<LinkProps, "domain" | "key">[]) {
+ if (links.length === 0) {
+ return;
+ }
+
+ const linkChunks = chunk(links, 100);
+
+ for (const linkChunk of linkChunks) {
+ await linkCache.expireMany(linkChunk);
+ }
+
+ console.info(`Expired cache for ${links.length} links.`);
}