billing: record one plan start per Checkout

One Checkout sends checkout.session.completed, customer.subscription.created and invoice.paid,
often concurrently; each that re-read the row before another wrote it saw the plan start and
pushed billing.plan_started with its own 'at', so the event ids differed and the team's audit
log showed it twice. A plan starting or ending now carries a once key (subscription id and
period start), so every racer pushes the same event id and the control plane's INSERT OR IGNORE
keeps one.
This commit is contained in:
Neil
2026-11-14 03:45:08 -08:00
parent d12fcb60e9
commit 8104f84b94
3 changed files with 70 additions and 7 deletions
+24 -5
View File
@@ -25,6 +25,15 @@ export type BillingAuditEvent = {
actorUserId?: string
// Flat and small. No price ids, customer ids or card details: plan, interval, seats, cents.
detail?: Record<string, string | number | boolean | null>
/**
* Names the change itself rather than the moment it was seen, for changes that happen once per
* subscription period (a plan starting or ending). Several Stripe events report the same change
* (one Checkout sends checkout.session.completed, customer.subscription.created/updated and
* invoice.paid, often concurrently), and each that reads the row before another wrote it sees the
* change again: with this key they all push the same event id, so the control plane keeps one.
* Never sent.
*/
onceKey?: string
}
type PushEnv = Pick<Env, 'CONTROL_PLANE_TOKEN' | 'SANDBOX_CONTROL_URL' | 'SANDBOX_CONTROL'>
@@ -35,7 +44,9 @@ export function hasTeamAuditLog(accountId: string): boolean {
}
async function eventId(accountId: string, event: BillingAuditEvent): Promise<string> {
const text = `${accountId}|${event.action}|${event.at}|${event.actorUserId ?? ''}|${JSON.stringify(event.detail ?? {})}`
const text = event.onceKey
? `${accountId}|${event.action}|once|${event.onceKey}`
: `${accountId}|${event.action}|${event.at}|${event.actorUserId ?? ''}|${JSON.stringify(event.detail ?? {})}`
const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))
return `billing_${Array.from(bytes.slice(0, 20), (byte) => byte.toString(16).padStart(2, '0')).join('')}`
}
@@ -95,17 +106,25 @@ const NOT_STARTED = new Set(['incomplete'])
/**
* What changed between the stored subscription and the one Stripe now reports, as audit events.
* A replay of the same Stripe state finds no difference, so it records nothing twice.
* A replay of the same Stripe state finds no difference, so it records nothing twice. With
* `subscription` (its id and current period start, ms), a plan starting or ending carries a once
* key, so concurrent events that each saw the change still record it once.
*/
export function subscriptionAuditEvents(before: SubscriptionTerms | null, after: SubscriptionTerms, at: number): BillingAuditEvent[] {
export function subscriptionAuditEvents(
before: SubscriptionTerms | null,
after: SubscriptionTerms,
at: number,
subscription?: { id: string; periodStart: number }
): BillingAuditEvent[] {
const terms = { plan: after.plan, interval: after.billing_interval, seats: after.seats }
const wasLive = before !== null && !ENDED.has(before.status) && !NOT_STARTED.has(before.status)
const isLive = !ENDED.has(after.status) && !NOT_STARTED.has(after.status)
const once = subscription ? { onceKey: `${subscription.id}|${subscription.periodStart}` } : {}
if (!wasLive) {
return isLive ? [{ action: 'billing.plan_started', at, detail: terms }] : []
return isLive ? [{ action: 'billing.plan_started', at, detail: terms, ...once }] : []
}
if (!isLive) {
return ENDED.has(after.status) ? [{ action: 'billing.plan_canceled', at, detail: { plan: before!.plan } }] : []
return ENDED.has(after.status) ? [{ action: 'billing.plan_canceled', at, detail: { plan: before!.plan }, ...once }] : []
}
const events: BillingAuditEvent[] = []
if (before!.plan !== after.plan || before!.billing_interval !== after.billing_interval) {
+3 -2
View File
@@ -180,7 +180,8 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript
subscriptionAuditEvents(
known,
{ status: subscription.status, plan: match.plan, billing_interval: match.interval, seats, cancel_at_period_end: cancelling, current_period_end: periodEnd * 1000 },
now
now,
{ id: subscription.id, periodStart: periodStart * 1000 }
)
)
if (overageItemId) {
@@ -313,7 +314,7 @@ export async function endCustomerSubscriptions(env: Env, customerId: string, now
async function markCanceled(env: Env, row: SubscriptionRow, now: number): Promise<void> {
await upsertSubscription(env.BILLING_DB, { ...row, status: 'canceled', past_due_since: null, member_count: null, updated_at: now })
await projectGrants(env, row.stripe_subscription_id, now)
await pushBillingAudit(env, row.account_id, subscriptionAuditEvents(row, { ...row, status: 'canceled' }, now))
await pushBillingAudit(env, row.account_id, subscriptionAuditEvents(row, { ...row, status: 'canceled' }, now, { id: row.stripe_subscription_id, periodStart: row.current_period_start }))
}
/**
@@ -84,6 +84,49 @@ describe('subscription changes', () => {
expect(control.events().map((event) => event.action)).toEqual(['billing.plan_started'])
})
it('records one plan start for a Checkout whose Stripe events arrive together', async () => {
const control = controlPlane()
const h = await createHarness({ SANDBOX_CONTROL_URL: CONTROL })
// SAFETY: the Worker only calls fetch on the binding.
h.env.SANDBOX_CONTROL = control.binding as unknown as Fetcher
const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' })
await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: { authorization: `Bearer ${token}` } })
const customer = [...h.stripe.customers.keys()][0]!
const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice: 'price_team_month', quantity: 2, periodStart: PERIOD_START, periodEnd: PERIOD_END })
// One Checkout: three events, delivered at once, each re-reading the same subscription.
await Promise.all([
h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })),
h.webhook(stripeEvent('customer.subscription.created', subscription)),
h.webhook(stripeEvent('invoice.paid', { id: 'in_1', customer, subscription: subscription.id }))
])
const started = control.events().filter((event) => event.action === 'billing.plan_started')
expect(started.length).toBeGreaterThanOrEqual(1)
// However many saw it, they name one event, which the control plane keeps once.
expect(new Set(started.map((event) => event.eventId)).size).toBe(1)
})
it('names a plan start or end by subscription and period, not by when it was seen', () => {
const live = { status: 'active', plan: 'team', billing_interval: 'month', seats: 2, cancel_at_period_end: 0 } as const
const sub = { id: 'sub_1', periodStart: 1_000 }
const first = subscriptionAuditEvents(null, live, 1, sub)[0]!
const second = subscriptionAuditEvents({ ...live, status: 'incomplete' }, live, 2, sub)[0]!
expect(first.onceKey).toBe(second.onceKey)
// A new period (a team coming back) is a new start.
expect(subscriptionAuditEvents({ ...live, status: 'canceled' }, live, 3, { ...sub, periodStart: 2_000 })[0]!.onceKey).not.toBe(first.onceKey)
// Other changes keep their per-moment ids.
expect(subscriptionAuditEvents(live, { ...live, seats: 3 }, 4, sub)[0]!.onceKey).toBeUndefined()
})
it('pushes the same event id for the same once key at different times', async () => {
const control = controlPlane()
const env = { CONTROL_PLANE_TOKEN: 'c'.repeat(40), SANDBOX_CONTROL_URL: CONTROL, SANDBOX_CONTROL: control.binding as unknown as Fetcher }
await pushBillingAudit(env, 'org:o1', [{ action: 'billing.plan_started', at: 1, onceKey: 'sub_1|1000' }])
await pushBillingAudit(env, 'org:o1', [{ action: 'billing.plan_started', at: 2, onceKey: 'sub_1|1000' }])
const [a, b] = control.events()
expect(a!.eventId).toBe(b!.eventId)
expect('onceKey' in a!).toBe(false)
})
it('works out what changed from the stored row alone', () => {
const live = { status: 'active', plan: 'team', billing_interval: 'month', seats: 2, cancel_at_period_end: 0 } as const
const actions = (before: Parameters<typeof subscriptionAuditEvents>[0], after: Parameters<typeof subscriptionAuditEvents>[1]) =>