Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ model WebhookEvent {
stripeEventId String @unique
eventType String
processedAt DateTime
billingFacts Json?
}

model ScheduledMessage {
Expand Down
86 changes: 83 additions & 3 deletions src/__tests__/pages/api/stripe/utils/idempotency.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { setTimeout } from 'node:timers/promises'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import prisma from '@/lib/db'
import type { BillingFacts } from '@/lib/stripe/utils/billing-facts'
import { processEventIdempotently } from '@/lib/stripe/utils/idempotency'
import { withTransaction } from '@/lib/stripe/utils/transaction'

Expand Down Expand Up @@ -39,13 +40,30 @@ describePostgres('Stripe webhook PostgreSQL reliability', () => {
let processorCalls = 0
receiptIds.add(eventId)
scheduledMessageIds.add(scheduledMessageId)
const billingFacts = {
cancelAtPeriodEnd: false,
canceledAt: null,
cancellationReason: null,
currentPeriodEnd: 1_800_000_000,
endedAt: null,
kind: 'subscription',
livemode: true,
occurredAt: 1_700_000_000,
status: 'past_due',
stripeCustomerId: 'cus_rollback',
stripeSubscriptionId: 'sub_rollback',
trialEnd: null,
trialStart: null,
version: 1,
} satisfies BillingFacts

await expect(
withTransaction(
async (tx) =>
await processEventIdempotently(
eventId,
'checkout.session.completed',
'customer.subscription.updated',
billingFacts,
async (transactionClient) => {
processorCalls += 1
await transactionClient.scheduledMessage.create({
Expand Down Expand Up @@ -87,6 +105,7 @@ describePostgres('Stripe webhook PostgreSQL reliability', () => {
await processEventIdempotently(
eventId,
'checkout.session.completed',
undefined,
async () => {
processorCalls += 1
processorStarted.resolve(true)
Expand All @@ -100,7 +119,13 @@ describePostgres('Stripe webhook PostgreSQL reliability', () => {

const secondDelivery = withTransaction(
async (tx) =>
await processEventIdempotently(eventId, 'checkout.session.completed', countProcessor, tx),
await processEventIdempotently(
eventId,
'checkout.session.completed',
undefined,
countProcessor,
tx,
),
)
const deliveries = Promise.allSettled([firstDelivery, secondDelivery])

Expand All @@ -113,11 +138,66 @@ describePostgres('Stripe webhook PostgreSQL reliability', () => {

const laterDelivery = await withTransaction(
async (tx) =>
await processEventIdempotently(eventId, 'checkout.session.completed', countProcessor, tx),
await processEventIdempotently(
eventId,
'checkout.session.completed',
undefined,
countProcessor,
tx,
),
)

expect(laterDelivery.kind).toBe('duplicate')
expect(processorCalls).toBe(1)
await expect(prisma.webhookEvent.count({ where: { stripeEventId: eventId } })).resolves.toBe(1)
}, 20_000)

it('keeps the original billing fact when a later delivery is a duplicate', async () => {
const eventId = `evt_fact_${randomUUID()}`
receiptIds.add(eventId)
const originalFact = {
cancelAtPeriodEnd: false,
canceledAt: null,
cancellationReason: null,
currentPeriodEnd: 1_800_000_000,
endedAt: null,
kind: 'subscription',
livemode: true,
occurredAt: 1_700_000_000,
status: 'active',
stripeCustomerId: 'cus_original',
stripeSubscriptionId: 'sub_original',
trialEnd: null,
trialStart: null,
version: 1,
} satisfies BillingFacts
const laterFact = { ...originalFact, status: 'canceled' } satisfies BillingFacts
const processor = vi.fn<() => Promise<void>>().mockResolvedValue()

await withTransaction(
async (tx) =>
await processEventIdempotently(
eventId,
'customer.subscription.updated',
originalFact,
processor,
tx,
),
)
const duplicate = await withTransaction(
async (tx) =>
await processEventIdempotently(
eventId,
'customer.subscription.updated',
laterFact,
processor,
tx,
),
)

expect(duplicate.kind).toBe('duplicate')
await expect(
prisma.webhookEvent.findUnique({ where: { stripeEventId: eventId } }),
).resolves.toMatchObject({ billingFacts: originalFact })
})
})
47 changes: 45 additions & 2 deletions src/__tests__/pages/api/stripe/utils/idempotency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { Prisma } from '@prisma/client'
import { PrismaClient } from '@prisma/client'
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'

import type { BillingFacts } from '@/lib/stripe/utils/billing-facts'
import { processEventIdempotently } from '@/lib/stripe/utils/idempotency'

describe(processEventIdempotently, () => {
Expand All @@ -10,6 +11,7 @@ describe(processEventIdempotently, () => {
const remove = vi.spyOn(tx.webhookEvent, 'delete')
const findUnique = vi.spyOn(tx.webhookEvent, 'findUnique')
const receipt = {
billingFacts: null,
eventType: 'checkout.session.completed',
id: 'receipt-1',
processedAt: new Date('2026-09-07T12:00:00.000Z'),
Expand All @@ -35,7 +37,7 @@ describe(processEventIdempotently, () => {
.mockResolvedValue()

await expect(
processEventIdempotently('evt_1', 'checkout.session.completed', processor, tx),
processEventIdempotently('evt_1', 'checkout.session.completed', undefined, processor, tx),
).resolves.toStrictEqual({ kind: 'processed' })

expect(processor).toHaveBeenCalledOnce()
Expand All @@ -48,7 +50,7 @@ describe(processEventIdempotently, () => {
const processor = vi.fn<(transaction: Prisma.TransactionClient) => Promise<void>>()

await expect(
processEventIdempotently('evt_1', 'checkout.session.completed', processor, tx),
processEventIdempotently('evt_1', 'checkout.session.completed', undefined, processor, tx),
).resolves.toStrictEqual({ kind: 'duplicate', processedAt: receipt.processedAt })

expect(processor).not.toHaveBeenCalled()
Expand All @@ -62,6 +64,7 @@ describe(processEventIdempotently, () => {
processEventIdempotently(
'evt_1',
'checkout.session.completed',
undefined,
async () => {
await Promise.resolve()
throw processorError
Expand All @@ -73,4 +76,44 @@ describe(processEventIdempotently, () => {
expect(create).toHaveBeenCalledOnce()
expect(remove).not.toHaveBeenCalled()
})

it('stores billing facts on the receipt create', async () => {
const billingFacts = {
cancelAtPeriodEnd: false,
canceledAt: null,
cancellationReason: null,
currentPeriodEnd: 1_800_000_000,
endedAt: null,
kind: 'subscription',
livemode: true,
occurredAt: 1_700_000_000,
status: 'active',
stripeCustomerId: 'cus_test',
stripeSubscriptionId: 'sub_test',
trialEnd: null,
trialStart: null,
version: 1,
} satisfies BillingFacts
const processor = vi
.fn<(transaction: Prisma.TransactionClient) => Promise<void>>()
.mockResolvedValue()

await processEventIdempotently(
'evt_1',
'customer.subscription.updated',
billingFacts,
processor,
tx,
)

expect(create).toHaveBeenCalledWith({
data: {
billingFacts,
eventType: 'customer.subscription.updated',
processedAt: create.mock.calls[0]?.[0].data.processedAt,
stripeEventId: 'evt_1',
},
})
expect(create.mock.calls[0]?.[0].data.processedAt).toBeInstanceOf(Date)
})
})
Loading
Loading