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.

retry customer write conflicts and clarify unique-key errors

Kiran Kb4da2fd76412
diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.ts
index 6b301c3edc..00ef2869a7 100644
--- a/apps/web/lib/api/commissions/create-manual-commissions.ts
+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts
@@ -438,6 +438,10 @@ async function resolveLinkAndCustomer(args: ResolveLinkAndCustomerArgs) {
* - P2002: the update sets a `stripeCustomerId` already used by another customer.
* - P2025: the create hit one of the other unique keys, so the fallback lookup
* by `(projectId, externalId)` found nothing.
+ *
+ * P2034 (write conflict / deadlock) is retried: MySQL can deadlock concurrent
+ * inserts that collide on the same unique index, and the retry then resolves
+ * to one of the cases above.
*/
async function createOrUpdateCustomer({
workspace,
@@ -454,56 +458,77 @@ async function createOrUpdateCustomer({
const { id, name, email, avatar, externalId, stripeCustomerId, country } =
customer;
- try {
- const { customer: resolvedCustomer, created } = await getOrCreateCustomer({
- where: {
- projectId_externalId: {
- projectId: workspace.id,
- externalId,
+ // Retry on MySQL deadlocks (P2034) from concurrent inserts on the same unique key
+ const maxAttempts = 3;
+
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const { customer: resolvedCustomer, created } = await getOrCreateCustomer(
+ {
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId,
+ },
+ },
+ create: {
+ id,
+ name,
+ email,
+ avatar,
+ externalId,
+ stripeCustomerId,
+ linkId,
+ country,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ },
},
- },
- create: {
- id,
- name,
- email,
- avatar,
- externalId,
- stripeCustomerId,
- linkId,
- country,
- projectId: workspace.id,
- projectConnectId: workspace.stripeConnectId,
- },
- });
+ );
- if (created) {
- return resolvedCustomer;
- }
+ if (created) {
+ return resolvedCustomer;
+ }
- return await prisma.customer.update({
- where: {
- id: resolvedCustomer.id,
- },
- data: {
- name,
- email,
- avatar,
- country,
- stripeCustomerId,
- },
- });
- } catch (error) {
- if (
- error instanceof Prisma.PrismaClientKnownRequestError &&
- (error.code === "P2002" || error.code === "P2025")
- ) {
- throw new DubApiError({
- code: "conflict",
- message: `A customer with external ID ${externalId} or Stripe customer ID ${stripeCustomerId} already exists.`,
+ return await prisma.customer.update({
+ where: {
+ id: resolvedCustomer.id,
+ },
+ data: {
+ name,
+ email,
+ avatar,
+ country,
+ stripeCustomerId,
+ },
});
- }
+ } catch (error) {
+ if (!(error instanceof Prisma.PrismaClientKnownRequestError)) {
+ throw error;
+ }
+
+ if (error.code === "P2034" && attempt < maxAttempts) {
+ continue;
+ }
+
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: `The Stripe customer ID ${stripeCustomerId} is already linked to a different customer than external ID ${externalId}.`,
+ });
+ }
+
+ if (error.code === "P2025") {
+ throw new DubApiError({
+ code: "conflict",
+ message: stripeCustomerId
+ ? `The Stripe customer ID ${stripeCustomerId} is already linked to a customer with a different external ID.`
+ : `A customer with external ID ${externalId} already exists for this Stripe account.`,
+ });
+ }
- throw error;
+ throw error;
+ }
}
}
diff --git a/apps/web/playwright/api/commissions/commissions-create.spec.ts b/apps/web/playwright/api/commissions/commissions-create.spec.ts
index bda20f2f83..6c5838d513 100644
--- a/apps/web/playwright/api/commissions/commissions-create.spec.ts
+++ b/apps/web/playwright/api/commissions/commissions-create.spec.ts
@@ -74,6 +74,32 @@ async function seedDiscountCode({
return { code, linkId: link.id };
}
+async function seedCustomer({
+ workspaceId,
+ stripeCustomerId,
+}: {
+ workspaceId: string;
+ stripeCustomerId?: string;
+}) {
+ const { externalId, name } = randomCustomer();
+
+ return prisma.customer.create({
+ data: {
+ id: createId({ prefix: "cus_" }),
+ name,
+ externalId,
+ stripeCustomerId,
+ projectId: workspaceId,
+ },
+ });
+}
+
+async function deleteCustomers(ids: string[]) {
+ await prisma.customer.deleteMany({
+ where: { id: { in: ids } },
+ });
+}
+
test.describe("Custom commissions", () => {
test("creates a custom commission", async ({ api, program }) => {
const description = `custom-${nanoid()}`;
@@ -301,6 +327,224 @@ test.describe("Lead commissions", () => {
});
});
+test.describe("Inline customer", () => {
+ test("updates the existing customer with the same externalId", async ({
+ api,
+ program,
+ workspace,
+ }) => {
+ const customer = customerBody();
+ const stripeCustomerId = `cus_pw_${nanoid()}`;
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "lead",
+ partnerId,
+ customer,
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ expect(
+ await api.post("/api/commissions", {
+ type: "lead",
+ partnerId,
+ customer: {
+ ...customer,
+ name: "Updated name",
+ stripeCustomerId,
+ },
+ }),
+ ).toEqual(expectedQueuedResponse);
+
+ expect(
+ await prisma.customer.findMany({
+ where: {
+ projectId: workspace.id,
+ externalId: customer.externalId,
+ },
+ select: {
+ name: true,
+ stripeCustomerId: true,
+ },
+ }),
+ ).toEqual([{ name: "Updated name", stripeCustomerId }]);
+ });
+ });
+
+ test("creates one customer for concurrent requests with the same externalId", async ({
+ api,
+ program,
+ workspace,
+ }) => {
+ const customer = customerBody();
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ const responses = await Promise.all(
+ Array.from({ length: 5 }, () =>
+ api.post("/api/commissions", {
+ type: "lead",
+ partnerId,
+ customer,
+ }),
+ ),
+ );
+
+ expect(responses).toEqual(
+ Array.from({ length: 5 }, () => expectedQueuedResponse),
+ );
+
+ expect(
+ await prisma.customer.count({
+ where: {
+ projectId: workspace.id,
+ externalId: customer.externalId,
+ },
+ }),
+ ).toEqual(1);
+ });
+ });
+
+ test.describe("conflicts", () => {
+ test("rejects a stripeCustomerId owned by another customer", async ({
+ api,
+ program,
+ workspace,
+ }) => {
+ const customer = customerBody();
+ const stripeCustomerId = `cus_pw_${nanoid()}`;
+ const owner = await seedCustomer({
+ workspaceId: workspace.id,
+ stripeCustomerId,
+ });
+
+ try {
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "lead",
+ partnerId,
+ customer: { ...customer, stripeCustomerId },
+ }),
+ ).toEqual(
+ apiError({
+ code: "conflict",
+ message: `The Stripe customer ID ${stripeCustomerId} is already linked to a customer with a different external ID.`,
+ }),
+ );
+
+ expect(
+ await prisma.customer.count({
+ where: {
+ projectId: workspace.id,
+ externalId: customer.externalId,
+ },
+ }),
+ ).toEqual(0);
+ });
+ } finally {
+ await deleteCustomers([owner.id]);
+ }
+ });
+
+ test("rejects updating a customer to a stripeCustomerId owned by another customer", async ({
+ api,
+ program,
+ workspace,
+ }) => {
+ const stripeCustomerId = `cus_pw_${nanoid()}`;
+ const owner = await seedCustomer({
+ workspaceId: workspace.id,
+ stripeCustomerId,
+ });
+ const existing = await seedCustomer({
+ workspaceId: workspace.id,
+ });
+
+ try {
+ await withCommissionPartner(api, program, async (partnerId) => {
+ expect(
+ await api.post("/api/commissions", {
+ type: "lead",
+ partnerId,
+ customer: {
+ ...customerBody(),
+ externalId: existing.externalId,
+ stripeCustomerId,
+ },
+ }),
+ ).toEqual(
+ apiError({
+ code: "conflict",
+ message: `The Stripe customer ID ${stripeCustomerId} is already linked to a different customer than external ID ${existing.externalId}.`,
+ }),
+ );
+
+ expect(
+ await prisma.customer.findMany({
+ where: {
+ id: { in: [owner.id, existing.id] },
+ },
+ select: {
+ id: true,
+ stripeCustomerId: true,
+ },
+ orderBy: {
+ stripeCustomerId: "desc",
+ },
+ }),
+ ).toEqual([
+ { id: owner.id, stripeCustomerId },
+ { id: existing.id, stripeCustomerId: null },
+ ]);
+ });
+ } finally {
+ await deleteCustomers([owner.id, existing.id]);
+ }
+ });
+
+ test("allows only one concurrent create for the same stripeCustomerId", async ({
+ api,
+ program,
+ workspace,
+ }) => {
+ const stripeCustomerId = `cus_pw_${nanoid()}`;
+ const conflict = apiError({
+ code: "conflict",
+ message: `The Stripe customer ID ${stripeCustomerId} is already linked to a customer with a different external ID.`,
+ });
+
+ await withCommissionPartner(api, program, async (partnerId) => {
+ const responses = await Promise.all(
+ Array.from({ length: 5 }, () =>
+ api.post("/api/commissions", {
+ type: "lead",
+ partnerId,
+ customer: { ...customerBody(), stripeCustomerId },
+ }),
+ ),
+ );
+
+ expect(
+ responses.filter((r) => r.status === expectedQueuedResponse.status),
+ ).toEqual([expectedQueuedResponse]);
+ expect(responses.filter((r) => r.status === conflict.status)).toEqual(
+ Array.from({ length: 4 }, () => conflict),
+ );
+
+ expect(
+ await prisma.customer.count({
+ where: {
+ projectId: workspace.id,
+ stripeCustomerId,
+ },
+ }),
+ ).toEqual(1);
+ });
+ });
+ });
+});
+
test.describe("Sale commissions", () => {
test("creates a sale commission", async ({ api, program }) => {
const invoiceId = `INV_${nanoid()}`;