diff --git a/cloud/apps/billing/src/audit-push.ts b/cloud/apps/billing/src/audit-push.ts index 7ef81401cad..1d61ef19e36 100644 --- a/cloud/apps/billing/src/audit-push.ts +++ b/cloud/apps/billing/src/audit-push.ts @@ -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 + /** + * 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 @@ -35,7 +44,9 @@ export function hasTeamAuditLog(accountId: string): boolean { } async function eventId(accountId: string, event: BillingAuditEvent): Promise { - 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) { diff --git a/cloud/apps/billing/src/webhook.ts b/cloud/apps/billing/src/webhook.ts index 7889dadb843..680587a971a 100644 --- a/cloud/apps/billing/src/webhook.ts +++ b/cloud/apps/billing/src/webhook.ts @@ -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 { 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 })) } /** diff --git a/cloud/apps/billing/test/audit-push.test.ts b/cloud/apps/billing/test/audit-push.test.ts index d5f7829407a..c077ee23588 100644 --- a/cloud/apps/billing/test/audit-push.test.ts +++ b/cloud/apps/billing/test/audit-push.test.ts @@ -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[0], after: Parameters[1]) =>