-
Notifications
You must be signed in to change notification settings - Fork 3k
Add async discount processing with versioned cron jobs and soft delete #3967
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
devkiran
wants to merge
3
commits into
main
Choose a base branch
from
discounts-sync
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
apps/web/app/(ee)/api/cron/cleanup/orphaned-discounts/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { withCron } from "@/lib/cron/with-cron"; | ||
| import { prisma } from "@dub/prisma"; | ||
| import { subMinutes } from "date-fns"; | ||
| import { logAndRespond } from "../../utils"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| // The discounts/process cron normally hard-deletes once enrollments are cleared, but a newer | ||
| // discount change for the same group can bump the version and skip stale jobs | ||
| // (e.g. delete then create), leaving the old row behind. This job is a safety net for those orphans. | ||
|
|
||
| // POST /api/cron/cleanup/orphaned-discounts | ||
| export const POST = withCron(async () => { | ||
| const discounts = await prisma.discount.findMany({ | ||
| where: { | ||
| programId: null, | ||
| updatedAt: { | ||
| lt: subMinutes(new Date(), 30), // only look for discounts older than 30 minutes ago | ||
| }, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| _count: { | ||
| select: { | ||
| discountCodes: true, | ||
| programEnrollments: true, | ||
| }, | ||
| }, | ||
| }, | ||
| orderBy: { | ||
| updatedAt: "asc", | ||
| }, | ||
| take: 100, | ||
| }); | ||
|
|
||
| if (discounts.length === 0) { | ||
| return logAndRespond("No orphaned discounts found."); | ||
| } | ||
|
|
||
| const discountsToDelete = discounts.filter((discount) => { | ||
| return ( | ||
| discount._count.programEnrollments === 0 && | ||
| discount._count.discountCodes === 0 | ||
| ); | ||
| }); | ||
|
|
||
| console.log( | ||
| `Found ${discountsToDelete.length} discounts to delete out of ${discounts.length} discounts (some of them are still referenced by program enrollments or discount codes).`, | ||
| ); | ||
|
|
||
| if (discountsToDelete.length === 0) { | ||
| return logAndRespond("No discounts to delete, skipping..."); | ||
| } | ||
|
|
||
| const deletedDiscounts = await prisma.discount.deleteMany({ | ||
| where: { | ||
| id: { | ||
| in: discountsToDelete.map((discount) => discount.id), | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| return logAndRespond( | ||
| `Finished deleting orphaned discounts (${deletedDiscounts.count} discounts deleted).`, | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
apps/web/app/(ee)/api/cron/discount-codes/delete/queue/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import { withCron } from "@/lib/cron/with-cron"; | ||
| import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code"; | ||
| import { prisma } from "@dub/prisma"; | ||
| import { DiscountProvider } from "@dub/prisma/client"; | ||
| import * as z from "zod/v4"; | ||
| import { logAndRespond } from "../../../utils"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| export const maxDuration = 600; | ||
|
|
||
| const inputSchema = z.object({ | ||
| discountId: z.string(), | ||
| provider: z.enum(DiscountProvider), | ||
| }); | ||
|
|
||
| // POST /api/cron/discount-codes/delete/queue | ||
| export const POST = withCron(async ({ rawBody }) => { | ||
| const { discountId, provider } = inputSchema.parse(JSON.parse(rawBody)); | ||
|
|
||
| let startingAfter: string | undefined; | ||
|
|
||
| while (true) { | ||
| const discountCodes = await prisma.discountCode.findMany({ | ||
| where: { | ||
| discountId, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| code: true, | ||
| programId: true, | ||
| }, | ||
| ...(startingAfter && { | ||
| skip: 1, | ||
| cursor: { | ||
| id: startingAfter, | ||
| }, | ||
| }), | ||
| orderBy: { | ||
| id: "asc", | ||
| }, | ||
| take: 500, | ||
| }); | ||
|
|
||
| if (discountCodes.length === 0) { | ||
| break; | ||
| } | ||
|
|
||
| startingAfter = discountCodes[discountCodes.length - 1].id; | ||
|
|
||
| await deleteDiscountCodes( | ||
| discountCodes.map((discountCode) => ({ | ||
| ...discountCode, | ||
| discount: { | ||
| provider, | ||
| }, | ||
| })), | ||
| ); | ||
| } | ||
|
|
||
| return logAndRespond( | ||
| `Finished queuing discount codes for discount ${discountId}.`, | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| import { isStaleDiscountVersion } from "@/lib/api/discounts/discount-version"; | ||
| import { | ||
| discountJobSchema, | ||
| queueDiscountProcessing, | ||
| } from "@/lib/api/discounts/queue-discount-processing"; | ||
| import { withCron } from "@/lib/cron/with-cron"; | ||
| import { INACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners"; | ||
| import { prisma } from "@dub/prisma"; | ||
| import { Prisma } from "@dub/prisma/client"; | ||
| import { logAndRespond } from "../../utils"; | ||
|
|
||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| // POST /api/cron/discounts/process | ||
| export const POST = withCron(async ({ rawBody }) => { | ||
| const input = discountJobSchema.parse(JSON.parse(rawBody)); | ||
|
|
||
| const { | ||
| event, | ||
| groupId, | ||
| version, | ||
| batchNumber, | ||
| discountSnapshot, | ||
| startAfterProgramEnrollmentId, | ||
| } = input; | ||
|
|
||
| const { id: discountId } = discountSnapshot; | ||
|
|
||
| const discount = await prisma.discount.findUnique({ | ||
| where: { | ||
| id: discountId, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| }, | ||
| }); | ||
|
|
||
| if (!discount) { | ||
| return logAndRespond(`Discount ${discountId} not found. Skipping...`); | ||
| } | ||
|
|
||
| const group = await prisma.partnerGroup.findUnique({ | ||
| where: { | ||
| id: groupId, | ||
| }, | ||
| select: { | ||
| id: true, | ||
| }, | ||
| }); | ||
|
|
||
| if (!group) { | ||
| return logAndRespond(`Group ${groupId} not found. Skipping...`); | ||
| } | ||
|
|
||
| const isStaleVersion = await isStaleDiscountVersion({ | ||
| version, | ||
| groupId, | ||
| }); | ||
|
|
||
| if (isStaleVersion) { | ||
| return logAndRespond( | ||
| "Discount changed while processing. Skipping stale discount evaluation.", | ||
| ); | ||
| } | ||
|
|
||
| let data: Prisma.ProgramEnrollmentUpdateManyArgs["data"] | undefined = | ||
| undefined; | ||
|
|
||
| switch (event) { | ||
| case "discount-created": | ||
| data = { discountId: discount.id }; | ||
| break; | ||
|
|
||
| case "discount-deleted": | ||
| data = { discountId: null }; | ||
| break; | ||
| } | ||
|
|
||
| const programEnrollments = await prisma.programEnrollment.findMany({ | ||
| where: { | ||
| groupId: group.id, | ||
| status: { | ||
| notIn: INACTIVE_ENROLLMENT_STATUSES, | ||
| }, | ||
| ...(startAfterProgramEnrollmentId && { | ||
| id: { | ||
| gt: startAfterProgramEnrollmentId, | ||
| }, | ||
| }), | ||
| }, | ||
| select: { | ||
| id: true, | ||
| }, | ||
| orderBy: { | ||
| id: "asc", | ||
| }, | ||
| take: 300, | ||
| }); | ||
|
|
||
| if (programEnrollments.length > 0) { | ||
| await prisma.programEnrollment.updateMany({ | ||
| where: { | ||
| id: { | ||
| in: programEnrollments.map(({ id }) => id), | ||
| }, | ||
| }, | ||
| data: { | ||
| ...data, | ||
| }, | ||
| }); | ||
|
|
||
| const startingAfter = programEnrollments[programEnrollments.length - 1].id; | ||
|
|
||
| await queueDiscountProcessing({ | ||
| ...input, | ||
| startAfterProgramEnrollmentId: startingAfter, | ||
| batchNumber: batchNumber + 1, | ||
| }); | ||
|
|
||
| return logAndRespond( | ||
| `Enqueued next batch (${batchNumber + 1}) for discount ${discountId} for the group ${groupId}.`, | ||
| ); | ||
| } | ||
|
|
||
| // No more program enrollments found, hard delete the discount | ||
| if (event === "discount-deleted") { | ||
| const discountCodes = await prisma.discountCode.count({ | ||
| where: { | ||
| discountId: discount.id, | ||
| }, | ||
| }); | ||
|
|
||
| if (discountCodes > 0) { | ||
| return logAndRespond( | ||
| `Found ${discountCodes} discount codes for discount ${discountId}. Skipping hard delete...`, | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| await prisma.discount.delete({ | ||
| where: { | ||
| id: discount.id, | ||
| }, | ||
| }); | ||
| } catch (error) { | ||
| // Treat already-deleted discount as success so retries can complete | ||
| if (!(error.code === "P2025")) { | ||
| throw new Error( | ||
| `Failed to hard delete discount ${discount.id}: ${error instanceof Error ? error.message : String(error)}`, | ||
| ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return logAndRespond( | ||
| `Finished processing discount ${discountId} for the group ${groupId}.`, | ||
| ); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.