diff --git a/AGENTS.md b/AGENTS.md index 4c80587..65e761e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,11 +99,11 @@ protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by ## Where things stand -Phase 1: `@pegma/billing-core` (ledger collection, `(eventAt, eventId)` -watermark, effective-watermark guard, lifecycle-rank tie-break). Nothing is -published. Invariant combinators and reservation are Phase 2; snapshot -reconciliation is Phase 3; `@pegma/billing-stripe` is Phase 4 — do not -create those packages here yet. +Phase 2: `@pegma/billing-core` (ledger collection, `(eventAt, eventId)` +watermark, effective-watermark guard, lifecycle-rank tie-break, declared +`sticky` / `firstWins` combinators, checkout reservation). Nothing is +published. Snapshot reconciliation is Phase 3; `@pegma/billing-stripe` is +Phase 4 — do not create those packages here yet. Siblings: [spine](https://github.com/pegma-dev/spine), [storage-core](https://github.com/pegma-dev/storage-core), diff --git a/README.md b/README.md index 0a775e6..5e36569 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ hosts: the durable record of what a customer's subscription **is**, maintained correctly under out-of-order webhook delivery. > [!IMPORTANT] -> Pegma is in early `0.x` development. `@pegma/billing-core` Phase 1 is +> Pegma is in early `0.x` development. `@pegma/billing-core` Phase 2 is > in-tree and unpublished. No public API is stable. ## The part everyone gets wrong @@ -29,13 +29,13 @@ makes that impossible: - periodic **snapshot reconciliation** that repairs field drift without disturbing the dedup identity of the events themselves. -Phase 1 ships the watermark, the effective-watermark guard, and -lifecycle-rank arbitration. Snapshot reconciliation, declared ledger -invariants (`sticky`, `firstWins`), and the checkout reservation are later -phases. Ships later with a Stripe adapter; the core knows lifecycle -states, not Stripe's vocabulary. And the data boundary is absolute: the -ledger stores provider identifiers and derived state — never a card -number, a raw payload, or an amount. +Phase 2 ships the watermark, the effective-watermark guard, +lifecycle-rank arbitration, declared ledger invariants (`sticky`, +`firstWins`), and the checkout reservation. Snapshot reconciliation and +the Stripe adapter are later phases. The core knows lifecycle states, not +Stripe's vocabulary. And the data boundary is absolute: the ledger stores +provider identifiers and derived state — never a card number, a raw +payload, or an amount. Not here, on purpose: payment processing and checkout flows, entitlement resolution ([Authorization Core](https://github.com/pegma-dev/authorization-core)'s @@ -54,10 +54,10 @@ application. ## Packages -| Package | Role | Phase | -| ----------------------- | ---------------------------------------------- | ----- | -| `@pegma/billing-core` | Ledger collection, watermark, rank arbitration | 1 | -| `@pegma/billing-stripe` | Event and snapshot translation | later | +| Package | Role | Phase | +| ----------------------- | ------------------------------------------------ | ----- | +| `@pegma/billing-core` | Ledger, watermark, rank, invariants, reservation | 2 | +| `@pegma/billing-stripe` | Event and snapshot translation | later | The Stripe adapter package is not created until Phase 4. diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 3c2bd93..fca302a 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,8 +2,8 @@ ## Status -**Stage:** Phase 1 — arbitration core in-tree. Nothing is published. -(`0.1.0`, unpublished.) +**Stage:** Phase 2 — combinators and reservation in-tree. Nothing is +published. (`0.1.0`, unpublished.) **Extraction source:** the RetireGolden account API's subscription ledger — `api/src/lib/repo.js` (`shouldApplyEvent`, `applySubscriptionSnapshot`, @@ -160,13 +160,13 @@ posture. ## Delivery phases -### Phase 1 — the arbitration core (this tree) +### Phase 1 — the arbitration core Ledger collection, watermark, effective-watermark guard, lifecycle rank, equal-second tie-breaking. The reference implementation's race tests are the conformance bar; suite runs over memory and real Azurite. -### Phase 2 — invariant combinators and the reservation +### Phase 2 — invariant combinators and the reservation (this tree) `sticky` and `firstWins` as declared rules; the single-opportunity reservation with its read-winner-back semantics and TTL expiry. @@ -191,11 +191,11 @@ acceptance bar. ## Timing -Phase 1 is implemented in-tree. Later phases remain gated: combinators and -reservation (Phase 2), snapshot reconciliation (Phase 3), and the Stripe -adapter (Phase 4) wait until a named consumer needs them. Phase 5 (first -consumer cutover) stays gated on that application's operational calendar — -never swap code under a soak or mid-migration. +Phase 2 is implemented in-tree. Later phases remain gated: snapshot +reconciliation (Phase 3) and the Stripe adapter (Phase 4) wait until a +named consumer needs them. Phase 5 (first consumer cutover) stays gated +on that application's operational calendar — never swap code under a soak +or mid-migration. ## Open questions diff --git a/packages/billing-core/README.md b/packages/billing-core/README.md index 9a7ae82..a78314f 100644 --- a/packages/billing-core/README.md +++ b/packages/billing-core/README.md @@ -1,43 +1,67 @@ # `@pegma/billing-core` Provider-agnostic subscription ledger for Pegma hosts: a per-account -watermark, an effective-watermark guard, and lifecycle-rank tie-breaking -at the equal second. +watermark, an effective-watermark guard, lifecycle-rank tie-breaking at +the equal second, declared write-path invariants, and a single-opportunity +checkout reservation. > [!IMPORTANT] > Pegma is in early `0.x` development. This package's public API is unstable. ```ts -import { createBillingLedger } from "@pegma/billing-core"; +import { createBillingLedger, firstWins, sticky } from "@pegma/billing-core"; import { createMemoryStore } from "@pegma/storage-core"; +import { fixedClock } from "@pegma/spine"; const ledger = createBillingLedger({ store: createMemoryStore(), + clock: fixedClock("2026-08-15T16:00:00.000Z"), + fields: { + foundingMember: sticky(), + consentAt: firstWins("consent"), + consentVersion: firstWins("consent"), + }, }); -const result = await ledger.apply("acct_123", { - eventId: "evt_canceled", +await ledger.apply("acct_123", { + eventId: "evt_founding", eventAt: "2026-08-15T16:00:00.000Z", - status: "canceled", + status: "active", providerCustomerId: "cus_123", providerSubscriptionId: "sub_123", - providerPriceId: "price_pro", - plan: "pro", + providerPriceId: "price_founding", + plan: "founding", periodStartAt: "2026-08-01T00:00:00.000Z", periodEndAt: "2026-09-01T00:00:00.000Z", trialStartAt: null, trialEndAt: null, cancelAtPeriodEnd: false, + fields: { + foundingMember: true, + consentAt: "2026-08-15T16:00:00.000Z", + consentVersion: "v1", + }, }); + +const reserved = await ledger.reserve("acct_456"); +if (reserved.reserved) { + await ledger.release("acct_456", reserved.reservationId); +} ``` Hosts inject a `@pegma/storage-core` `Store` and, optionally, a Spine -`Clock` and `Logger`. This package never creates a network client and never -stores card data, raw payloads, line items, or amounts. +`Clock` and `Logger`. Reservation TTL is taken from the injected clock — +never from `Date.now()`. This package never creates a network client and +never stores card data, raw payloads, line items, or amounts. Arrival order proves nothing. Every apply goes through the effective-watermark guard and lifecycle rank. Exact redelivery is an idempotent no-op. -Phase 1 is the arbitration core. Invariant combinators, checkout reservation, -snapshot reconciliation, and the Stripe adapter are later phases — do not -import them from this package. +`sticky` and `firstWins` are declared on the host's ledger definition and +enforced inside the update decider, so they re-evaluate against fresh state +on every conflict. A reservation id is minted inside the decider and read +back from storage; the caller's id is whatever the stored record says. + +Phase 2 is the arbitration core plus combinators and reservation. Snapshot +reconciliation and the Stripe adapter are later phases — do not import them +from this package. diff --git a/packages/billing-core/package.json b/packages/billing-core/package.json index 297307c..0b364c7 100644 --- a/packages/billing-core/package.json +++ b/packages/billing-core/package.json @@ -1,7 +1,7 @@ { "name": "@pegma/billing-core", "version": "0.1.0", - "description": "Provider-agnostic subscription ledger: event watermark, effective-watermark guard, and lifecycle-rank arbitration.", + "description": "Provider-agnostic subscription ledger: event watermark, lifecycle-rank arbitration, declared invariants, and checkout reservation.", "license": "MIT", "type": "module", "sideEffects": false, diff --git a/packages/billing-core/src/index.test.ts b/packages/billing-core/src/index.test.ts index 15ff505..c9b187a 100644 --- a/packages/billing-core/src/index.test.ts +++ b/packages/billing-core/src/index.test.ts @@ -18,13 +18,23 @@ import { waitForStartup, } from "../../../test/azurite.js"; import { + applyLedgerInvariants, billingLedgerCollection, billingLedgerKey, createBillingLedger, decideLedgerApplication, + decideReservation, + DEFAULT_RESERVATION_TTL_MS, effectiveWatermarkSecond, + firstWins, + hasReservationProvenance, + type HostFromInvariants, + isEventlessLedgerRow, + isGrantingStatus, LIFECYCLE_RANK, lifecycleRank, + reservationIsLive, + sticky, type LedgerEvent, type LedgerRecord, } from "./index.js"; @@ -62,10 +72,10 @@ function freshAzureStore(): Store { return createAzureTablesStore({ client }); } -function event( +function event( eventId: string, - overrides: Partial = {}, -): LedgerEvent { + overrides: Partial> = {}, +): LedgerEvent { return { eventId, eventAt: SECOND, @@ -102,6 +112,10 @@ function record( eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + reservationId: null, + reservationExpiresAt: null, + reservationSeeded: false, + offerRedeemed: false, ...overrides, }; } @@ -172,7 +186,7 @@ function ledgerConformance(name: string, freshStore: () => Store): void { const result = await ledger.apply("acct_create", first); expect(result.applied).toBe(true); expect(result.record).toEqual( - record("acct_create", { eventId: "evt_first" }), + record("acct_create", { eventId: "evt_first", offerRedeemed: true }), ); expect(await ledger.get("acct_create")).toEqual(result.record); }); @@ -759,9 +773,37 @@ describe("billing ledger codec", () => { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + reservationId: null, + reservationExpiresAt: null, + reservationSeeded: false, + offerRedeemed: false, }); }); + it("does not treat a blank unknown-status decode as reservation provenance", () => { + const decoded = codec.decode({ + accountId: "acct_unknown_blank", + status: "unknown", + }); + expect(decoded).toMatchObject({ + status: "incomplete", + reservationSeeded: false, + reservationId: null, + reservationExpiresAt: null, + eventAt: null, + eventId: null, + }); + expect(hasReservationProvenance(decoded)).toBe(false); + expect(isEventlessLedgerRow(decoded)).toBe(false); + expect( + decideLedgerApplication( + decoded, + "acct_unknown_blank", + event("evt_granting_arrival", { status: "active" }), + ), + ).toEqual({ action: "keep", reason: "stale" }); + }); + it("decodes unknown status to incomplete so a corrupt row cannot grant", () => { expect( codec.decode({ @@ -788,3 +830,782 @@ describe("production clock discipline", () => { expect(source).not.toMatch(/Date\.now\s*\(/u); }); }); + +function controllableClock(start: IsoTimestamp) { + let current = start; + return { + now: () => current, + set(at: IsoTimestamp) { + current = at; + }, + advance(ms: number) { + current = new Date( + Date.parse(current) + ms, + ).toISOString() as IsoTimestamp; + }, + }; +} + +const HOST_FIELDS = { + foundingMember: sticky(), + consentAt: firstWins("consent"), + consentVersion: firstWins("consent"), +}; +type Host = HostFromInvariants; + +function conflictFirstWrite(store: Store): Store { + let attempts = 0; + return { + collection(definition: CollectionDefinition): CollectionStore { + const delegate = store.collection(definition); + if (definition.name !== "billingLedger") { + return delegate; + } + return { + ...delegate, + update: (key, decide, options) => + delegate.update( + key, + async (current) => { + const decision = await decide(current); + attempts += 1; + if (attempts === 1 && decision.action === "write") { + await delegate.put( + current === null + ? (record("acct_conflict_seed", { + accountId: String(key.partition), + status: "incomplete", + providerCustomerId: null, + providerSubscriptionId: null, + providerPriceId: null, + plan: null, + periodStartAt: null, + periodEndAt: null, + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + eventAt: null, + eventId: null, + snapshotAt: null, + offerRedeemed: false, + }) as T) + : current, + ); + } + return decision; + }, + options, + ), + }; + }, + }; +} + +function invariantsAndReservation(name: string, freshStore: () => Store): void { + describe(name, () => { + it("sticky one-way flip survives a later price reversion", async () => { + const store = freshStore(); + const ledger = createBillingLedger({ + store, + fields: HOST_FIELDS, + }); + await ledger.apply( + "acct_sticky", + event("evt_founding", { + fields: { foundingMember: true, consentAt: SECOND }, + }), + ); + const reverted = await ledger.apply( + "acct_sticky", + event("evt_reversion", { + eventAt: LATER, + status: "active", + plan: "starter", + providerPriceId: "price_starter", + fields: { foundingMember: false, consentAt: LATER }, + }), + ); + expect(reverted.applied).toBe(true); + expect(reverted.record).toMatchObject({ + plan: "starter", + foundingMember: true, + consentAt: SECOND, + offerRedeemed: true, + }); + }); + + it("sticky stays true under concurrent deliveries that try to clear it", async () => { + const base = freshStore(); + const rows = base.collection(billingLedgerCollection(HOST_FIELDS)); + await rows.put({ + ...record("acct_sticky_race", { + eventAt: EARLIER, + eventId: "evt_seed", + }), + foundingMember: true, + consentAt: EARLIER, + consentVersion: "v1", + }); + const ledger = createBillingLedger({ + store: synchronizeFirstTwoUpdates(base), + fields: HOST_FIELDS, + }); + await Promise.all([ + ledger.apply( + "acct_sticky_race", + event("evt_clear_a", { + eventAt: LATER, + status: "active", + fields: { foundingMember: false }, + }), + ), + ledger.apply( + "acct_sticky_race", + event("evt_clear_b", { + eventAt: "2026-08-15T16:00:02.000Z", + status: "canceled", + fields: { foundingMember: false }, + }), + ), + ]); + expect(await ledger.get("acct_sticky_race")).toMatchObject({ + foundingMember: true, + consentAt: EARLIER, + consentVersion: "v1", + }); + }); + + it("firstWins keeps the first consent group under concurrent deliveries", async () => { + const base = freshStore(); + const rows = base.collection(billingLedgerCollection(HOST_FIELDS)); + await rows.put({ + ...record("acct_first_wins", { + eventAt: EARLIER, + eventId: "evt_seed", + status: "incomplete", + offerRedeemed: false, + }), + foundingMember: false, + consentAt: null, + consentVersion: null, + }); + const ledger = createBillingLedger({ + store: synchronizeFirstTwoUpdates(base), + fields: HOST_FIELDS, + }); + await Promise.all([ + ledger.apply( + "acct_first_wins", + event("evt_consent_a", { + eventAt: LATER, + status: "active", + fields: { consentAt: LATER, consentVersion: "a" }, + }), + ), + ledger.apply( + "acct_first_wins", + event("evt_consent_b", { + eventAt: "2026-08-15T16:00:02.000Z", + status: "active", + fields: { + consentAt: "2026-08-15T16:00:02.000Z", + consentVersion: "b", + }, + }), + ), + ]); + const stored = await ledger.get("acct_first_wins"); + expect(["a", "b"]).toContain(stored?.consentVersion); + expect(stored?.consentAt).toBe( + stored?.consentVersion === "a" ? LATER : "2026-08-15T16:00:02.000Z", + ); + const later = await ledger.apply( + "acct_first_wins", + event("evt_consent_c", { + eventAt: "2026-08-15T16:00:03.000Z", + status: "canceled", + fields: { + consentAt: "2026-08-15T16:00:03.000Z", + consentVersion: "c", + }, + }), + ); + expect(later.applied).toBe(true); + expect(later.record.consentVersion).toBe(stored?.consentVersion); + expect(later.record.consentAt).toBe(stored?.consentAt); + }); + + it("mints one reservation and reads the winning id back from storage", async () => { + const clock = controllableClock(SECOND); + const minted: string[] = []; + const base = freshStore(); + const ledger = createBillingLedger({ + store: conflictFirstWrite(base), + clock, + newId: () => { + const id = `rsv_mint_${minted.length}`; + minted.push(id); + return id; + }, + }); + const result = await ledger.reserve("acct_read_back"); + expect(result).toEqual({ + reserved: true, + reservationId: minted[minted.length - 1], + expiresAt: "2026-08-15T16:30:00.000Z", + }); + expect(minted.length).toBeGreaterThanOrEqual(2); + expect(result.reserved).toBe(true); + if (result.reserved) { + expect(result.reservationId).not.toBe(minted[0]); + expect( + await base + .collection(billingLedgerCollection()) + .get(billingLedgerKey("acct_read_back")), + ).toMatchObject({ + reservationId: result.reservationId, + reservationExpiresAt: result.expiresAt, + }); + } + }); + + it("concurrent reservation admits exactly one winner", async () => { + const clock = controllableClock(SECOND); + let next = 0; + const ledger = createBillingLedger({ + store: synchronizeFirstTwoUpdates(freshStore()), + clock, + newId: () => `rsv_race_${(next += 1)}`, + }); + const [left, right] = await Promise.all([ + ledger.reserve("acct_rsv_race"), + ledger.reserve("acct_rsv_race"), + ]); + const outcomes = [left, right]; + const winners = outcomes.filter((outcome) => outcome.reserved); + const losers = outcomes.filter((outcome) => !outcome.reserved); + expect(winners).toHaveLength(1); + expect(losers).toHaveLength(1); + expect(losers[0]).toEqual({ reserved: false, reason: "reserved" }); + const stored = await ledger.get("acct_rsv_race"); + expect(winners[0]?.reserved).toBe(true); + if (winners[0]?.reserved) { + expect(stored?.reservationId).toBe(winners[0].reservationId); + expect(stored?.reservationExpiresAt).toBe(winners[0].expiresAt); + } + }); + + it("refuses when redeemed, live-subscribed, or already reserved", async () => { + const clock = controllableClock(SECOND); + const ledger = createBillingLedger({ store: freshStore(), clock }); + + expect(await ledger.reserve("acct_live")).toMatchObject({ + reserved: true, + }); + expect(await ledger.reserve("acct_live")).toEqual({ + reserved: false, + reason: "reserved", + }); + + const subscribedStore = freshStore(); + await subscribedStore + .collection(billingLedgerCollection()) + .put(record("acct_sub", { status: "active", offerRedeemed: false })); + expect( + await createBillingLedger({ store: subscribedStore, clock }).reserve( + "acct_sub", + ), + ).toEqual({ + reserved: false, + reason: "subscribed", + }); + + await ledger.apply("acct_redeemed", event("evt_active")); + await ledger.apply( + "acct_redeemed", + event("evt_canceled", { eventAt: LATER, status: "canceled" }), + ); + expect(await ledger.get("acct_redeemed")).toMatchObject({ + status: "canceled", + offerRedeemed: true, + reservationId: null, + }); + expect(await ledger.reserve("acct_redeemed")).toEqual({ + reserved: false, + reason: "redeemed", + }); + }); + + it("expires an abandoned reservation by TTL from the injected clock", async () => { + const clock = controllableClock(SECOND); + const ledger = createBillingLedger({ + store: freshStore(), + clock, + reservationTtlMs: 60_000, + }); + const first = await ledger.reserve("acct_ttl"); + expect(first).toMatchObject({ + reserved: true, + expiresAt: "2026-08-15T16:01:00.000Z", + }); + clock.advance(59_999); + expect(await ledger.reserve("acct_ttl")).toEqual({ + reserved: false, + reason: "reserved", + }); + clock.advance(1); + const again = await ledger.reserve("acct_ttl"); + expect(again.reserved).toBe(true); + if (first.reserved && again.reserved) { + expect(again.reservationId).not.toBe(first.reservationId); + expect(again.expiresAt).toBe("2026-08-15T16:02:00.000Z"); + } + }); + + it("releases a reservation best-effort and lets the account reserve again", async () => { + const clock = controllableClock(SECOND); + const ledger = createBillingLedger({ store: freshStore(), clock }); + const minted = await ledger.reserve("acct_release"); + expect(minted.reserved).toBe(true); + if (!minted.reserved) { + throw new Error("expected a reservation"); + } + expect( + await ledger.release("acct_release", minted.reservationId), + ).toEqual({ released: true }); + expect( + await ledger.release("acct_release", minted.reservationId), + ).toEqual({ released: false }); + expect(await ledger.release("acct_release", "rsv_other")).toEqual({ + released: false, + }); + const again = await ledger.reserve("acct_release"); + expect(again.reserved).toBe(true); + if (!again.reserved) { + throw new Error("expected a second reservation"); + } + expect(again.reservationId).not.toBe(minted.reservationId); + expect(await ledger.release("acct_release", again.reservationId)).toEqual( + { + released: true, + }, + ); + const firstEvent = await ledger.apply( + "acct_release", + event("evt_after_release", { status: "incomplete" }), + ); + expect(firstEvent.applied).toBe(true); + expect(firstEvent.record.reservationSeeded).toBe(true); + }); + + it("applies the first event onto a reservation-only row and keeps the reservation until granting", async () => { + const clock = controllableClock(SECOND); + const ledger = createBillingLedger({ store: freshStore(), clock }); + const minted = await ledger.reserve("acct_after_rsv"); + expect(minted.reserved).toBe(true); + const incomplete = await ledger.apply( + "acct_after_rsv", + event("evt_incomplete", { status: "incomplete", plan: "pro" }), + ); + expect(incomplete.applied).toBe(true); + expect(incomplete.record).toMatchObject({ + status: "incomplete", + plan: "pro", + offerRedeemed: false, + reservationId: minted.reserved ? minted.reservationId : null, + }); + const active = await ledger.apply( + "acct_after_rsv", + event("evt_active", { eventAt: LATER, status: "active" }), + ); + expect(active.applied).toBe(true); + expect(active.record).toMatchObject({ + status: "active", + offerRedeemed: true, + reservationId: null, + reservationExpiresAt: null, + }); + }); + + it("does not treat a blank decoded corrupt row as reservation-only", async () => { + const store = freshStore(); + const rows = store.collection(billingLedgerCollection()); + const decoded = billingLedgerCollection().codec.decode({ + accountId: "acct_unknown_blank", + status: "unknown", + }); + expect(hasReservationProvenance(decoded)).toBe(false); + expect(isEventlessLedgerRow(decoded)).toBe(false); + await rows.put(decoded); + const ledger = createBillingLedger({ + store, + clock: controllableClock(SECOND), + }); + const result = await ledger.apply( + "acct_unknown_blank", + event("evt_granting_arrival", { status: "active", plan: "resurrect" }), + ); + expect(result.applied).toBe(false); + expect(result.record).toMatchObject({ + status: "incomplete", + eventAt: null, + eventId: null, + plan: null, + }); + }); + + it("firstWins keeps an empty-string first write under a later event", async () => { + const store = freshStore(); + const rows = store.collection(billingLedgerCollection(HOST_FIELDS)); + await rows.put({ + ...record("acct_empty_first", { + eventAt: EARLIER, + eventId: "evt_seed", + status: "incomplete", + offerRedeemed: false, + }), + foundingMember: false, + consentAt: "", + consentVersion: "", + }); + const ledger = createBillingLedger({ + store, + fields: HOST_FIELDS, + }); + const later = await ledger.apply( + "acct_empty_first", + event("evt_consent_later", { + eventAt: LATER, + status: "active", + fields: { consentAt: LATER, consentVersion: "later" }, + }), + ); + expect(later.applied).toBe(true); + expect(later.record).toMatchObject({ + consentAt: "", + consentVersion: "", + }); + }); + + it("allows reserve after a terminal event that never granted", async () => { + const clock = controllableClock(SECOND); + const ledger = createBillingLedger({ store: freshStore(), clock }); + const canceled = await ledger.apply( + "acct_never_granted", + event("evt_canceled", { status: "canceled" }), + ); + expect(canceled.applied).toBe(true); + expect(canceled.record.offerRedeemed).toBe(false); + expect(await ledger.reserve("acct_never_granted")).toMatchObject({ + reserved: true, + }); + + const reserved = await ledger.reserve("acct_abandoned_cancel"); + expect(reserved.reserved).toBe(true); + if (!reserved.reserved) { + throw new Error("expected a reservation"); + } + const terminal = await ledger.apply( + "acct_abandoned_cancel", + event("evt_unpaid", { status: "unpaid" }), + ); + expect(terminal.applied).toBe(true); + expect(terminal.record.offerRedeemed).toBe(false); + expect(terminal.record.reservationId).toBe(reserved.reservationId); + expect( + await ledger.release("acct_abandoned_cancel", reserved.reservationId), + ).toEqual({ released: true }); + expect(await ledger.reserve("acct_abandoned_cancel")).toMatchObject({ + reserved: true, + }); + }); + + it("redeems a Phase 1 live row when a later non-granting event applies", async () => { + const store = freshStore(); + await store.collection(billingLedgerCollection()).put( + record("acct_phase1", { + status: "active", + offerRedeemed: false, + reservationSeeded: false, + }), + ); + const ledger = createBillingLedger({ + store, + clock: controllableClock(SECOND), + }); + const canceled = await ledger.apply( + "acct_phase1", + event("evt_canceled", { eventAt: LATER, status: "canceled" }), + ); + expect(canceled.applied).toBe(true); + expect(canceled.record.offerRedeemed).toBe(true); + expect(await ledger.reserve("acct_phase1")).toEqual({ + reserved: false, + reason: "redeemed", + }); + }); + + it("does not apply onto a corrupt canceled row that lacks a watermark", async () => { + const store = freshStore(); + const rows = store.collection(billingLedgerCollection()); + await rows.put( + record("acct_corrupt_reserved", { + status: "canceled", + eventAt: null, + eventId: null, + snapshotAt: null, + plan: "kept", + reservationId: "rsv_stale", + reservationExpiresAt: LATER, + }), + ); + const ledger = createBillingLedger({ + store, + clock: controllableClock(SECOND), + }); + const result = await ledger.apply( + "acct_corrupt_reserved", + event("evt_granting_arrival", { status: "active", plan: "resurrect" }), + ); + expect(result.applied).toBe(false); + expect(result.record).toMatchObject({ + status: "canceled", + plan: "kept", + reservationId: "rsv_stale", + }); + }); + }); +} + +invariantsAndReservation( + "invariants and reservation / memory", + createMemoryStore, +); +invariantsAndReservation( + "invariants and reservation / Azure Tables", + freshAzureStore, +); + +describe("declared invariants", () => { + it("rejects host field names that collide with core ledger fields", () => { + expect(() => + billingLedgerCollection({ status: sticky() } as never), + ).toThrow(/host ledger field/); + expect(() => + createBillingLedger({ + store: createMemoryStore(), + fields: { "bad-name": sticky() } as never, + }), + ).toThrow(/host ledger field/); + }); + + it("encodes declared host fields and still drops cast-in payload data", () => { + const codec = billingLedgerCollection(HOST_FIELDS).codec; + const value = { + ...record("acct_host"), + foundingMember: true, + consentAt: SECOND, + consentVersion: "v1", + payload: { customer: "secret" }, + amount: 1999, + }; + expect(codec.encode(value)).toEqual({ + accountId: "acct_host", + providerCustomerId: "cus_123", + providerSubscriptionId: "sub_123", + providerPriceId: "price_pro", + status: "active", + plan: "pro", + periodStartAt: "2026-08-01T00:00:00.000Z", + periodEndAt: "2026-09-01T00:00:00.000Z", + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + reservationId: null, + reservationExpiresAt: null, + reservationSeeded: false, + offerRedeemed: false, + foundingMember: true, + consentAt: SECOND, + consentVersion: "v1", + }); + }); + + it("rejects declared host fields that would persist forbidden data", () => { + for (const name of ["amount", "cardData", "rawPayload", "lineItems"]) { + expect(() => billingLedgerCollection({ [name]: firstWins() })).toThrow( + /card data, raw payloads, line items, or amounts/, + ); + } + expect(() => + createBillingLedger({ + store: createMemoryStore(), + fields: { amount: sticky() }, + }), + ).toThrow(/card data, raw payloads, line items, or amounts/); + }); + + it("re-evaluates sticky and firstWins against fresh current state", () => { + const current = { + ...record("acct"), + foundingMember: true, + consentAt: EARLIER, + consentVersion: "first", + }; + expect( + applyLedgerInvariants( + current, + { foundingMember: false, consentAt: LATER, consentVersion: "second" }, + HOST_FIELDS, + ), + ).toEqual({ + foundingMember: true, + consentAt: EARLIER, + consentVersion: "first", + }); + expect( + applyLedgerInvariants( + { + ...record("acct"), + foundingMember: false, + consentAt: null, + consentVersion: null, + }, + { foundingMember: true, consentAt: SECOND, consentVersion: "v1" }, + HOST_FIELDS, + ), + ).toEqual({ + foundingMember: true, + consentAt: SECOND, + consentVersion: "v1", + }); + }); + + it("firstWins freezes an empty-string first write", () => { + expect( + applyLedgerInvariants( + { + ...record("acct"), + foundingMember: false, + consentAt: "", + consentVersion: "", + }, + { consentAt: LATER, consentVersion: "later" }, + HOST_FIELDS, + ), + ).toEqual({ + foundingMember: false, + consentAt: "", + consentVersion: "", + }); + }); +}); + +describe("checkout reservation decider", () => { + it("refuses redeemed, subscribed, and live reservations without writing", () => { + expect( + decideReservation( + record("acct", { offerRedeemed: true }), + "acct", + SECOND, + "rsv_new", + LATER, + ), + ).toEqual({ action: "keep", reason: "redeemed" }); + expect( + decideReservation( + record("acct", { status: "canceled", offerRedeemed: false }), + "acct", + SECOND, + "rsv_new", + LATER, + ), + ).toMatchObject({ + action: "write", + value: { reservationId: "rsv_new", offerRedeemed: false }, + }); + expect( + decideReservation( + record("acct", { status: "trialing" }), + "acct", + SECOND, + "rsv_new", + LATER, + ), + ).toEqual({ action: "keep", reason: "subscribed" }); + expect( + decideReservation( + record("acct", { + status: "incomplete", + reservationId: "rsv_live", + reservationExpiresAt: LATER, + }), + "acct", + SECOND, + "rsv_new", + SNAPSHOT_BOUND, + ), + ).toEqual({ action: "keep", reason: "reserved" }); + }); + + it("treats an expired or unparseable reservation as free", () => { + const expired = decideReservation( + record("acct", { + status: "incomplete", + reservationId: "rsv_old", + reservationExpiresAt: SECOND, + }), + "acct", + SECOND, + "rsv_new", + LATER, + ); + expect(expired).toMatchObject({ + action: "write", + value: { reservationId: "rsv_new", reservationExpiresAt: LATER }, + }); + expect( + reservationIsLive( + { reservationId: "rsv_old", reservationExpiresAt: "not-a-time" }, + SECOND, + ), + ).toBe(false); + }); + + it("creates a reservation-only row that the first event can still apply onto", () => { + const reserved = decideReservation( + null, + "acct_blank", + SECOND, + "rsv_1", + LATER, + ); + expect(reserved.action).toBe("write"); + if (reserved.action !== "write") { + return; + } + expect(hasReservationProvenance(reserved.value)).toBe(true); + expect(isEventlessLedgerRow(reserved.value)).toBe(true); + expect( + decideLedgerApplication( + reserved.value, + "acct_blank", + event("evt_first", { status: "incomplete" }), + ), + ).toMatchObject({ + action: "write", + value: { eventId: "evt_first", reservationId: "rsv_1" }, + }); + }); + + it("requires an injected clock and never uses Date.now for TTL", async () => { + const ledger = createBillingLedger({ store: createMemoryStore() }); + await expect(ledger.reserve("acct_no_clock")).rejects.toThrow(/Clock/); + expect(DEFAULT_RESERVATION_TTL_MS).toBe(30 * 60 * 1000); + expect(isGrantingStatus("active")).toBe(true); + expect(isGrantingStatus("canceled")).toBe(false); + }); +}); diff --git a/packages/billing-core/src/index.ts b/packages/billing-core/src/index.ts index 4cfb95e..7230684 100644 --- a/packages/billing-core/src/index.ts +++ b/packages/billing-core/src/index.ts @@ -14,10 +14,15 @@ import { } from "@pegma/storage-core"; const SAFE_KEY_PART = /^[A-Za-z0-9|_.:@-]{1,256}$/; +const HOST_FIELD_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/; const CANONICAL_ISO_TIMESTAMP = /^(?:\d{4}|[+-]\d{6})-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; const LEDGER_ROW_ID = "subscription"; +/** Default checkout-reservation lifetime. Abandoned checkouts expire. */ +export const DEFAULT_RESERVATION_TTL_MS = 30 * 60 * 1000; +const MAX_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000; + /** * Provider-agnostic subscription lifecycle. * @@ -41,6 +46,72 @@ export function lifecycleRank(status: LifecycleStatus): number { return LIFECYCLE_RANK[status]; } +/** Granting statuses are a live subscription for the reservation gate. */ +export function isGrantingStatus(status: LifecycleStatus): boolean { + return lifecycleRank(status) === LIFECYCLE_RANK.active; +} + +function offerIsRedeemed( + current: Pick | null, + event: Pick, +): boolean { + if (current?.offerRedeemed === true || event.offerRedeemed === true) { + return true; + } + return ( + (current !== null && isGrantingStatus(current.status)) || + isGrantingStatus(event.status) + ); +} + +/** Values a host-declared ledger field may persist. */ +export type HostFieldValue = string | number | boolean | null; + +/** Host-declared fields governed by {@link sticky} / {@link firstWins}. */ +export type HostFields = object; + +/** A boolean that only ever flips false → true. */ +export interface StickyInvariant { + readonly kind: "sticky"; +} + +/** + * A field or named group whose first write is permanent. + * + * Fields that share a `group` freeze together: once any member is written, + * later events cannot change any member of the group. + */ +export interface FirstWinsInvariant { + readonly kind: "firstWins"; + readonly group?: string; +} + +export type FieldInvariant = StickyInvariant | FirstWinsInvariant; + +export type LedgerFieldMap = Record; + +export type HostFromInvariants = { + [K in keyof TFields]: TFields[K] extends StickyInvariant + ? boolean + : HostFieldValue; +}; + +export type LedgerInvariants = { + readonly [K in keyof THost]: FieldInvariant; +}; + +/** Declares a one-way boolean flag. */ +export function sticky(): StickyInvariant { + return { kind: "sticky" }; +} + +/** Declares a first-write-wins field, optionally as part of a named group. */ +export function firstWins(group?: string): FirstWinsInvariant { + return group === undefined + ? { kind: "firstWins" } + : { kind: "firstWins", group }; +} + /** * One subscription ledger row per billing account. * @@ -48,7 +119,7 @@ export function lifecycleRank(status: LifecycleStatus): number { * boundary: it will not persist card data, raw payloads, line items, or * amounts even if a caller casts them onto the value. */ -export interface LedgerRecord { +export interface LedgerFields { readonly accountId: string; readonly providerCustomerId: string | null; readonly providerSubscriptionId: string | null; @@ -63,10 +134,16 @@ export interface LedgerRecord { readonly eventAt: IsoTimestamp | null; readonly eventId: string | null; readonly snapshotAt: IsoTimestamp | null; + readonly reservationId: string | null; + readonly reservationExpiresAt: IsoTimestamp | null; + readonly reservationSeeded: boolean; + readonly offerRedeemed: boolean; } +export type LedgerRecord = LedgerFields & THost; + /** Provider event to apply through the watermark guard and lifecycle rank. */ -export interface LedgerEvent { +export type LedgerEvent = { readonly eventId: string; readonly eventAt: IsoTimestamp; readonly status: LifecycleStatus; @@ -79,32 +156,108 @@ export interface LedgerEvent { readonly trialStartAt: IsoTimestamp | null; readonly trialEndAt: IsoTimestamp | null; readonly cancelAtPeriodEnd: boolean; -} + readonly offerRedeemed?: boolean; + readonly fields?: Partial; +}; export type IgnoreReason = "redelivery" | "stale" | "equal-rank"; -export type ApplicationDecision = - | { readonly action: "write"; readonly value: LedgerRecord } +export type ApplicationDecision = + | { readonly action: "write"; readonly value: LedgerRecord } | { readonly action: "keep"; readonly reason: IgnoreReason }; -export interface ApplyResult { +export interface ApplyResult { readonly applied: boolean; - readonly record: LedgerRecord; + readonly record: LedgerRecord; +} + +export type ReserveRefusal = "redeemed" | "subscribed" | "reserved"; + +export type ReserveDecision = + | { readonly action: "write"; readonly value: LedgerRecord } + | { readonly action: "keep"; readonly reason: ReserveRefusal }; + +export type ReserveResult = + | { + readonly reserved: true; + readonly reservationId: string; + readonly expiresAt: IsoTimestamp; + } + | { readonly reserved: false; readonly reason: ReserveRefusal }; + +export interface ReserveOptions { + readonly ttlMs?: number; +} + +export interface ReleaseResult { + readonly released: boolean; } -export interface BillingLedger { - get(accountId: string): Promise; - apply(accountId: string, event: LedgerEvent): Promise; +export interface BillingLedger { + get(accountId: string): Promise | null>; + apply( + accountId: string, + event: LedgerEvent, + ): Promise>; + reserve(accountId: string, options?: ReserveOptions): Promise; + release(accountId: string, reservationId: string): Promise; } -export interface BillingLedgerOptions { +export interface BillingLedgerOptions { readonly store: Store; readonly clock?: Clock; readonly logger?: Logger; + readonly newId?: () => string; + readonly fields?: TFields; + readonly reservationTtlMs?: number; } const LIFECYCLE_STATUSES = new Set(Object.keys(LIFECYCLE_RANK)); +const CORE_FIELD_NAMES = new Set([ + "accountId", + "providerCustomerId", + "providerSubscriptionId", + "providerPriceId", + "status", + "plan", + "periodStartAt", + "periodEndAt", + "trialStartAt", + "trialEndAt", + "cancelAtPeriodEnd", + "eventAt", + "eventId", + "snapshotAt", + "reservationId", + "reservationExpiresAt", + "reservationSeeded", + "offerRedeemed", +]); + +const FORBIDDEN_HOST_FIELD_NAMES = new Set([ + "amount", + "amounts", + "card", + "cards", + "carddata", + "cardnumber", + "card_data", + "card_number", + "payload", + "payloads", + "rawpayload", + "raw_payload", + "lineitem", + "lineitems", + "line_item", + "line_items", +]); + +function isForbiddenHostFieldName(name: string): boolean { + return FORBIDDEN_HOST_FIELD_NAMES.has(name.toLowerCase()); +} + function assertSafeAccountId(accountId: string): string { if (typeof accountId !== "string" || !SAFE_KEY_PART.test(accountId)) { throw new TypeError( @@ -123,6 +276,41 @@ function assertSafeEventId(eventId: string): string { return eventId; } +function assertSafeReservationId(reservationId: string): string { + if (typeof reservationId !== "string" || !SAFE_KEY_PART.test(reservationId)) { + throw new TypeError( + "Unsupported billing reservation id: expected 1-256 safe key characters.", + ); + } + return reservationId; +} + +function assertHostFieldNames(fields: LedgerFieldMap | undefined): void { + if (fields === undefined) { + return; + } + for (const name of Object.keys(fields)) { + if (isForbiddenHostFieldName(name)) { + throw new TypeError( + `Unsupported host ledger field ${JSON.stringify(name)}: the ledger does not persist card data, raw payloads, line items, or amounts.`, + ); + } + if (CORE_FIELD_NAMES.has(name) || !HOST_FIELD_NAME.test(name)) { + throw new TypeError( + `Unsupported host ledger field ${JSON.stringify(name)}: expected a non-core name matching [A-Za-z][A-Za-z0-9_]{0,63}.`, + ); + } + } +} + +function hostFieldKeys( + fields: TFields | undefined, +): readonly (keyof TFields & string)[] { + return fields === undefined + ? [] + : (Object.keys(fields) as (keyof TFields & string)[]); +} + function canonicalTimestampMilliseconds(timestamp: unknown): number | null { if ( typeof timestamp !== "string" || @@ -195,7 +383,7 @@ function maxSecond( * Arrival time is not an input. Unparseable fields do not contribute. */ export function effectiveWatermarkSecond( - record: Pick, + record: Pick, ): number | null { return maxSecond(record.eventAt, record.snapshotAt); } @@ -229,9 +417,76 @@ function assertNullableString(value: unknown, label: string): string | null { return value; } -function assertEvent(event: LedgerEvent): LedgerEvent { +function storedHostValue(value: unknown): StoredValue { + if (value === null) { + return null; + } + if (typeof value === "boolean" || typeof value === "string") { + return value; + } + if (typeof value === "number" && Number.isFinite(value)) { + return value; + } + return null; +} + +function isWrittenHostValue(value: HostFieldValue | undefined): boolean { + return value !== undefined && value !== null; +} + +function assertTtlMs(ttlMs: number): number { + if ( + typeof ttlMs !== "number" || + !Number.isFinite(ttlMs) || + ttlMs <= 0 || + ttlMs > MAX_RESERVATION_TTL_MS + ) { + throw new TypeError( + "Unsupported reservation TTL: expected a positive duration of at most 24 hours.", + ); + } + return ttlMs; +} + +function assertClockNow(clock: Clock): IsoTimestamp { + const now = clock.now(); + timestampMilliseconds(now, "billing clock"); + return now as IsoTimestamp; +} + +function addMilliseconds(timestamp: IsoTimestamp, ms: number): IsoTimestamp { + return new Date( + timestampMilliseconds(timestamp, "billing clock") + ms, + ).toISOString() as IsoTimestamp; +} + +function defaultNewId(): string { + const cryptoApi = ( + globalThis as unknown as { + crypto?: { randomUUID?: () => string }; + } + ).crypto; + if (cryptoApi?.randomUUID === undefined) { + throw new Error( + "Billing reservation requires crypto.randomUUID or an injected newId.", + ); + } + return cryptoApi.randomUUID(); +} + +function requireClock(clock: Clock | undefined): Clock { + if (clock === undefined) { + throw new TypeError("Billing reservation requires an injected Clock."); + } + return clock; +} + +function assertEvent( + event: LedgerEvent, +): LedgerEvent { assertSafeEventId(event.eventId); timestampMilliseconds(event.eventAt, "billing event timestamp"); + const fields = event.fields; return { eventId: event.eventId, eventAt: event.eventAt, @@ -254,14 +509,193 @@ function assertEvent(event: LedgerEvent): LedgerEvent { trialStartAt: optionalTimestamp(event.trialStartAt, "trial start"), trialEndAt: optionalTimestamp(event.trialEndAt, "trial end"), cancelAtPeriodEnd: event.cancelAtPeriodEnd === true, + ...(event.offerRedeemed === true ? { offerRedeemed: true } : {}), + ...(fields === undefined ? {} : { fields }), }; } -function recordFromEvent( +function blankHostFields( + invariants: TFields | undefined, +): HostFromInvariants { + const blank = {} as HostFromInvariants; + if (invariants === undefined) { + return blank; + } + for (const key of hostFieldKeys(invariants)) { + const invariant = invariants[key]; + if (invariant === undefined) { + continue; + } + (blank as Record)[key] = + invariant.kind === "sticky" ? false : null; + } + return blank; +} + +function blankLedgerRecord( accountId: string, - event: LedgerEvent, - snapshotAt: IsoTimestamp | null, -): LedgerRecord { + invariants: TFields | undefined, +): LedgerRecord> { + return { + accountId, + providerCustomerId: null, + providerSubscriptionId: null, + providerPriceId: null, + status: "incomplete", + plan: null, + periodStartAt: null, + periodEndAt: null, + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + eventAt: null, + eventId: null, + snapshotAt: null, + reservationId: null, + reservationExpiresAt: null, + reservationSeeded: false, + offerRedeemed: false, + ...blankHostFields(invariants), + }; +} + +/** + * A row created only to hold a reservation has no event watermark yet. + * The first provider event must still apply; a corrupt row that already + * carries subscription state without a watermark must not. + */ +export function hasReservationProvenance( + record: Pick< + LedgerFields, + "reservationId" | "reservationExpiresAt" | "reservationSeeded" + >, +): boolean { + return ( + record.reservationSeeded === true || + record.reservationId != null || + record.reservationExpiresAt != null + ); +} + +export function isEventlessLedgerRow( + record: Pick< + LedgerFields, + | "eventAt" + | "eventId" + | "snapshotAt" + | "status" + | "providerCustomerId" + | "providerSubscriptionId" + | "providerPriceId" + | "plan" + | "periodStartAt" + | "periodEndAt" + | "trialStartAt" + | "trialEndAt" + | "cancelAtPeriodEnd" + | "reservationId" + | "reservationExpiresAt" + | "reservationSeeded" + >, +): boolean { + return ( + hasReservationProvenance(record) && + record.eventAt === null && + record.eventId === null && + record.snapshotAt === null && + record.status === "incomplete" && + record.providerCustomerId === null && + record.providerSubscriptionId === null && + record.providerPriceId === null && + record.plan === null && + record.periodStartAt === null && + record.periodEndAt === null && + record.trialStartAt === null && + record.trialEndAt === null && + record.cancelAtPeriodEnd === false + ); +} + +function hostValueFromCurrent( + current: object | null, + key: string, + invariant: FieldInvariant, +): HostFieldValue { + if (current === null) { + return invariant.kind === "sticky" ? false : null; + } + return storedHostValue((current as Record)[key]); +} + +/** + * Enforces declared invariants against freshly read state. + * + * `sticky` keeps a true flag. `firstWins` keeps the first write of a field + * or named group. Call this inside a decider so conflict retries re-evaluate. + */ +export function applyLedgerInvariants( + current: LedgerRecord | null, + incoming: Partial | undefined, + invariants: LedgerInvariants | undefined, +): THost { + const next = blankHostFields(invariants) as THost; + if (invariants === undefined) { + return next; + } + + const incomingFields = incoming as Record | undefined; + const groupKeys = new Map(); + for (const key of hostFieldKeys(invariants)) { + const invariant = invariants[key]; + if (invariant === undefined) { + continue; + } + if (invariant.kind === "sticky") { + const already = hostValueFromCurrent(current, key, invariant) === true; + const incomingValue = incomingFields?.[key]; + (next as Record)[key] = + already || incomingValue === true ? true : false; + continue; + } + const group = invariant.group ?? key; + const members = groupKeys.get(group) ?? []; + members.push(key); + groupKeys.set(group, members); + } + + for (const members of groupKeys.values()) { + const alreadyWritten = members.some((key) => + isWrittenHostValue( + hostValueFromCurrent(current, key, { kind: "firstWins" }), + ), + ); + for (const key of members) { + if (alreadyWritten) { + (next as Record)[key] = hostValueFromCurrent( + current, + key, + { kind: "firstWins" }, + ); + continue; + } + const incomingValue = incomingFields?.[key]; + (next as Record)[key] = + incomingValue === undefined + ? hostValueFromCurrent(current, key, { kind: "firstWins" }) + : storedHostValue(incomingValue); + } + } + + return next; +} + +function projectAppliedRecord( + current: LedgerRecord | null, + accountId: string, + event: LedgerEvent, + invariants: LedgerInvariants | undefined, +): LedgerRecord { + const granting = isGrantingStatus(event.status); return { accountId, providerCustomerId: event.providerCustomerId, @@ -276,29 +710,41 @@ function recordFromEvent( cancelAtPeriodEnd: event.cancelAtPeriodEnd, eventAt: event.eventAt, eventId: event.eventId, - snapshotAt, - }; + snapshotAt: current?.snapshotAt ?? null, + reservationId: granting ? null : (current?.reservationId ?? null), + reservationExpiresAt: granting + ? null + : (current?.reservationExpiresAt ?? null), + reservationSeeded: current?.reservationSeeded === true, + offerRedeemed: offerIsRedeemed(current, event), + ...applyLedgerInvariants(current, event.fields, invariants), + } as LedgerRecord; } /** * Decides whether an event may replace the current ledger row. * - * The incoming event applies when there is no row, when its second is - * strictly newer than `max(eventAt, snapshotAt)`, or when it shares that - * second and outranks the stored status. Exact redelivery (same event id) - * is a keep. Equal rank at the equal second drops the later arrival. An - * existing row with no usable watermark is untrusted: keep, never apply - * because the event arrived. + * The incoming event applies when there is no row, when the row exists only + * to hold a reservation, when its second is strictly newer than + * `max(eventAt, snapshotAt)`, or when it shares that second and outranks the + * stored status. Exact redelivery (same event id) is a keep. Equal rank at + * the equal second drops the later arrival. An existing row with no usable + * watermark that already carries subscription state is untrusted: keep, + * never apply because the event arrived. + * + * Host-declared `sticky` / `firstWins` fields are enforced on the write + * against the freshly read row. */ -export function decideLedgerApplication( - current: LedgerRecord | null, +export function decideLedgerApplication( + current: LedgerRecord | null, accountId: string, - event: LedgerEvent, -): ApplicationDecision { - if (current === null) { + event: LedgerEvent, + invariants?: LedgerInvariants, +): ApplicationDecision { + if (current === null || isEventlessLedgerRow(current)) { return { action: "write", - value: recordFromEvent(accountId, event, null), + value: projectAppliedRecord(current, accountId, event, invariants), }; } if (current.eventId === event.eventId) { @@ -321,13 +767,76 @@ export function decideLedgerApplication( return { action: "write", - value: recordFromEvent(accountId, event, current.snapshotAt), + value: projectAppliedRecord(current, accountId, event, invariants), + }; +} + +/** + * A reservation is live when it has an id and an unexpired deadline. + * Unparseable deadlines do not lock the account. + */ +export function reservationIsLive( + record: Pick, + now: IsoTimestamp, +): boolean { + if (record.reservationId == null) { + return false; + } + const expires = canonicalTimestampMilliseconds(record.reservationExpiresAt); + const nowMs = canonicalTimestampMilliseconds(now); + if (expires === null || nowMs === null) { + return false; + } + return nowMs < expires; +} + +/** + * Mints or refuses a checkout reservation against freshly read state. + * + * `reservationId` is a candidate for this decider run only. The caller must + * read the winning id back from the stored record after the write. + */ +export function decideReservation( + current: LedgerRecord | null, + accountId: string, + now: IsoTimestamp, + reservationId: string, + expiresAt: IsoTimestamp, + invariants?: LedgerInvariants, +): ReserveDecision { + const base = + current === null + ? (blankLedgerRecord(accountId, invariants) as LedgerRecord) + : current; + if (base.offerRedeemed) { + return { action: "keep", reason: "redeemed" }; + } + if (isGrantingStatus(base.status)) { + return { action: "keep", reason: "subscribed" }; + } + if (reservationIsLive(base, now)) { + return { action: "keep", reason: "reserved" }; + } + return { + action: "write", + value: { + ...base, + accountId, + reservationId, + reservationExpiresAt: expiresAt, + reservationSeeded: true, + }, }; } -type EncodedLedgerRecord = Record; +type EncodedLedgerRecord = Record< + keyof LedgerFields | keyof THost, + StoredValue +>; -function encodeLedgerRecord(value: LedgerRecord): EncodedLedgerRecord { +function encodeLedgerCore( + value: LedgerFields, +): Record { return { accountId: value.accountId, providerCustomerId: value.providerCustomerId, @@ -343,10 +852,39 @@ function encodeLedgerRecord(value: LedgerRecord): EncodedLedgerRecord { eventAt: value.eventAt, eventId: value.eventId, snapshotAt: value.snapshotAt, - }; + reservationId: value.reservationId, + reservationExpiresAt: value.reservationExpiresAt, + reservationSeeded: value.reservationSeeded, + offerRedeemed: value.offerRedeemed, + } satisfies Record; +} + +function encodeLedgerRecord( + value: LedgerRecord, + hostKeys: readonly (keyof THost & string)[], +): EncodedLedgerRecord { + const encoded = encodeLedgerCore(value) as EncodedLedgerRecord; + for (const key of hostKeys) { + if (isForbiddenHostFieldName(key)) { + continue; + } + encoded[key] = storedHostValue((value as Record)[key]); + } + return encoded; } -function decodeLedgerRecord(record: StoredRecord): LedgerRecord { +function decodeLedgerRecord( + record: StoredRecord, + hostKeys: readonly (keyof THost & string)[], + invariants: LedgerInvariants | undefined, +): LedgerRecord { + const host = blankHostFields(invariants); + for (const key of hostKeys) { + const invariant = invariants?.[key]; + const raw = record[key]; + (host as Record)[key] = + invariant?.kind === "sticky" ? raw === true : storedHostValue(raw); + } return { accountId: String(record["accountId"] ?? ""), providerCustomerId: toNullableString(record["providerCustomerId"]), @@ -362,7 +900,12 @@ function decodeLedgerRecord(record: StoredRecord): LedgerRecord { eventAt: storedTimestamp(record["eventAt"]), eventId: toNullableString(record["eventId"]), snapshotAt: storedTimestamp(record["snapshotAt"]), - }; + reservationId: toNullableString(record["reservationId"]), + reservationExpiresAt: storedTimestamp(record["reservationExpiresAt"]), + reservationSeeded: record["reservationSeeded"] === true, + offerRedeemed: record["offerRedeemed"] === true, + ...host, + } as LedgerRecord; } export function billingLedgerKey(accountId: string): EntityKey { @@ -372,22 +915,37 @@ export function billingLedgerKey(accountId: string): EntityKey { }; } -export function billingLedgerCollection(): CollectionDefinition { +export function billingLedgerCollection( + fields?: TFields, +): CollectionDefinition>> { + type THost = HostFromInvariants; + const invariants = fields as LedgerInvariants | undefined; + assertHostFieldNames(invariants); + const hostKeys = hostFieldKeys(invariants) as readonly (keyof THost & + string)[]; return defineCollection({ name: "billingLedger", key: (value) => billingLedgerKey(value.accountId), codec: { - encode: encodeLedgerRecord, - decode: decodeLedgerRecord, + encode: (value) => encodeLedgerRecord(value, hostKeys), + decode: (record) => + decodeLedgerRecord(record, hostKeys, invariants), }, }); } -export function createBillingLedger( - options: BillingLedgerOptions, -): BillingLedger { +export function createBillingLedger( + options: BillingLedgerOptions, +): BillingLedger> { + type THost = HostFromInvariants; const logger = options.logger ?? noopLogger; - const definition = billingLedgerCollection(); + const newId = options.newId ?? defaultNewId; + const invariants = options.fields as LedgerInvariants | undefined; + assertHostFieldNames(invariants); + const defaultTtlMs = assertTtlMs( + options.reservationTtlMs ?? DEFAULT_RESERVATION_TTL_MS, + ); + const definition = billingLedgerCollection(options.fields); const rows = options.store.collection(definition); return { @@ -399,7 +957,7 @@ export function createBillingLedger( assertSafeAccountId(accountId); const incoming = assertEvent(event); const result = await rows.update(billingLedgerKey(accountId), (current) => - decideLedgerApplication(current, accountId, incoming), + decideLedgerApplication(current, accountId, incoming, invariants), ); if (result.value === null) { throw new Error("Billing ledger apply did not persist a record."); @@ -418,5 +976,87 @@ export function createBillingLedger( ); return { applied, record: result.value }; }, + + async reserve(accountId, reserveOptions) { + assertSafeAccountId(accountId); + const clock = requireClock(options.clock); + const ttlMs = assertTtlMs(reserveOptions?.ttlMs ?? defaultTtlMs); + let refusal: ReserveRefusal | undefined; + const result = await rows.update( + billingLedgerKey(accountId), + (current) => { + const now = assertClockNow(clock); + const candidateId = assertSafeReservationId(newId()); + const decision = decideReservation( + current, + accountId, + now, + candidateId, + addMilliseconds(now, ttlMs), + invariants, + ); + if (decision.action === "keep") { + refusal = decision.reason; + return { action: "keep" as const }; + } + return decision; + }, + ); + if (result.written) { + const stored = result.value; + if ( + stored === null || + stored.reservationId === null || + stored.reservationExpiresAt === null + ) { + throw new Error( + "Billing reservation write did not persist a reservation.", + ); + } + logger.log("info", "Billing reservation minted", { + accountId, + reserved: true, + }); + return { + reserved: true, + reservationId: stored.reservationId, + expiresAt: stored.reservationExpiresAt, + }; + } + const reason = refusal ?? "reserved"; + logger.log("info", "Billing reservation refused", { + accountId, + reserved: false, + reason, + }); + return { reserved: false, reason }; + }, + + async release(accountId, reservationId) { + assertSafeAccountId(accountId); + assertSafeReservationId(reservationId); + const result = await rows.update( + billingLedgerKey(accountId), + (current) => { + if (current === null || current.reservationId !== reservationId) { + return { action: "keep" as const }; + } + return { + action: "write" as const, + value: { + ...current, + reservationId: null, + reservationExpiresAt: null, + }, + }; + }, + ); + const released = result.written; + logger.log("info", "Billing reservation released", { + accountId, + released, + }); + return { released }; + }, }; }