-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Fix race conditions in partner create-and-enroll upsert #4237
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
7
commits into
main
Choose a base branch
from
fix-partner-upsert
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.
+226
−47
Open
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6adbf6a
Split partner enroll into race-safe get-or-create helpers
devkiran aa01515
Only fall back on email unique conflicts when creating partners
devkiran 604185a
Conflict when concurrent enroll requests a different tenantId
devkiran bbd8502
Merge branch 'main' into fix-partner-upsert
devkiran 2e5cac2
Merge branch 'main' into fix-partner-upsert
devkiran 8041e0c
Merge branch 'main' into fix-partner-upsert
devkiran a82e760
Merge branch 'main' into fix-partner-upsert
steven-tey 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
Some comments aren't visible on the classic Files Changed page.
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
112 changes: 112 additions & 0 deletions
112
apps/web/lib/api/partners/create-or-get-program-enrollment.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,112 @@ | ||
| import { createId } from "@/lib/api/create-id"; | ||
| import { prisma } from "@/lib/prisma"; | ||
| import { Prisma, ProgramEnrollment } from "@prisma/client"; | ||
| import { throwIfExistingTenantEnrollmentExists } from "./throw-if-existing-tenant-id-exists"; | ||
|
|
||
| // Attempts to create a program enrollment. | ||
| // If another request creates it concurrently, returns the existing enrollment. | ||
| export async function createOrGetProgramEnrollment({ | ||
| programId, | ||
| partnerId, | ||
| tenantId, | ||
| status, | ||
| groupId, | ||
| clickRewardId, | ||
| leadRewardId, | ||
| saleRewardId, | ||
| referralRewardId, | ||
| discountId, | ||
| enrolledAt, | ||
| }: Pick< | ||
| ProgramEnrollment, | ||
| | "partnerId" | ||
| | "programId" | ||
| | "tenantId" | ||
| | "status" | ||
| | "groupId" | ||
| | "clickRewardId" | ||
| | "leadRewardId" | ||
| | "saleRewardId" | ||
| | "referralRewardId" | ||
| | "discountId" | ||
| > & { | ||
| enrolledAt?: Date; | ||
| }) { | ||
| try { | ||
| const programEnrollment = await prisma.programEnrollment.create({ | ||
| data: { | ||
| id: createId({ prefix: "pge_" }), | ||
| partnerId, | ||
| programId, | ||
| tenantId, | ||
| status, | ||
| groupId, | ||
| clickRewardId, | ||
| leadRewardId, | ||
| saleRewardId, | ||
| referralRewardId, | ||
| discountId, | ||
| ...(enrolledAt && { | ||
| createdAt: enrolledAt, | ||
| }), | ||
| }, | ||
| include: { | ||
| partner: { | ||
| include: { | ||
| platforms: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| return { | ||
| programEnrollment, | ||
| created: true as const, | ||
| }; | ||
| } catch (error) { | ||
| if ( | ||
| error instanceof Prisma.PrismaClientKnownRequestError && | ||
| error.code === "P2002" | ||
| ) { | ||
| console.info( | ||
| "[createOrGetProgramEnrollment] Unique constraint conflict (P2002), falling back to find", | ||
| { target: error.meta?.target }, | ||
| ); | ||
|
|
||
| // Same partner already enrolled (concurrent create on partnerId_programId) | ||
| const programEnrollment = await prisma.programEnrollment.findUnique({ | ||
| where: { | ||
| partnerId_programId: { | ||
| partnerId, | ||
| programId, | ||
| }, | ||
| }, | ||
| include: { | ||
| links: true, | ||
| partner: { | ||
| include: { | ||
| platforms: true, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| if (programEnrollment) { | ||
| return { | ||
| programEnrollment, | ||
| created: false as const, | ||
| }; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| // Conflict was on tenantId_programId — another partner owns this tenant | ||
| if (tenantId) { | ||
| await throwIfExistingTenantEnrollmentExists({ | ||
| tenantId, | ||
| programId, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| throw error; | ||
| } | ||
| } | ||
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,68 @@ | ||
| import { prisma } from "@/lib/prisma"; | ||
| import { Prisma } from "@prisma/client"; | ||
| import { generatePartnerUsername } from "./generate-partner-username"; | ||
|
|
||
| // This helper finds first, creates if missing, | ||
| // and on unique-constraint conflict falls back to find by email. | ||
| export async function getOrCreatePartner({ | ||
| email, | ||
| create, | ||
| }: { | ||
| email: string; | ||
| create: Omit<Prisma.PartnerUncheckedCreateInput, "username">; | ||
| }) { | ||
| const partner = await prisma.partner.findUnique({ | ||
| where: { | ||
| email, | ||
| }, | ||
| }); | ||
|
|
||
| if (partner) { | ||
| return { | ||
| partner, | ||
| created: false, | ||
| }; | ||
| } | ||
|
|
||
| try { | ||
| const username = await generatePartnerUsername({ | ||
| email, | ||
| name: typeof create.name === "string" ? create.name : null, | ||
| }); | ||
|
|
||
| const partner = await prisma.partner.create({ | ||
| data: { | ||
| ...create, | ||
| username, | ||
| }, | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| return { | ||
| partner, | ||
| created: true, | ||
| }; | ||
| } catch (error) { | ||
| if ( | ||
| error instanceof Prisma.PrismaClientKnownRequestError && | ||
| error.code === "P2002" | ||
| ) { | ||
| console.info( | ||
| "[getOrCreatePartner] Unique constraint conflict (P2002), falling back to find", | ||
| { target: error.meta?.target }, | ||
| ); | ||
|
|
||
| const partner = await prisma.partner.findUniqueOrThrow({ | ||
| where: { | ||
| email, | ||
| }, | ||
| }); | ||
|
|
||
| return { | ||
| partner, | ||
| created: false, | ||
| }; | ||
| } | ||
|
|
||
| throw error; | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
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.