billing: prepared requests sent verbatim, outcome classes, exhaustive lists, renewal invoices, and a fake that models every unclear-outcome and renewal case (plans 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+2,755
−42
internal/billing/billing.go+195 −1internal/billing/billingtest/fake.go+1,289 −36internal/billing/billingtest/fake_test.go+903 −0internal/billing/clock.go+101 −0internal/billing/clock_test.go+97 −0internal/billing/recognise.go+13 −5internal/billing/recognise_test.go+97 −0internal/billingstripe/unimplemented.go+60 −0
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index 9d064e4bf..b03aa90c8 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -30,8 +30,10 @@ const ( |
| StateEnded State = "ended" |
| ) |
| -// Item is one line of a subscription: a price and its quantity. |
| +// Item is one line of a subscription: a price and its quantity. ItemID is |
| +// the provider's id for the line, which a ChangeRequest names. |
| type Item struct { |
| + ItemID string |
| PriceID string |
| Quantity int64 |
| Currency string |
| @@ -55,8 +57,22 @@ type Subscription struct { |
| CancelAtPeriodEnd bool |
| Items []Item |
| ItemsComplete bool // false when the provider said there are more items than it sent |
| + // PendingUpdate is a charged change waiting for its payment (provider |
| + // fact 8): its items are not applied, and it is dropped at |
| + // PendingExpires unless paid first. |
| + PendingUpdate bool |
| + PendingExpires time.Time |
| + // Collecting is the provider still trying to collect an open invoice on |
| + // the subscription. |
| + Collecting bool |
| + // ProviderTime is the read's Date header; zero when the response had |
| + // none. |
| + ProviderTime time.Time |
| } |
| +// Renewing is a live subscription that will renew at its period end. |
| +func (s *Subscription) Renewing() bool { return s.Live && !s.CancelAtPeriodEnd } |
| + |
| // EventKind says what an event asks the console to re-read. |
| type EventKind string |
| @@ -77,11 +93,142 @@ type Event struct { |
| // MaxCustomerSubscriptions bounds CustomerSubscriptions. |
| const MaxCustomerSubscriptions = 10 |
| +// MaxListPages bounds every exhaustive list: at most this many pages of up |
| +// to 100, else ErrIncomplete (Invariant 3). |
| +const MaxListPages = 10 |
| + |
| +// Proration is how a change is charged. |
| +type Proration string |
| + |
| +const ( |
| + // ProrateNone changes quantities with no charge: reductions and |
| + // restores, which take effect for the next renewal's invoice. |
| + ProrateNone Proration = "none" |
| + // ProrateNow charges the prorated difference at once and applies the |
| + // change only once that is paid (a pending update until then). |
| + ProrateNow Proration = "now" |
| +) |
| + |
| +// ItemChange is one line of a ChangeRequest. An ItemID names an existing |
| +// line: Delete removes it, otherwise Quantity (and PriceID, when set, |
| +// swapping its price) is what it becomes. An empty ItemID adds a new line |
| +// of PriceID at Quantity. |
| +type ItemChange struct { |
| + ItemID, PriceID string |
| + Quantity int64 |
| + Delete bool |
| +} |
| + |
| +// ChangeRequest is a subscription change, every parameter resolved: |
| +// ProrationDate is frozen in provider time when the change is prepared. |
| +type ChangeRequest struct { |
| + Subscription string |
| + Items []ItemChange |
| + Proration Proration |
| + ProrationDate time.Time |
| + IdempotencyKey string |
| +} |
| + |
| +// CheckoutItem is one line a Checkout sells. |
| +type CheckoutItem struct { |
| + PriceID string |
| + Quantity int64 |
| +} |
| + |
| +// CheckoutRequest is a Checkout session to create, every parameter |
| +// resolved. |
| +type CheckoutRequest struct { |
| + Customer, AccountSqid, IntentID, Book, Currency string |
| + Items []CheckoutItem |
| + SuccessURL, CancelURL string |
| + Coupon string // the resolved coupon id, "" for none; never a flag |
| + ExpiresAt time.Time |
| + IdempotencyKey string |
| +} |
| + |
| +// CheckoutState is a Checkout session's state. |
| +type CheckoutState string |
| + |
| +const ( |
| + CheckoutOpen CheckoutState = "open" |
| + CheckoutComplete CheckoutState = "complete" |
| + CheckoutExpired CheckoutState = "expired" |
| +) |
| + |
| +// CheckoutInfo is a read of one Checkout session. |
| +type CheckoutInfo struct { |
| + ID, URL, Subscription, Customer, IntentID string |
| + State CheckoutState |
| + ExpiresAt time.Time |
| +} |
| + |
| +// The kinds of Prepared. |
| +const ( |
| + PreparedCustomer = "customer" |
| + PreparedCheckout = "checkout" |
| + PreparedExpire = "expire" |
| + PreparedChange = "change" |
| + PreparedRenewal = "renewal" |
| +) |
| + |
| +// Prepared is a write exactly as the adapter will send it: opaque to the |
| +// console, persisted before the first send, resent only verbatim (same |
| +// method, path, body and idempotency key). |
| +type Prepared struct { |
| + Kind string |
| + Method, Path string |
| + Body []byte |
| + Key string |
| +} |
| + |
| +// Result is what a definite answer to a Send says. Which fields are set |
| +// depends on the Prepared's kind. |
| +type Result struct { |
| + Subscription *Subscription // a change or renewal |
| + Checkout *CheckoutInfo // a Checkout create or expiry |
| + Customer string // a customer create |
| + Replayed bool // the provider replayed a stored answer (fact 7) |
| + ProviderTime time.Time // the response's Date header; zero when it had none |
| +} |
| + |
| +// InvoiceQuantities is a renewal invoice reduced to the quantity it billed |
| +// per price. |
| +type InvoiceQuantities struct { |
| + Invoice string |
| + PeriodStart time.Time |
| + ByPrice map[string]int64 |
| +} |
| + |
| var ( |
| // ErrBadEvent is any signature or shape failure on an event. |
| ErrBadEvent = errors.New("billing: event refused") |
| // ErrNotFound is the provider saying the object does not exist. |
| ErrNotFound = errors.New("billing: not found") |
| + |
| + // The outcome classes of a Send (provider facts 1 to 5). A nil error is |
| + // definite success. |
| + |
| + // ErrPaymentFailed is definite: the charge was declined, nothing applied. |
| + ErrPaymentFailed = errors.New("billing: payment failed") |
| + // ErrRefused is definite: an executed or validation 4xx, nothing applied. |
| + ErrRefused = errors.New("billing: request refused") |
| + // ErrNotExecuted is a 429 or another pre-execution refusal: resend the |
| + // same bytes (fact 2). |
| + ErrNotExecuted = errors.New("billing: request not executed") |
| + // ErrInFlight is a 409 on the same key: wait, then resend the same bytes |
| + // (fact 3). |
| + ErrInFlight = errors.New("billing: request still executing") |
| + // ErrNoResponse is a transport error or timeout: resend the same bytes |
| + // inside the window (fact 4). |
| + ErrNoResponse = errors.New("billing: no response") |
| + // ErrIndeterminate is a 5xx: cached, so a resend returns it again |
| + // (fact 5). |
| + ErrIndeterminate = errors.New("billing: outcome indeterminate") |
| + |
| + // ErrIncomplete is a list longer than MaxListPages pages. |
| + ErrIncomplete = errors.New("billing: list incomplete") |
| + // ErrNoHouseCoupon is a house Checkout with no coupon configured. |
| + ErrNoHouseCoupon = errors.New("billing: no house coupon configured") |
| ) |
| // Provider is a billing provider as the console uses it. |
| @@ -102,4 +249,51 @@ type Provider interface { |
| // Check is the readiness check: the provider account and every price |
| // of the book agree with the configuration. |
| Check(ctx context.Context, book *plans.PriceBook, prices PriceMap) error |
| + |
| + // The Prepare methods encode a write exactly as Send will send it, with |
| + // the given idempotency key. They make no request. |
| + PrepareCustomer(accountSqid, key string) (Prepared, error) |
| + PrepareCheckout(req CheckoutRequest) (Prepared, error) |
| + PrepareExpire(sessionID, key string) (Prepared, error) |
| + PrepareChange(req ChangeRequest) (Prepared, error) |
| + PrepareRenewal(subscription string, renew bool, key string) (Prepared, error) |
| + // Send makes exactly one request: p's bytes under p's key. A nil error |
| + // is definite success; otherwise the error is one of the outcome |
| + // classes (ErrPaymentFailed, ErrRefused, ErrNotExecuted, ErrInFlight, |
| + // ErrNoResponse, ErrIndeterminate). |
| + Send(ctx context.Context, p Prepared) (Result, error) |
| + |
| + // LiveSubscriptions names every live subscription of a customer, |
| + // examining subscriptions in every status. Exhaustive: ErrIncomplete |
| + // past MaxListPages pages. |
| + LiveSubscriptions(ctx context.Context, customer string) ([]string, error) |
| + // CustomerCheckouts is every Checkout session of a customer created |
| + // after createdAfter. Exhaustive. |
| + CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]CheckoutInfo, error) |
| + // Checkout reads one session. ErrNotFound when the provider has none. |
| + Checkout(ctx context.Context, sessionID string) (CheckoutInfo, error) |
| + // RenewalInvoice is the quantities the subscription's renewal invoice |
| + // for the period starting at periodStart billed: exhaustive invoice |
| + // pages, then exhaustive line pages. ErrNotFound when there is none. |
| + RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (InvoiceQuantities, error) |
| + // PortalURL opens a customer portal session. |
| + PortalURL(ctx context.Context, customer, returnURL, key string) (string, error) |
| + // ClockProbe is one cheap read whose only purpose is the response's |
| + // Date header, observed into ctx's ClockRecorder. |
| + ClockProbe(ctx context.Context) error |
| +} |
| + |
| +// FindItem is the subscription's item whose price is for kind and name |
| +// (KindPlan or KindPack). An empty name matches any name of that kind. |
| +func FindItem(sub *Subscription, prices PriceMap, kind, name string) (Item, bool) { |
| + if sub == nil { |
| + return Item{}, false |
| + } |
| + for _, it := range sub.Items { |
| + ref, ok := prices.Lookup(it.PriceID) |
| + if ok && ref.Kind == kind && (name == "" || ref.Name == name) { |
| + return it, true |
| + } |
| + } |
| + return Item{}, false |
| } |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 54e39b55f..fa69267ab 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -1,28 +1,127 @@ |
| -// Package billingtest is an in-memory billing.Provider for tests. |
| +// Package billingtest is an in-memory billing.Provider for tests: a Fake |
| +// that behaves like the payment provider the console talks to, including |
| +// every unclear outcome the console must recover from. |
| +// |
| +// What it models (plan 6b, "Provider facts" 1 to 10): |
| +// |
| +// - Per-key idempotency. Send stores the answer of every request that |
| +// began executing under its key; the same bytes again replay it |
| +// (Result.Replayed), a 5xx included; other bytes under the key are an |
| +// idempotency error (ErrRefused and ErrKeyReused). Keys can be pruned |
| +// after 24 h (PruneKeysOlderThan), after which the same bytes execute |
| +// anew. |
| +// - Pending updates: a ProrateNow change whose payment fails softly waits |
| +// as a pending update (FailPayment), paid later (PayPending) or dropped |
| +// (ExpirePending, or provider time passing PendingExpires). |
| +// - Unclear outcomes: a request lost before delivery (FailBeforeDelivery), |
| +// a response lost after applying (LoseNextResponse), a request that |
| +// lands only after further calls (CompleteLater), cached 500s before |
| +// and after applying, 409 in flight (InFlight), 429 (RateLimit), and a |
| +// request that first applies after a renewal (ApplyAfterRenewal). |
| +// - Renewal across a period boundary with a renewal invoice (Renew). |
| +// - Checkout sessions, their completion, expiry and races. |
| +// - Provider time: every response carries ProviderClock as its Date, |
| +// independent of the console's wall clock (SetConsoleClock) and of an |
| +// injectable monotonic clock (AdvanceMonotonic). |
| +// - Paging like the provider: limit up to 100, has_more, starting_after; |
| +// every page is one request in CallsBy. |
| +// |
| +// One-shot knobs are fields; set them before the code under test runs, or |
| +// under Lock while it may be running. Methods (InFlight, CompleteLater, |
| +// Renew, ...) take the lock themselves: never call them while holding Lock. |
| package billingtest |
| import ( |
| + "bytes" |
| "context" |
| "encoding/json" |
| + "errors" |
| + "fmt" |
| "net/http" |
| + "slices" |
| "sort" |
| "sync" |
| + "sync/atomic" |
| "time" |
| "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/plans" |
| ) |
| -// Fake is an in-memory billing.Provider. Set Subs and Checkouts to what the |
| -// provider would say; set Err to make every call fail, CheckErr to fail |
| -// only the readiness check. Calls counts every call but ParseEvent. |
| +var ( |
| + // ErrCrash is what Send returns when CrashBeforeSend or CrashAfterSend |
| + // fires: the console process "dies" at that point. It is deliberately |
| + // none of billing's outcome classes. The console's send path must treat |
| + // an error outside the classes as "stop and record nothing more" and |
| + // return it, so the operation row stays as it was before the send |
| + // (sending). The test then discards that Server, builds a new one on |
| + // the same store with the same Fake (a restart), and drives recovery. |
| + ErrCrash = errors.New("billingtest: injected crash") |
| + // ErrInjected is an injected read failure (InvoiceReadFails). |
| + ErrInjected = errors.New("billingtest: injected failure") |
| + // ErrKeyReused is the provider's idempotency error: a key sent again |
| + // with other parameters. Send wraps it with billing.ErrRefused. |
| + ErrKeyReused = errors.New("billingtest: idempotency key reused with other parameters") |
| +) |
| + |
| +// Invoice billing reasons. |
| +const ( |
| + ReasonCycle = "subscription_cycle" // a renewal |
| + ReasonUpdate = "subscription_update" // a proration charge |
| + ReasonCreate = "subscription_create" // a Checkout's first invoice |
| +) |
| + |
| +// maxPage is the provider's largest page. |
| +const maxPage = 100 |
| + |
| +// Customer is a customer at the provider. |
| +type Customer struct{ ID, Account string } |
| + |
| +// Invoice is an invoice at the provider. Lines use PriceID and Quantity. |
| +type Invoice struct { |
| + ID, Subscription, Reason string |
| + PeriodStart time.Time |
| + Lines []billing.Item |
| +} |
| + |
| +// Session is a Checkout session at the provider: what a read shows, when |
| +// it was created, and what was asked for (CompleteCheckout builds the |
| +// subscription from it). |
| +type Session struct { |
| + billing.CheckoutInfo |
| + Created time.Time |
| + Request billing.CheckoutRequest |
| +} |
| + |
| +// PageRequest is one list page the Fake served. |
| +type PageRequest struct { |
| + Method string // the CallsBy key it was counted under |
| + Limit int |
| + StartingAfter string |
| + IDs []string // what the page held |
| + HasMore bool |
| +} |
| + |
| +// Fake is an in-memory billing.Provider. |
| +// |
| +// 6a's fields keep their meaning: Subs, Checkouts, Err, CheckErr, Calls, |
| +// SubErr, CustomerCalls, BeforeSubscription. |
| type Fake struct { |
| - mu sync.Mutex |
| - Subs map[string]*billing.Subscription |
| + mu sync.Mutex |
| + |
| + // Subs is the provider's subscriptions by id. Reads return copies. |
| + // Items seeded without an ItemID get a stable one when first served. |
| + Subs map[string]*billing.Subscription |
| + // Checkouts maps a checkout id to the subscription it made (6a's |
| + // CheckoutSubscription); Sessions is consulted when absent. |
| Checkouts map[string]string |
| - Err error |
| - CheckErr error |
| - Calls int |
| + // Err fails every call (no Date): a provider that cannot be reached. |
| + Err error |
| + // CheckErr fails only the readiness check. |
| + CheckErr error |
| + // Calls counts every request but ParseEvent. It equals the sum of |
| + // CallsBy. |
| + Calls int |
| // SubErr fails Subscription for one id only. |
| SubErr map[string]error |
| // CustomerCalls counts CustomerSubscriptions calls. |
| @@ -31,20 +130,385 @@ type Fake struct { |
| // Subscription call, outside the Fake's lock (so it may call back into |
| // the code under test); a non-nil error is returned as the read's. |
| BeforeSubscription func(id string) error |
| + |
| + // Customers, Sessions and Invoices are the rest of the provider's |
| + // state. AddSession and AddInvoice seed them with ids. |
| + Customers map[string]*Customer |
| + Sessions map[string]*Session |
| + Invoices map[string]*Invoice |
| + |
| + // CallsBy counts requests by method name: "Subscription", |
| + // "CheckoutSubscription", "CustomerSubscriptions", "Check", "Send", |
| + // "Checkout", "PortalURL", "ClockProbe", and one per list page under |
| + // "LiveSubscriptions", "CustomerCheckouts", "RenewalInvoice" (invoice |
| + // pages) and "RenewalInvoiceLines" (line pages). A request that fails |
| + // still counts; a CrashBeforeSend does not (nothing was sent). |
| + CallsBy map[string]int |
| + // Sent is every Prepared Send received, in order (not those stopped by |
| + // CrashBeforeSend): a test compares resent bytes with these. |
| + Sent []billing.Prepared |
| + // PageLog is every list page served, in order. |
| + PageLog []PageRequest |
| + |
| + // ProviderClock is the provider's time: every response's Date (to the |
| + // second), the base of pending-update and session expiry, and the |
| + // clock keys age on. Move it with SetProviderClock, AdvanceProvider or |
| + // Elapse. New sets it to the current time. |
| + ProviderClock time.Time |
| + |
| + // PageSize is the limit the Fake's lists ask for, as the adapter does: |
| + // 0 is 100, and anything above 100 is 100. |
| + PageSize int |
| + // Headerless makes every response arrive with no Date header: calls |
| + // succeed, but nothing is observed and ProviderTime is zero. |
| + Headerless bool |
| + // HeaderlessTimeout fails the next n requests of any kind (reads, list |
| + // pages, the probe, Send) with billing.ErrNoResponse before any header |
| + // arrives: no Date, and a Send so failed was not executed. |
| + HeaderlessTimeout int |
| + // ProbeErr fails every ClockProbe with this error, no Date, until |
| + // cleared. |
| + ProbeErr error |
| + |
| + // FailBeforeDelivery loses the next n Sends before they reach the |
| + // provider: billing.ErrNoResponse, nothing executed or stored. |
| + FailBeforeDelivery int |
| + // RateLimit answers the next n Sends with a 429: billing.ErrNotExecuted, |
| + // nothing executed or stored (fact 2). |
| + RateLimit int |
| + // LoseNextResponse executes and stores the next Send that executes, then |
| + // loses its response: billing.ErrNoResponse (fact 4). One-shot. |
| + LoseNextResponse bool |
| + // Cached500Before makes the next Send that executes fail with a 500 |
| + // before applying anything; the 500 is stored under its key, so a |
| + // resend returns it again (fact 5). One-shot. |
| + Cached500Before bool |
| + // Cached500After is Cached500Before after applying. One-shot. |
| + Cached500After bool |
| + // FailPayment declines the next n ProrateNow charges softly: the change |
| + // waits as a pending update (PendingUpdate, PendingExpires, Collecting) |
| + // and the Send succeeds, granting nothing (fact 8). |
| + FailPayment int |
| + // DeclineHard declines the next n ProrateNow charges outright: |
| + // billing.ErrPaymentFailed, nothing applied, the answer stored. |
| + DeclineHard int |
| + // CrashBeforeSend makes the next Send return ErrCrash before the |
| + // provider receives anything (not counted, not in Sent). One-shot. |
| + CrashBeforeSend bool |
| + // CrashAfterSend makes the next Send reach the provider and be handled |
| + // in full (applied and stored, if it would be), then return ErrCrash in |
| + // place of the answer: the console dies before recording. One-shot. |
| + CrashAfterSend bool |
| + // BeforeSend, when set, runs at the start of every Send, outside the |
| + // Fake's lock, after CrashBeforeSend is checked: something that happens |
| + // at the provider just before the request arrives (a buyer completing a |
| + // session, say). A non-nil error is returned as the Send's answer. |
| + BeforeSend func(p billing.Prepared) error |
| + |
| + keys map[string]*keyEntry |
| + pending map[string][]billing.Item // a pending update's target items, by subscription |
| + late []*lateSend |
| + held map[string]bool // ApplyAfterRenewal keys not yet sent |
| + inFlight int |
| + lateArmed bool |
| + lateAfter int |
| + invoiceErr int |
| + seq int // id counter |
| + callSeq int // request counter, for CompleteLater |
| + |
| + mono atomic.Int64 // the monotonic source, nanoseconds |
| + cmu sync.Mutex |
| + console time.Time // the console's injected wall clock |
| +} |
| + |
| +type keyEntry struct { |
| + method, path string |
| + body []byte |
| + executing bool // held or landing later: a resend is a 409 |
| + result billing.Result |
| + err error |
| + storedAt time.Time |
| +} |
| + |
| +func (e *keyEntry) same(p billing.Prepared) bool { |
| + return e.method == p.Method && e.path == p.Path && bytes.Equal(e.body, p.Body) |
| +} |
| + |
| +// lateSend is an executing request that lands later: at the end of call |
| +// number dueSeq (CompleteLater) or at the next Renew (ApplyAfterRenewal). |
| +type lateSend struct { |
| + p billing.Prepared |
| + body any |
| + dueSeq int |
| + afterRenewal bool |
| } |
| -// New is an empty Fake. |
| +// New is an empty Fake whose provider and console clocks read the current |
| +// time, to the second. |
| func New() *Fake { |
| - return &Fake{Subs: map[string]*billing.Subscription{}, Checkouts: map[string]string{}} |
| + f := &Fake{} |
| + f.init() |
| + now := time.Now().UTC().Truncate(time.Second) |
| + f.ProviderClock = now |
| + f.console = now |
| + return f |
| } |
| -// Lock and Unlock guard a test's edits to the maps while the code under |
| -// test may be reading them. |
| +func (f *Fake) init() { |
| + if f.Subs == nil { |
| + f.Subs = map[string]*billing.Subscription{} |
| + } |
| + if f.Checkouts == nil { |
| + f.Checkouts = map[string]string{} |
| + } |
| + if f.Customers == nil { |
| + f.Customers = map[string]*Customer{} |
| + } |
| + if f.Sessions == nil { |
| + f.Sessions = map[string]*Session{} |
| + } |
| + if f.Invoices == nil { |
| + f.Invoices = map[string]*Invoice{} |
| + } |
| + if f.CallsBy == nil { |
| + f.CallsBy = map[string]int{} |
| + } |
| + if f.keys == nil { |
| + f.keys = map[string]*keyEntry{} |
| + } |
| + if f.pending == nil { |
| + f.pending = map[string][]billing.Item{} |
| + } |
| + if f.held == nil { |
| + f.held = map[string]bool{} |
| + } |
| +} |
| + |
| +// Lock and Unlock guard a test's edits to the maps and knobs while the |
| +// code under test may be calling the Fake. |
| func (f *Fake) Lock() { f.mu.Lock() } |
| func (f *Fake) Unlock() { f.mu.Unlock() } |
| +// ---- clocks ---- |
| + |
| +// SetProviderClock sets the provider's time. |
| +func (f *Fake) SetProviderClock(t time.Time) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.ProviderClock = t |
| +} |
| + |
| +// AdvanceProvider moves the provider's time only. |
| +func (f *Fake) AdvanceProvider(d time.Duration) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.ProviderClock = f.ProviderClock.Add(d) |
| +} |
| + |
| +// SetConsoleClock sets the console's wall clock, which tests inject as the |
| +// console's now (ConsoleNow). Provider time never follows it. |
| +func (f *Fake) SetConsoleClock(t time.Time) { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + f.console = t |
| +} |
| + |
| +// AdvanceConsole moves the console's wall clock only. |
| +func (f *Fake) AdvanceConsole(d time.Duration) { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + f.console = f.console.Add(d) |
| +} |
| + |
| +// ConsoleNow reads the console's wall clock: a func(time.Time) a test |
| +// injects as the console's now. |
| +func (f *Fake) ConsoleNow() time.Time { |
| + f.cmu.Lock() |
| + defer f.cmu.Unlock() |
| + return f.console |
| +} |
| + |
| +// Monotonic reads the injected monotonic clock: inject it as a |
| +// billing.ClockRecorder's Monotonic (or use Recorder). It takes no lock. |
| +func (f *Fake) Monotonic() time.Duration { return time.Duration(f.mono.Load()) } |
| + |
| +// AdvanceMonotonic moves the monotonic clock only: local time passing with |
| +// no new provider observation. |
| +func (f *Fake) AdvanceMonotonic(d time.Duration) { f.mono.Add(int64(d)) } |
| + |
| +// Elapse is real time passing: the provider clock, the console clock and |
| +// the monotonic clock all move by d. |
| +func (f *Fake) Elapse(d time.Duration) { |
| + f.AdvanceProvider(d) |
| + f.AdvanceConsole(d) |
| + f.AdvanceMonotonic(d) |
| +} |
| + |
| +// Recorder is a billing.ClockRecorder on the Fake's monotonic clock. |
| +func (f *Fake) Recorder() *billing.ClockRecorder { |
| + return &billing.ClockRecorder{Monotonic: f.Monotonic} |
| +} |
| + |
| +// date is the Date header the next response carries: zero when Headerless. |
| +func (f *Fake) date() time.Time { |
| + if f.Headerless { |
| + return time.Time{} |
| + } |
| + return f.ProviderClock.UTC().Truncate(time.Second) |
| +} |
| + |
| +// respond observes the response's Date into ctx's recorder. |
| +func (f *Fake) respond(ctx context.Context) time.Time { |
| + d := f.date() |
| + billing.ObserveDate(ctx, d) |
| + return d |
| +} |
| + |
| +// ---- request bookkeeping (all under f.mu) ---- |
| + |
| +// begin counts one request and settles time-driven provider state. |
| +func (f *Fake) begin(method string) { |
| + f.init() |
| + f.Calls++ |
| + f.CallsBy[method]++ |
| + f.callSeq++ |
| + f.settle() |
| +} |
| + |
| +// end lands every CompleteLater request now due. |
| +func (f *Fake) end() { |
| + var keep []*lateSend |
| + for _, l := range f.late { |
| + if !l.afterRenewal && f.callSeq >= l.dueSeq { |
| + f.land(l) |
| + continue |
| + } |
| + keep = append(keep, l) |
| + } |
| + f.late = keep |
| +} |
| + |
| +func (f *Fake) timedOut() bool { |
| + if f.HeaderlessTimeout > 0 { |
| + f.HeaderlessTimeout-- |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +func (f *Fake) nextID(prefix string) string { |
| + f.seq++ |
| + return fmt.Sprintf("%s_fake_%06d", prefix, f.seq) |
| +} |
| + |
| +// settle applies what provider time does by itself: pending updates and |
| +// open sessions expire. It also gives seeded items their ids. |
| +func (f *Fake) settle() { |
| + now := f.ProviderClock |
| + for id, s := range f.Subs { |
| + for i := range s.Items { |
| + if s.Items[i].ItemID == "" { |
| + s.Items[i].ItemID = fmt.Sprintf("si_%s_%d", id, i) |
| + } |
| + } |
| + if s.PendingUpdate && !s.PendingExpires.IsZero() && !now.Before(s.PendingExpires) { |
| + f.dropPending(s) |
| + } |
| + } |
| + for _, s := range f.Sessions { |
| + if s.State == billing.CheckoutOpen && !s.ExpiresAt.IsZero() && !now.Before(s.ExpiresAt) { |
| + s.State = billing.CheckoutExpired |
| + } |
| + } |
| +} |
| + |
| +func (f *Fake) dropPending(s *billing.Subscription) { |
| + s.PendingUpdate, s.PendingExpires, s.Collecting = false, time.Time{}, false |
| + delete(f.pending, s.ID) |
| +} |
| + |
| +func snapshot(s *billing.Subscription) *billing.Subscription { |
| + c := *s |
| + c.Items = slices.Clone(s.Items) |
| + return &c |
| +} |
| + |
| +func cloneResult(r billing.Result) billing.Result { |
| + if r.Subscription != nil { |
| + r.Subscription = snapshot(r.Subscription) |
| + } |
| + if r.Checkout != nil { |
| + c := *r.Checkout |
| + r.Checkout = &c |
| + } |
| + return r |
| +} |
| + |
| +func sortedKeys[V any](m map[string]V, keep func(V) bool) []string { |
| + var ids []string |
| + for id, v := range m { |
| + if keep(v) { |
| + ids = append(ids, id) |
| + } |
| + } |
| + sort.Strings(ids) |
| + return ids |
| +} |
| + |
| +func (f *Fake) pageLimit() int { |
| + if f.PageSize <= 0 || f.PageSize > maxPage { |
| + return maxPage |
| + } |
| + return f.PageSize |
| +} |
| + |
| +// list serves ids (in id order) page by page as the provider does, one |
| +// counted request per page, calling each for every id served. More than |
| +// billing.MaxListPages pages is billing.ErrIncomplete. |
| +func (f *Fake) list(ctx context.Context, method string, ids []string, each func(id string)) error { |
| + limit := f.pageLimit() |
| + pos := map[string]int{} |
| + for i, id := range ids { |
| + pos[id] = i |
| + } |
| + after := "" |
| + for page := 1; ; page++ { |
| + f.begin(method) |
| + if f.Err != nil { |
| + f.end() |
| + return f.Err |
| + } |
| + if f.timedOut() { |
| + f.end() |
| + return fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + start := 0 |
| + if after != "" { |
| + start = pos[after] + 1 |
| + } |
| + stop := min(start+limit, len(ids)) |
| + got := ids[start:stop] |
| + hasMore := stop < len(ids) |
| + f.PageLog = append(f.PageLog, PageRequest{Method: method, Limit: limit, StartingAfter: after, IDs: slices.Clone(got), HasMore: hasMore}) |
| + f.respond(ctx) |
| + for _, id := range got { |
| + each(id) |
| + } |
| + f.end() |
| + if !hasMore { |
| + return nil |
| + } |
| + if page == billing.MaxListPages { |
| + return billing.ErrIncomplete |
| + } |
| + after = got[len(got)-1] |
| + } |
| +} |
| + |
| +// ---- 6a's reads ---- |
| + |
| // ParseEvent accepts a JSON {"id","kind","object","live"} body under the |
| -// header Fake-Signature: ok. |
| +// header Fake-Signature: ok. It is not counted. |
| func (f *Fake) ParseEvent(raw []byte, header http.Header, _ time.Time) (billing.Event, error) { |
| if header.Get("Fake-Signature") != "ok" { |
| return billing.Event{}, billing.ErrBadEvent |
| @@ -66,79 +530,868 @@ func (f *Fake) ParseEvent(raw []byte, header http.Header, _ time.Time) (billing. |
| return billing.Event{ID: e.ID, Kind: billing.EventKind(e.Kind), Object: e.Object, LiveMode: e.Live}, nil |
| } |
| -// Subscription returns a copy of Subs[id], or billing.ErrNotFound. |
| -func (f *Fake) Subscription(_ context.Context, id string) (*billing.Subscription, error) { |
| +// Subscription returns a copy of Subs[id] with ProviderTime set, or |
| +// billing.ErrNotFound. |
| +func (f *Fake) Subscription(ctx context.Context, id string) (*billing.Subscription, error) { |
| f.mu.Lock() |
| hook := f.BeforeSubscription |
| f.mu.Unlock() |
| if hook != nil { |
| if err := hook(id); err != nil { |
| f.mu.Lock() |
| - f.Calls++ |
| + f.begin("Subscription") |
| + f.end() |
| f.mu.Unlock() |
| return nil, err |
| } |
| } |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - f.Calls++ |
| + f.begin("Subscription") |
| + defer f.end() |
| if f.Err != nil { |
| return nil, f.Err |
| } |
| + if f.timedOut() { |
| + return nil, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| if err := f.SubErr[id]; err != nil { |
| return nil, err |
| } |
| + d := f.respond(ctx) |
| s, ok := f.Subs[id] |
| if !ok { |
| return nil, billing.ErrNotFound |
| } |
| - c := *s |
| - c.Items = append([]billing.Item(nil), s.Items...) |
| - return &c, nil |
| + c := snapshot(s) |
| + c.ProviderTime = d |
| + return c, nil |
| } |
| -// CustomerSubscriptions returns the ids of Subs on customer, in id order. |
| -func (f *Fake) CustomerSubscriptions(_ context.Context, customer string) ([]string, error) { |
| +// CustomerSubscriptions returns the ids of Subs on customer, in id order, |
| +// at most billing.MaxCustomerSubscriptions: 6a's single capped request. |
| +func (f *Fake) CustomerSubscriptions(ctx context.Context, customer string) ([]string, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - f.Calls++ |
| + f.begin("CustomerSubscriptions") |
| + defer f.end() |
| f.CustomerCalls++ |
| if f.Err != nil { |
| return nil, f.Err |
| } |
| - var ids []string |
| - for id, s := range f.Subs { |
| - if s.Customer == customer { |
| - ids = append(ids, id) |
| - } |
| + if f.timedOut() { |
| + return nil, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| } |
| - sort.Strings(ids) |
| + f.respond(ctx) |
| + ids := sortedKeys(f.Subs, func(s *billing.Subscription) bool { return s.Customer == customer }) |
| if len(ids) > billing.MaxCustomerSubscriptions { |
| ids = ids[:billing.MaxCustomerSubscriptions] |
| } |
| return ids, nil |
| } |
| -// CheckoutSubscription returns Checkouts[id], "" when absent. |
| -func (f *Fake) CheckoutSubscription(_ context.Context, id string) (string, error) { |
| +// CheckoutSubscription returns Checkouts[id], else the session's |
| +// subscription, "" when neither names one. |
| +func (f *Fake) CheckoutSubscription(ctx context.Context, id string) (string, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - f.Calls++ |
| + f.begin("CheckoutSubscription") |
| + defer f.end() |
| if f.Err != nil { |
| return "", f.Err |
| } |
| - return f.Checkouts[id], nil |
| + if f.timedOut() { |
| + return "", fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + f.respond(ctx) |
| + if sub, ok := f.Checkouts[id]; ok { |
| + return sub, nil |
| + } |
| + if s, ok := f.Sessions[id]; ok { |
| + return s.Subscription, nil |
| + } |
| + return "", nil |
| } |
| // Check returns Err, then CheckErr. |
| -func (f *Fake) Check(context.Context, *plans.PriceBook, billing.PriceMap) error { |
| +func (f *Fake) Check(ctx context.Context, _ *plans.PriceBook, _ billing.PriceMap) error { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - f.Calls++ |
| + f.begin("Check") |
| + defer f.end() |
| if f.Err != nil { |
| return f.Err |
| } |
| + f.respond(ctx) |
| return f.CheckErr |
| } |
| +// ---- 6b's reads ---- |
| + |
| +// LiveSubscriptions pages through every subscription of customer, in id |
| +// order and in every status, and returns the live ones. |
| +func (f *Fake) LiveSubscriptions(ctx context.Context, customer string) ([]string, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + ids := sortedKeys(f.Subs, func(s *billing.Subscription) bool { return s.Customer == customer }) |
| + out := []string{} |
| + err := f.list(ctx, "LiveSubscriptions", ids, func(id string) { |
| + if s := f.Subs[id]; s != nil && s.Live { |
| + out = append(out, id) |
| + } |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// CustomerCheckouts pages through customer's sessions created after |
| +// createdAfter, in id order. |
| +func (f *Fake) CustomerCheckouts(ctx context.Context, customer string, createdAfter time.Time) ([]billing.CheckoutInfo, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + ids := sortedKeys(f.Sessions, func(s *Session) bool { return s.Customer == customer && s.Created.After(createdAfter) }) |
| + out := []billing.CheckoutInfo{} |
| + err := f.list(ctx, "CustomerCheckouts", ids, func(id string) { |
| + if s := f.Sessions[id]; s != nil { |
| + out = append(out, s.CheckoutInfo) |
| + } |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// Checkout reads one session, or billing.ErrNotFound. |
| +func (f *Fake) Checkout(ctx context.Context, sessionID string) (billing.CheckoutInfo, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("Checkout") |
| + defer f.end() |
| + if f.Err != nil { |
| + return billing.CheckoutInfo{}, f.Err |
| + } |
| + if f.timedOut() { |
| + return billing.CheckoutInfo{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + f.respond(ctx) |
| + s, ok := f.Sessions[sessionID] |
| + if !ok { |
| + return billing.CheckoutInfo{}, billing.ErrNotFound |
| + } |
| + return s.CheckoutInfo, nil |
| +} |
| + |
| +// RenewalInvoice pages through every invoice of the subscription (one |
| +// request per page under "RenewalInvoice"), picks the renewal |
| +// (ReasonCycle) whose period starts at periodStart, then pages through its |
| +// lines (under "RenewalInvoiceLines") and sums quantity per price. |
| +// billing.ErrNotFound when there is no such invoice. |
| +func (f *Fake) RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (billing.InvoiceQuantities, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.invoiceErr > 0 { |
| + f.invoiceErr-- |
| + f.begin("RenewalInvoice") |
| + f.end() |
| + return billing.InvoiceQuantities{}, ErrInjected |
| + } |
| + ids := sortedKeys(f.Invoices, func(inv *Invoice) bool { return inv.Subscription == subscription }) |
| + var match *Invoice |
| + err := f.list(ctx, "RenewalInvoice", ids, func(id string) { |
| + inv := f.Invoices[id] |
| + if match == nil && inv != nil && inv.Reason == ReasonCycle && inv.PeriodStart.Unix() == periodStart.Unix() { |
| + match = inv |
| + } |
| + }) |
| + if err != nil { |
| + return billing.InvoiceQuantities{}, err |
| + } |
| + if match == nil { |
| + return billing.InvoiceQuantities{}, billing.ErrNotFound |
| + } |
| + lineIDs := make([]string, len(match.Lines)) |
| + byLine := map[string]billing.Item{} |
| + for i, l := range match.Lines { |
| + lineIDs[i] = fmt.Sprintf("il_%s_%06d", match.ID, i) |
| + byLine[lineIDs[i]] = l |
| + } |
| + out := billing.InvoiceQuantities{Invoice: match.ID, PeriodStart: match.PeriodStart, ByPrice: map[string]int64{}} |
| + if err := f.list(ctx, "RenewalInvoiceLines", lineIDs, func(id string) { |
| + l := byLine[id] |
| + out.ByPrice[l.PriceID] += l.Quantity |
| + }); err != nil { |
| + return billing.InvoiceQuantities{}, err |
| + } |
| + return out, nil |
| +} |
| + |
| +// PortalURL opens a portal session: a write at the provider, counted in |
| +// Writes. |
| +func (f *Fake) PortalURL(ctx context.Context, customer, _, _ string) (string, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("PortalURL") |
| + defer f.end() |
| + if f.Err != nil { |
| + return "", f.Err |
| + } |
| + if f.timedOut() { |
| + return "", fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + f.respond(ctx) |
| + if customer == "" { |
| + return "", fmt.Errorf("%w: no customer", billing.ErrRefused) |
| + } |
| + return fmt.Sprintf("https://billing.example.test/portal/%s/%d", customer, f.callSeq), nil |
| +} |
| + |
| +// ClockProbe observes ProviderClock into ctx's recorder. It fails with |
| +// ProbeErr when set, or ErrNoResponse under HeaderlessTimeout, and |
| +// observes nothing when Headerless. |
| +func (f *Fake) ClockProbe(ctx context.Context) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("ClockProbe") |
| + defer f.end() |
| + if f.Err != nil { |
| + return f.Err |
| + } |
| + if f.ProbeErr != nil { |
| + return f.ProbeErr |
| + } |
| + if f.timedOut() { |
| + return fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + f.respond(ctx) |
| + return nil |
| +} |
| + |
| +// Writes is the number of write requests the Fake received: Sends and |
| +// portal sessions. Background passes must leave it unchanged. |
| +func (f *Fake) Writes() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.CallsBy["Send"] + f.CallsBy["PortalURL"] |
| +} |
| + |
| +// ---- prepared requests ---- |
| + |
| +type customerBody struct { |
| + Account string `json:"account"` |
| +} |
| + |
| +type checkoutBody struct { |
| + Customer string `json:"customer"` |
| + AccountSqid string `json:"account_sqid"` |
| + IntentID string `json:"intent_id"` |
| + Book string `json:"book"` |
| + Currency string `json:"currency"` |
| + Items []billing.CheckoutItem `json:"items"` |
| + SuccessURL string `json:"success_url"` |
| + CancelURL string `json:"cancel_url"` |
| + Coupon string `json:"coupon"` |
| + ExpiresAt int64 `json:"expires_at"` |
| +} |
| + |
| +type expireBody struct { |
| + Session string `json:"session"` |
| +} |
| + |
| +type changeBody struct { |
| + Subscription string `json:"subscription"` |
| + Items []billing.ItemChange `json:"items"` |
| + Proration billing.Proration `json:"proration"` |
| + ProrationDate int64 `json:"proration_date"` |
| +} |
| + |
| +type renewalBody struct { |
| + Subscription string `json:"subscription"` |
| + Renew bool `json:"renew"` |
| +} |
| + |
| +func unix(t time.Time) int64 { |
| + if t.IsZero() { |
| + return 0 |
| + } |
| + return t.Unix() |
| +} |
| + |
| +func fromUnix(s int64) time.Time { |
| + if s == 0 { |
| + return time.Time{} |
| + } |
| + return time.Unix(s, 0).UTC() |
| +} |
| + |
| +func pathFor(kind string, body any) string { |
| + switch b := body.(type) { |
| + case *customerBody: |
| + return "/v1/customers" |
| + case *checkoutBody: |
| + return "/v1/checkout/sessions" |
| + case *expireBody: |
| + return "/v1/checkout/sessions/" + b.Session + "/expire" |
| + case *changeBody: |
| + return "/v1/subscriptions/" + b.Subscription |
| + case *renewalBody: |
| + return "/v1/subscriptions/" + b.Subscription |
| + } |
| + return "/v1/unknown/" + kind |
| +} |
| + |
| +func prepare(kind, key string, body any) (billing.Prepared, error) { |
| + if key == "" { |
| + return billing.Prepared{}, fmt.Errorf("billingtest: %s: no idempotency key", kind) |
| + } |
| + raw, err := json.Marshal(body) |
| + if err != nil { |
| + return billing.Prepared{}, err |
| + } |
| + return billing.Prepared{Kind: kind, Method: http.MethodPost, Path: pathFor(kind, body), Body: raw, Key: key}, nil |
| +} |
| + |
| +// PrepareCustomer encodes a customer create for the account. |
| +func (f *Fake) PrepareCustomer(accountSqid, key string) (billing.Prepared, error) { |
| + if accountSqid == "" { |
| + return billing.Prepared{}, errors.New("billingtest: customer: no account") |
| + } |
| + return prepare(billing.PreparedCustomer, key, &customerBody{Account: accountSqid}) |
| +} |
| + |
| +// PrepareCheckout encodes a Checkout create. |
| +func (f *Fake) PrepareCheckout(req billing.CheckoutRequest) (billing.Prepared, error) { |
| + if req.Customer == "" || req.IntentID == "" || len(req.Items) == 0 { |
| + return billing.Prepared{}, errors.New("billingtest: checkout: customer, intent and items are required") |
| + } |
| + return prepare(billing.PreparedCheckout, req.IdempotencyKey, &checkoutBody{ |
| + Customer: req.Customer, AccountSqid: req.AccountSqid, IntentID: req.IntentID, Book: req.Book, Currency: req.Currency, |
| + Items: slices.Clone(req.Items), SuccessURL: req.SuccessURL, CancelURL: req.CancelURL, Coupon: req.Coupon, |
| + ExpiresAt: unix(req.ExpiresAt), |
| + }) |
| +} |
| + |
| +// PrepareExpire encodes a session expiry. |
| +func (f *Fake) PrepareExpire(sessionID, key string) (billing.Prepared, error) { |
| + if sessionID == "" { |
| + return billing.Prepared{}, errors.New("billingtest: expire: no session") |
| + } |
| + return prepare(billing.PreparedExpire, key, &expireBody{Session: sessionID}) |
| +} |
| + |
| +// PrepareChange encodes a subscription change. ProrationDate is kept to |
| +// the second, as the provider takes it. |
| +func (f *Fake) PrepareChange(req billing.ChangeRequest) (billing.Prepared, error) { |
| + if req.Subscription == "" || len(req.Items) == 0 { |
| + return billing.Prepared{}, errors.New("billingtest: change: subscription and items are required") |
| + } |
| + if req.Proration != billing.ProrateNone && req.Proration != billing.ProrateNow { |
| + return billing.Prepared{}, fmt.Errorf("billingtest: change: proration %q", req.Proration) |
| + } |
| + return prepare(billing.PreparedChange, req.IdempotencyKey, &changeBody{ |
| + Subscription: req.Subscription, Items: slices.Clone(req.Items), Proration: req.Proration, ProrationDate: unix(req.ProrationDate), |
| + }) |
| +} |
| + |
| +// PrepareRenewal encodes stopping (renew false) or resuming renewal. |
| +func (f *Fake) PrepareRenewal(subscription string, renew bool, key string) (billing.Prepared, error) { |
| + if subscription == "" { |
| + return billing.Prepared{}, errors.New("billingtest: renewal: no subscription") |
| + } |
| + return prepare(billing.PreparedRenewal, key, &renewalBody{Subscription: subscription, Renew: renew}) |
| +} |
| + |
| +// decode is the provider parsing a request: anything malformed, or a path |
| +// that is not the body's, is a validation error. |
| +func decode(p billing.Prepared) (any, error) { |
| + var body any |
| + switch p.Kind { |
| + case billing.PreparedCustomer: |
| + body = &customerBody{} |
| + case billing.PreparedCheckout: |
| + body = &checkoutBody{} |
| + case billing.PreparedExpire: |
| + body = &expireBody{} |
| + case billing.PreparedChange: |
| + body = &changeBody{} |
| + case billing.PreparedRenewal: |
| + body = &renewalBody{} |
| + default: |
| + return nil, fmt.Errorf("%w: unknown request kind %q", billing.ErrRefused, p.Kind) |
| + } |
| + if p.Method != http.MethodPost || p.Key == "" { |
| + return nil, fmt.Errorf("%w: not a keyed POST", billing.ErrRefused) |
| + } |
| + if err := json.Unmarshal(p.Body, body); err != nil { |
| + return nil, fmt.Errorf("%w: body does not parse", billing.ErrRefused) |
| + } |
| + if pathFor(p.Kind, body) != p.Path { |
| + return nil, fmt.Errorf("%w: path %s does not match the body", billing.ErrRefused, p.Path) |
| + } |
| + return body, nil |
| +} |
| + |
| +// validate is the provider's parameter validation, before execution: a |
| +// refusal here is not stored under the key (fact 2). |
| +func (f *Fake) validate(body any) error { |
| + if b, ok := body.(*checkoutBody); ok { |
| + exp := fromUnix(b.ExpiresAt) |
| + now := f.ProviderClock |
| + if exp.Before(now.Add(30*time.Minute)) || exp.After(now.Add(24*time.Hour)) { |
| + return fmt.Errorf("%w: expires_at must be 30 minutes to 24 hours ahead", billing.ErrRefused) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// Send is one request: p's bytes under p's key, answered as the provider |
| +// would, given the knobs. See the package doc and each knob. |
| +func (f *Fake) Send(ctx context.Context, p billing.Prepared) (billing.Result, error) { |
| + f.mu.Lock() |
| + if f.CrashBeforeSend { |
| + f.CrashBeforeSend = false |
| + f.mu.Unlock() |
| + return billing.Result{}, ErrCrash |
| + } |
| + hook := f.BeforeSend |
| + f.mu.Unlock() |
| + var hookErr error |
| + if hook != nil { |
| + hookErr = hook(p) |
| + } |
| + |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.begin("Send") |
| + defer f.end() |
| + f.Sent = append(f.Sent, billing.Prepared{Kind: p.Kind, Method: p.Method, Path: p.Path, Body: bytes.Clone(p.Body), Key: p.Key}) |
| + var r billing.Result |
| + err := hookErr |
| + if err == nil { |
| + r, err = f.send(ctx, p) |
| + } |
| + if f.CrashAfterSend { |
| + f.CrashAfterSend = false |
| + return billing.Result{}, ErrCrash |
| + } |
| + return r, err |
| +} |
| + |
| +func (f *Fake) send(ctx context.Context, p billing.Prepared) (billing.Result, error) { |
| + if f.Err != nil { |
| + return billing.Result{}, f.Err |
| + } |
| + if f.timedOut() { |
| + return billing.Result{}, fmt.Errorf("%w: timed out before headers", billing.ErrNoResponse) |
| + } |
| + if f.FailBeforeDelivery > 0 { |
| + f.FailBeforeDelivery-- |
| + return billing.Result{}, fmt.Errorf("%w: lost before delivery", billing.ErrNoResponse) |
| + } |
| + if f.RateLimit > 0 { |
| + f.RateLimit-- |
| + return billing.Result{ProviderTime: f.respond(ctx)}, fmt.Errorf("%w: 429", billing.ErrNotExecuted) |
| + } |
| + if e, ok := f.keys[p.Key]; ok { |
| + d := f.respond(ctx) |
| + switch { |
| + case !e.same(p): |
| + return billing.Result{ProviderTime: d}, fmt.Errorf("%w: %w", billing.ErrRefused, ErrKeyReused) |
| + case e.executing: |
| + return billing.Result{ProviderTime: d}, fmt.Errorf("%w: 409 on key %s", billing.ErrInFlight, p.Key) |
| + } |
| + r := cloneResult(e.result) |
| + r.Replayed, r.ProviderTime = true, d |
| + if r.Subscription != nil { |
| + r.Subscription.ProviderTime = d |
| + } |
| + return r, e.err |
| + } |
| + if f.inFlight > 0 { |
| + f.inFlight-- |
| + return billing.Result{ProviderTime: f.respond(ctx)}, fmt.Errorf("%w: 409", billing.ErrInFlight) |
| + } |
| + body, err := decode(p) |
| + if err == nil { |
| + err = f.validate(body) |
| + } |
| + if err != nil { |
| + return billing.Result{ProviderTime: f.respond(ctx)}, err |
| + } |
| + |
| + // Execution begins: from here the answer is stored under the key. |
| + e := &keyEntry{method: p.Method, path: p.Path, body: bytes.Clone(p.Body), storedAt: f.ProviderClock} |
| + f.keys[p.Key] = e |
| + if f.held[p.Key] { |
| + delete(f.held, p.Key) |
| + e.executing = true |
| + f.late = append(f.late, &lateSend{p: p, body: body, afterRenewal: true}) |
| + return billing.Result{}, fmt.Errorf("%w: timed out", billing.ErrNoResponse) |
| + } |
| + if f.lateArmed { |
| + f.lateArmed = false |
| + e.executing = true |
| + f.late = append(f.late, &lateSend{p: p, body: body, dueSeq: f.callSeq + f.lateAfter}) |
| + return billing.Result{}, fmt.Errorf("%w: timed out", billing.ErrNoResponse) |
| + } |
| + if f.Cached500Before { |
| + f.Cached500Before = false |
| + e.err = fmt.Errorf("%w: 500", billing.ErrIndeterminate) |
| + return billing.Result{ProviderTime: f.respond(ctx)}, e.err |
| + } |
| + r, err := f.execute(body) |
| + e.result, e.err = cloneResult(r), err |
| + if f.Cached500After { |
| + f.Cached500After = false |
| + e.result, e.err = billing.Result{}, fmt.Errorf("%w: 500", billing.ErrIndeterminate) |
| + return billing.Result{ProviderTime: f.respond(ctx)}, e.err |
| + } |
| + if f.LoseNextResponse { |
| + f.LoseNextResponse = false |
| + return billing.Result{}, fmt.Errorf("%w: response lost", billing.ErrNoResponse) |
| + } |
| + d := f.respond(ctx) |
| + r.ProviderTime = d |
| + if r.Subscription != nil { |
| + r.Subscription.ProviderTime = d |
| + } |
| + return r, err |
| +} |
| + |
| +// land executes a late request and stores its answer under its key (the |
| +// response itself was lost long ago). |
| +func (f *Fake) land(l *lateSend) { |
| + r, err := f.execute(l.body) |
| + if e, ok := f.keys[l.p.Key]; ok && e.executing { |
| + e.executing, e.result, e.err, e.storedAt = false, cloneResult(r), err, f.ProviderClock |
| + } |
| +} |
| + |
| +// execute applies a parsed request to the provider's state. |
| +func (f *Fake) execute(body any) (billing.Result, error) { |
| + switch b := body.(type) { |
| + case *customerBody: |
| + id := f.nextID("cus") |
| + f.Customers[id] = &Customer{ID: id, Account: b.Account} |
| + return billing.Result{Customer: id}, nil |
| + case *checkoutBody: |
| + id := f.nextID("cs") |
| + s := &Session{ |
| + CheckoutInfo: billing.CheckoutInfo{ID: id, URL: "https://checkout.example.test/c/" + id, Customer: b.Customer, |
| + IntentID: b.IntentID, State: billing.CheckoutOpen, ExpiresAt: fromUnix(b.ExpiresAt)}, |
| + Created: f.ProviderClock, |
| + Request: billing.CheckoutRequest{Customer: b.Customer, AccountSqid: b.AccountSqid, IntentID: b.IntentID, Book: b.Book, |
| + Currency: b.Currency, Items: slices.Clone(b.Items), SuccessURL: b.SuccessURL, CancelURL: b.CancelURL, |
| + Coupon: b.Coupon, ExpiresAt: fromUnix(b.ExpiresAt)}, |
| + } |
| + f.Sessions[id] = s |
| + info := s.CheckoutInfo |
| + return billing.Result{Checkout: &info}, nil |
| + case *expireBody: |
| + s, ok := f.Sessions[b.Session] |
| + if !ok { |
| + return billing.Result{}, fmt.Errorf("%w: no such session", billing.ErrRefused) |
| + } |
| + if s.State != billing.CheckoutOpen { |
| + return billing.Result{}, fmt.Errorf("%w: only an open session can be expired", billing.ErrRefused) |
| + } |
| + s.State = billing.CheckoutExpired |
| + info := s.CheckoutInfo |
| + return billing.Result{Checkout: &info}, nil |
| + case *changeBody: |
| + return f.applyChange(b) |
| + case *renewalBody: |
| + s, ok := f.Subs[b.Subscription] |
| + if !ok { |
| + return billing.Result{}, fmt.Errorf("%w: no such subscription", billing.ErrRefused) |
| + } |
| + if !s.Live { |
| + return billing.Result{}, fmt.Errorf("%w: the subscription has ended", billing.ErrRefused) |
| + } |
| + s.CancelAtPeriodEnd = !b.Renew |
| + return billing.Result{Subscription: snapshot(s)}, nil |
| + } |
| + return billing.Result{}, fmt.Errorf("%w: unknown request", billing.ErrRefused) |
| +} |
| + |
| +// applyChange is a subscription update. ProrateNone applies at once. |
| +// ProrateNow is charged first: DeclineHard refuses it, FailPayment leaves |
| +// it pending, otherwise it applies and writes a proration invoice. Either |
| +// way an earlier pending update is discarded (the Fake's choice; the |
| +// console never changes a subscription with an operation outstanding). |
| +func (f *Fake) applyChange(b *changeBody) (billing.Result, error) { |
| + s, ok := f.Subs[b.Subscription] |
| + if !ok { |
| + return billing.Result{}, fmt.Errorf("%w: no such subscription", billing.ErrRefused) |
| + } |
| + if !s.Live { |
| + return billing.Result{}, fmt.Errorf("%w: the subscription has ended", billing.ErrRefused) |
| + } |
| + items := slices.Clone(s.Items) |
| + for _, c := range b.Items { |
| + if c.ItemID == "" { |
| + if c.PriceID == "" || c.Delete { |
| + return billing.Result{}, fmt.Errorf("%w: a new item needs a price", billing.ErrRefused) |
| + } |
| + if slices.ContainsFunc(items, func(it billing.Item) bool { return it.PriceID == c.PriceID }) { |
| + return billing.Result{}, fmt.Errorf("%w: price %s is already on the subscription", billing.ErrRefused, c.PriceID) |
| + } |
| + items = append(items, billing.Item{ItemID: f.nextID("si"), PriceID: c.PriceID, Quantity: c.Quantity, Currency: s.Currency}) |
| + continue |
| + } |
| + i := slices.IndexFunc(items, func(it billing.Item) bool { return it.ItemID == c.ItemID }) |
| + if i < 0 { |
| + return billing.Result{}, fmt.Errorf("%w: no item %s", billing.ErrRefused, c.ItemID) |
| + } |
| + if c.Delete { |
| + items = slices.Delete(items, i, i+1) |
| + continue |
| + } |
| + if c.PriceID != "" { |
| + items[i].PriceID = c.PriceID |
| + } |
| + items[i].Quantity = c.Quantity |
| + } |
| + if b.Proration == billing.ProrateNow { |
| + if f.DeclineHard > 0 { |
| + f.DeclineHard-- |
| + return billing.Result{}, fmt.Errorf("%w: card declined", billing.ErrPaymentFailed) |
| + } |
| + if f.FailPayment > 0 { |
| + f.FailPayment-- |
| + f.pending[s.ID] = items |
| + s.PendingUpdate, s.PendingExpires, s.Collecting = true, f.pendingExpiry(s), true |
| + return billing.Result{Subscription: snapshot(s)}, nil |
| + } |
| + f.dropPending(s) |
| + s.Items = items |
| + f.writeInvoice(s, ReasonUpdate, f.ProviderClock) |
| + return billing.Result{Subscription: snapshot(s)}, nil |
| + } |
| + f.dropPending(s) |
| + s.Items = items |
| + return billing.Result{Subscription: snapshot(s)}, nil |
| +} |
| + |
| +// pendingExpiry is fact 8: the period end when that is within 23 hours, |
| +// otherwise 23 hours after the update. |
| +func (f *Fake) pendingExpiry(s *billing.Subscription) time.Time { |
| + now := f.ProviderClock |
| + limit := now.Add(23 * time.Hour) |
| + if s.PeriodEnd.After(now) && !s.PeriodEnd.After(limit) { |
| + return s.PeriodEnd |
| + } |
| + return limit |
| +} |
| + |
| +func (f *Fake) writeInvoice(s *billing.Subscription, reason string, periodStart time.Time) string { |
| + id := f.nextID("in") |
| + lines := make([]billing.Item, len(s.Items)) |
| + for i, it := range s.Items { |
| + lines[i] = billing.Item{PriceID: it.PriceID, Quantity: it.Quantity, Currency: it.Currency} |
| + } |
| + f.Invoices[id] = &Invoice{ID: id, Subscription: s.ID, Reason: reason, PeriodStart: periodStart, Lines: lines} |
| + return id |
| +} |
| + |
| +// ---- provider-side events and outcome knobs ---- |
| + |
| +// InFlight answers the next n Sends of a key not yet stored with a 409: |
| +// billing.ErrInFlight, nothing executed or stored (fact 3: another request |
| +// with the key is executing). The next Send after them executes. |
| +func (f *Fake) InFlight(n int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.inFlight = n |
| +} |
| + |
| +// CompleteLater makes the next Send that executes return |
| +// billing.ErrNoResponse without applying, and land after n further |
| +// requests of any kind have been answered (0: as soon as the Send itself |
| +// is answered). Until it lands, a resend under its key is a 409, and reads |
| +// do not show it: a negative read is not final. |
| +func (f *Fake) CompleteLater(n int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.lateArmed, f.lateAfter = true, n |
| +} |
| + |
| +// ApplyAfterRenewal holds the Send under key (sent later): it returns |
| +// billing.ErrNoResponse, resends are a 409, and it applies at the next |
| +// Renew, after the renewal invoice is written. Risk R1: a request that |
| +// first applies after a renewal. |
| +func (f *Fake) ApplyAfterRenewal(key string) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + f.held[key] = true |
| +} |
| + |
| +// PruneKeysOlderThan forgets every stored key older than d by the provider |
| +// clock (fact 6): the same bytes then execute anew, and other bytes are no |
| +// longer an idempotency error. |
| +func (f *Fake) PruneKeysOlderThan(d time.Duration) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + cutoff := f.ProviderClock.Add(-d) |
| + for k, e := range f.keys { |
| + if !e.executing && e.storedAt.Before(cutoff) { |
| + delete(f.keys, k) |
| + } |
| + } |
| +} |
| + |
| +// InvoiceReadFails fails the next n RenewalInvoice calls at their first |
| +// request with ErrInjected (each counted under "RenewalInvoice"). |
| +func (f *Fake) InvoiceReadFails(n int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.invoiceErr = n |
| +} |
| + |
| +// Renew is the subscription reaching its period end. A renewing |
| +// subscription moves its period a year on, keeps its items, drops any |
| +// pending update, and gets a renewal invoice (ReasonCycle, PeriodStart the |
| +// old period end) of its items' quantities. One set to cancel at period |
| +// end ends instead. Then every request held by ApplyAfterRenewal applies. |
| +// Renew is not a request: it is not counted. |
| +func (f *Fake) Renew(subscription string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + f.settle() |
| + s, ok := f.Subs[subscription] |
| + if !ok || !s.Live { |
| + return fmt.Errorf("billingtest: %s is not a live subscription", subscription) |
| + } |
| + f.dropPending(s) |
| + if s.CancelAtPeriodEnd { |
| + s.Live, s.State, s.ProviderStatus = false, billing.StateEnded, "canceled" |
| + } else { |
| + old := s.PeriodEnd |
| + s.PeriodEnd = old.AddDate(1, 0, 0) |
| + f.writeInvoice(s, ReasonCycle, old) |
| + } |
| + var keep []*lateSend |
| + for _, l := range f.late { |
| + if l.afterRenewal { |
| + f.land(l) |
| + continue |
| + } |
| + keep = append(keep, l) |
| + } |
| + f.late = keep |
| + return nil |
| +} |
| + |
| +// PayPending is the buyer paying a pending update later: its items apply |
| +// and a proration invoice is written. |
| +func (f *Fake) PayPending(subscription string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + f.settle() |
| + s, ok := f.Subs[subscription] |
| + if !ok || !s.PendingUpdate { |
| + return fmt.Errorf("billingtest: %s has no pending update", subscription) |
| + } |
| + if items, ok := f.pending[subscription]; ok { |
| + s.Items = items |
| + } |
| + f.dropPending(s) |
| + f.writeInvoice(s, ReasonUpdate, f.ProviderClock) |
| + return nil |
| +} |
| + |
| +// ExpirePending drops a pending update now, as the provider does at |
| +// PendingExpires: nothing applied. |
| +func (f *Fake) ExpirePending(subscription string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + s, ok := f.Subs[subscription] |
| + if !ok || !s.PendingUpdate { |
| + return fmt.Errorf("billingtest: %s has no pending update", subscription) |
| + } |
| + f.dropPending(s) |
| + return nil |
| +} |
| + |
| +// CompleteCheckout is the buyer paying an open session: it makes a live, |
| +// paid subscription of the session's items (period ending a year from the |
| +// provider clock, metadata naming the account), marks the session |
| +// complete, and returns the subscription's id. A session that is not open |
| +// (expired, completed, or past its expires_at) refuses. |
| +func (f *Fake) CompleteCheckout(sessionID string) (string, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + f.settle() |
| + s, ok := f.Sessions[sessionID] |
| + if !ok || s.State != billing.CheckoutOpen { |
| + return "", fmt.Errorf("billingtest: session %s is not open", sessionID) |
| + } |
| + sub := &billing.Subscription{ |
| + ID: f.nextID("sub"), Customer: s.Customer, Account: s.Request.AccountSqid, ProviderStatus: "active", |
| + State: billing.StatePaid, Live: true, Currency: s.Request.Currency, PeriodEnd: f.ProviderClock.AddDate(1, 0, 0), |
| + ItemsComplete: true, |
| + } |
| + for _, it := range s.Request.Items { |
| + sub.Items = append(sub.Items, billing.Item{ItemID: f.nextID("si"), PriceID: it.PriceID, Quantity: it.Quantity, Currency: s.Request.Currency}) |
| + } |
| + f.Subs[sub.ID] = sub |
| + s.State, s.Subscription = billing.CheckoutComplete, sub.ID |
| + f.Checkouts[sessionID] = sub.ID |
| + f.writeInvoice(sub, ReasonCreate, f.ProviderClock) |
| + return sub.ID, nil |
| +} |
| + |
| +// ExpireCheckout expires an open session at the provider (not a console |
| +// request). |
| +func (f *Fake) ExpireCheckout(sessionID string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + s, ok := f.Sessions[sessionID] |
| + if !ok || s.State != billing.CheckoutOpen { |
| + return fmt.Errorf("billingtest: session %s is not open", sessionID) |
| + } |
| + s.State = billing.CheckoutExpired |
| + return nil |
| +} |
| + |
| +// AddSession seeds a session, giving it an id, URL and creation time when |
| +// they are empty. It returns the id. |
| +func (f *Fake) AddSession(s *Session) string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + if s.ID == "" { |
| + s.ID = f.nextID("cs") |
| + } |
| + if s.URL == "" { |
| + s.URL = "https://checkout.example.test/c/" + s.ID |
| + } |
| + if s.Created.IsZero() { |
| + s.Created = f.ProviderClock |
| + } |
| + f.Sessions[s.ID] = s |
| + return s.ID |
| +} |
| + |
| +// AddInvoice seeds an invoice, giving it an id when empty. It returns the |
| +// id. |
| +func (f *Fake) AddInvoice(inv *Invoice) string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.init() |
| + if inv.ID == "" { |
| + inv.ID = f.nextID("in") |
| + } |
| + f.Invoices[inv.ID] = inv |
| + return inv.ID |
| +} |
| + |
| var _ billing.Provider = (*Fake)(nil) |
diff --git a/internal/billing/billingtest/fake_test.go b/internal/billing/billingtest/fake_test.go| new file mode 100644 |
| index 000000000..cae636738 |
| --- /dev/null |
| +++ b/internal/billing/billingtest/fake_test.go |
| @@ -0,0 +1,903 @@ |
| +package billingtest |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +var t0 = time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC) |
| + |
| +func newFake(t *testing.T) *Fake { |
| + t.Helper() |
| + f := New() |
| + f.SetProviderClock(t0) |
| + return f |
| +} |
| + |
| +// seedSub puts a live, paid subscription with a plan item and two apps |
| +// packs on the Fake, its period ending six months after t0. |
| +func seedSub(f *Fake, id, customer string) *billing.Subscription { |
| + s := &billing.Subscription{ |
| + ID: id, Customer: customer, Account: "bab", ProviderStatus: "active", |
| + State: billing.StatePaid, Live: true, Currency: "usd", PeriodEnd: t0.AddDate(0, 6, 0), |
| + ItemsComplete: true, |
| + Items: []billing.Item{ |
| + {ItemID: "si_plan", PriceID: "price_plan", Quantity: 1, Currency: "usd"}, |
| + {ItemID: "si_apps", PriceID: "price_apps", Quantity: 2, Currency: "usd"}, |
| + }, |
| + } |
| + f.Subs[id] = s |
| + return s |
| +} |
| + |
| +func prepareApps(t *testing.T, f *Fake, sub string, qty int64, pr billing.Proration, key string) billing.Prepared { |
| + t.Helper() |
| + p, err := f.PrepareChange(billing.ChangeRequest{ |
| + Subscription: sub, Proration: pr, ProrationDate: t0, IdempotencyKey: key, |
| + Items: []billing.ItemChange{{ItemID: "si_apps", Quantity: qty}}, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| +} |
| + |
| +func appsQty(t *testing.T, f *Fake, sub string) int64 { |
| + t.Helper() |
| + f.Lock() |
| + defer f.Unlock() |
| + for _, it := range f.Subs[sub].Items { |
| + if it.ItemID == "si_apps" { |
| + return it.Quantity |
| + } |
| + } |
| + t.Fatalf("%s has no apps item", sub) |
| + return 0 |
| +} |
| + |
| +func resultApps(t *testing.T, r billing.Result) int64 { |
| + t.Helper() |
| + if r.Subscription == nil { |
| + t.Fatal("result has no subscription") |
| + } |
| + for _, it := range r.Subscription.Items { |
| + if it.ItemID == "si_apps" { |
| + return it.Quantity |
| + } |
| + } |
| + t.Fatal("result has no apps item") |
| + return 0 |
| +} |
| + |
| +func TestFakePreparedIdempotency(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + again := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + if !bytes.Equal(p.Body, again.Body) || p.Path != again.Path || p.Method != again.Method || p.Key != "op:1" || p.Kind != billing.PreparedChange { |
| + t.Fatalf("Prepare is not canonical: %+v vs %+v", p, again) |
| + } |
| + |
| + r, err := f.Send(ctx, p) |
| + if err != nil || r.Replayed || resultApps(t, r) != 3 || !r.ProviderTime.Equal(t0) { |
| + t.Fatalf("first send = %+v, %v", r, err) |
| + } |
| + // Something else moves the item; a resend replays the stored answer and |
| + // applies nothing. |
| + f.Lock() |
| + f.Subs["sub_1"].Items[1].Quantity = 5 |
| + f.Unlock() |
| + r, err = f.Send(ctx, p) |
| + if err != nil || !r.Replayed || resultApps(t, r) != 3 { |
| + t.Fatalf("resend = %+v, %v", r, err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 5 { |
| + t.Fatalf("a replay re-applied: apps = %d", got) |
| + } |
| + |
| + // The same key with other bytes is an idempotency error, nothing applied. |
| + other := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:1") |
| + if _, err := f.Send(ctx, other); !errors.Is(err, billing.ErrRefused) || !errors.Is(err, ErrKeyReused) { |
| + t.Fatalf("other body under the key: err = %v", err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 5 { |
| + t.Fatalf("a mismatch applied: apps = %d", got) |
| + } |
| + if f.CallsBy["Send"] != 3 || len(f.Sent) != 3 || !bytes.Equal(f.Sent[2].Body, other.Body) { |
| + t.Fatalf("CallsBy = %v, Sent = %d", f.CallsBy, len(f.Sent)) |
| + } |
| + |
| + if _, err := f.PrepareChange(billing.ChangeRequest{Subscription: "sub_1", Proration: billing.ProrateNone, |
| + Items: []billing.ItemChange{{ItemID: "si_apps", Quantity: 1}}}); err == nil { |
| + t.Error("a change with no key was prepared") |
| + } |
| + if _, err := f.PrepareChange(billing.ChangeRequest{Subscription: "sub_1", Proration: "sometime", IdempotencyKey: "op:2", |
| + Items: []billing.ItemChange{{ItemID: "si_apps", Quantity: 1}}}); err == nil { |
| + t.Error("a change with an unknown proration was prepared") |
| + } |
| +} |
| + |
| +func TestFakeCompleteLater(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + rec := f.Recorder() |
| + ctx := billing.WithClock(context.Background(), rec) |
| + |
| + // The write lands after one more call: the read straight after the |
| + // uncertain return is negative, the next is positive. |
| + f.CompleteLater(1) |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("send: err = %v, want ErrNoResponse", err) |
| + } |
| + if _, err := rec.Now(); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Fatalf("a lost response gave a Date: %v", err) |
| + } |
| + s, err := f.Subscription(ctx, "sub_1") |
| + if err != nil || s.Items[1].Quantity != 2 { |
| + t.Fatalf("first read = %+v, %v; want the old quantity", s, err) |
| + } |
| + if s, _ := f.Subscription(ctx, "sub_1"); s.Items[1].Quantity != 3 { |
| + t.Fatalf("second read: apps = %d, want 3", s.Items[1].Quantity) |
| + } |
| + r, err := f.Send(ctx, p) |
| + if err != nil || !r.Replayed { |
| + t.Fatalf("resend after landing = %+v, %v", r, err) |
| + } |
| + |
| + // While it is still executing, a resend under the key is a 409. |
| + f.CompleteLater(2) |
| + p2 := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:2") |
| + if _, err := f.Send(ctx, p2); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("send 2: %v", err) |
| + } |
| + if _, err := f.Send(ctx, p2); !errors.Is(err, billing.ErrInFlight) { |
| + t.Fatalf("resend while executing: err = %v, want ErrInFlight", err) |
| + } |
| + if s, _ := f.Subscription(ctx, "sub_1"); s.Items[1].Quantity != 3 { |
| + t.Fatalf("landed early: apps = %d", s.Items[1].Quantity) |
| + } |
| + if s, _ := f.Subscription(ctx, "sub_1"); s.Items[1].Quantity != 4 { |
| + t.Fatalf("never landed: apps = %d", s.Items[1].Quantity) |
| + } |
| + if r, err := f.Send(ctx, p2); err != nil || !r.Replayed { |
| + t.Fatalf("resend 2 = %+v, %v", r, err) |
| + } |
| +} |
| + |
| +func TestFakeCached500(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + rec := f.Recorder() |
| + ctx := billing.WithClock(context.Background(), rec) |
| + |
| + f.Cached500Before = true |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrIndeterminate) { |
| + t.Fatalf("500 before: err = %v", err) |
| + } |
| + if _, err := rec.Now(); err != nil { |
| + t.Fatalf("a 500 is a response with a Date: %v", err) |
| + } |
| + r, err := f.Send(ctx, p) |
| + if !errors.Is(err, billing.ErrIndeterminate) || !r.Replayed { |
| + t.Fatalf("resend after a cached 500 = %+v, %v; want the 500 again, replayed", r, err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 2 { |
| + t.Fatalf("500 before applied: apps = %d", got) |
| + } |
| + if f.Cached500Before { |
| + t.Error("Cached500Before is one-shot") |
| + } |
| + |
| + f.Cached500After = true |
| + p2 := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:2") |
| + if _, err := f.Send(ctx, p2); !errors.Is(err, billing.ErrIndeterminate) { |
| + t.Fatalf("500 after: err = %v", err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 4 { |
| + t.Fatalf("500 after did not apply: apps = %d", got) |
| + } |
| + if r, err := f.Send(ctx, p2); !errors.Is(err, billing.ErrIndeterminate) || !r.Replayed { |
| + t.Fatalf("resend after 500 after = %+v, %v", r, err) |
| + } |
| +} |
| + |
| +func TestFakeInFlightAndRateLimit(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + rec := f.Recorder() |
| + ctx := billing.WithClock(context.Background(), rec) |
| + |
| + f.RateLimit = 2 |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + for i := range 2 { |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrNotExecuted) { |
| + t.Fatalf("429 %d: err = %v", i, err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 2 { |
| + t.Fatalf("a 429 applied: apps = %d", got) |
| + } |
| + } |
| + if _, err := rec.Now(); err != nil { |
| + t.Fatalf("a 429 carries a Date: %v", err) |
| + } |
| + if r, err := f.Send(ctx, p); err != nil || r.Replayed || resultApps(t, r) != 3 { |
| + t.Fatalf("after the 429s = %+v, %v; want a first execution", r, err) |
| + } |
| + |
| + f.InFlight(1) |
| + p2 := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:2") |
| + if _, err := f.Send(ctx, p2); !errors.Is(err, billing.ErrInFlight) { |
| + t.Fatalf("409: err = %v", err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 3 { |
| + t.Fatalf("a 409 applied: apps = %d", got) |
| + } |
| + if r, err := f.Send(ctx, p2); err != nil || r.Replayed || resultApps(t, r) != 4 { |
| + t.Fatalf("after the 409 = %+v, %v", r, err) |
| + } |
| + if f.CallsBy["Send"] != 5 { |
| + t.Fatalf("CallsBy[Send] = %d, want 5", f.CallsBy["Send"]) |
| + } |
| +} |
| + |
| +func TestFakePrune(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + if _, err := f.Send(ctx, p); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.Lock() |
| + f.Subs["sub_1"].Items[1].Quantity = 5 |
| + f.Unlock() |
| + |
| + f.AdvanceProvider(23 * time.Hour) |
| + f.PruneKeysOlderThan(24 * time.Hour) |
| + if r, err := f.Send(ctx, p); err != nil || !r.Replayed || appsQty(t, f, "sub_1") != 5 { |
| + t.Fatalf("inside the window: %+v, %v, apps %d", r, err, appsQty(t, f, "sub_1")) |
| + } |
| + |
| + // Past 24 h the key may be gone: the same bytes execute anew. |
| + f.AdvanceProvider(2 * time.Hour) |
| + f.PruneKeysOlderThan(24 * time.Hour) |
| + if r, err := f.Send(ctx, p); err != nil || r.Replayed || appsQty(t, f, "sub_1") != 3 { |
| + t.Fatalf("after pruning: %+v, %v, apps %d; want a new execution", r, err, appsQty(t, f, "sub_1")) |
| + } |
| + // And a pruned key takes other bytes without complaint. |
| + f.AdvanceProvider(25 * time.Hour) |
| + f.PruneKeysOlderThan(24 * time.Hour) |
| + if _, err := f.Send(ctx, prepareApps(t, f, "sub_1", 6, billing.ProrateNone, "op:1")); err != nil { |
| + t.Fatalf("other bytes under a pruned key: %v", err) |
| + } |
| +} |
| + |
| +func TestFakePendingPayLaterExpire(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + |
| + // A declined charge leaves a pending update: nothing granted. |
| + f.FailPayment = 1 |
| + r, err := f.Send(ctx, prepareApps(t, f, "sub_1", 3, billing.ProrateNow, "op:1")) |
| + if err != nil { |
| + t.Fatalf("soft decline: %v", err) |
| + } |
| + s := r.Subscription |
| + if !s.PendingUpdate || !s.Collecting || resultApps(t, r) != 2 || !s.PendingExpires.Equal(t0.Add(23*time.Hour)) { |
| + t.Fatalf("pending = %+v", s) |
| + } |
| + if got, _ := f.Subscription(ctx, "sub_1"); !got.PendingUpdate { |
| + t.Fatal("a read does not show the pending update") |
| + } |
| + |
| + // Paid later: applied. |
| + if err := f.PayPending("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := f.Subscription(ctx, "sub_1"); got.PendingUpdate || got.Collecting || got.Items[1].Quantity != 3 { |
| + t.Fatalf("after paying = %+v", got) |
| + } |
| + |
| + // Expired: dropped. |
| + f.FailPayment = 1 |
| + if _, err := f.Send(ctx, prepareApps(t, f, "sub_1", 4, billing.ProrateNow, "op:2")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.ExpirePending("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := f.Subscription(ctx, "sub_1"); got.PendingUpdate || got.Items[1].Quantity != 3 { |
| + t.Fatalf("after expiry = %+v", got) |
| + } |
| + |
| + // It expires on its own once provider time passes PendingExpires. |
| + f.FailPayment = 1 |
| + if _, err := f.Send(ctx, prepareApps(t, f, "sub_1", 5, billing.ProrateNow, "op:3")); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.AdvanceProvider(23 * time.Hour) |
| + if got, _ := f.Subscription(ctx, "sub_1"); got.PendingUpdate || got.Items[1].Quantity != 3 { |
| + t.Fatalf("after 23 h = %+v", got) |
| + } |
| + if err := f.PayPending("sub_1"); err == nil { |
| + t.Error("paid an expired pending update") |
| + } |
| + |
| + // Within 23 hours of the period end, it expires at the period end. |
| + s2 := seedSub(f, "sub_2", "cus_2") |
| + f.Lock() |
| + s2.PeriodEnd = f.ProviderClock.Add(5 * time.Hour) |
| + f.FailPayment = 1 |
| + f.Unlock() |
| + r, err = f.Send(ctx, prepareApps(t, f, "sub_2", 3, billing.ProrateNow, "op:4")) |
| + if err != nil || !r.Subscription.PendingExpires.Equal(s2.PeriodEnd) { |
| + t.Fatalf("near the period end = %+v, %v", r.Subscription, err) |
| + } |
| + |
| + // A hard decline is definite: nothing applied, and the answer is stored. |
| + f.DeclineHard = 1 |
| + p := prepareApps(t, f, "sub_1", 6, billing.ProrateNow, "op:5") |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrPaymentFailed) { |
| + t.Fatalf("hard decline: err = %v", err) |
| + } |
| + if r, err := f.Send(ctx, p); !errors.Is(err, billing.ErrPaymentFailed) || !r.Replayed { |
| + t.Fatalf("resend of a decline = %+v, %v", r, err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 3 { |
| + t.Fatalf("a decline applied: apps = %d", got) |
| + } |
| + |
| + // A paid charge applies at once and writes a proration invoice. |
| + r, err = f.Send(ctx, prepareApps(t, f, "sub_1", 7, billing.ProrateNow, "op:6")) |
| + if err != nil || resultApps(t, r) != 7 || r.Subscription.PendingUpdate { |
| + t.Fatalf("paid charge = %+v, %v", r, err) |
| + } |
| +} |
| + |
| +func TestFakeFailBeforeDeliveryAndLostResponse(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + rec := f.Recorder() |
| + ctx := billing.WithClock(context.Background(), rec) |
| + |
| + f.FailBeforeDelivery = 1 |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("before delivery: err = %v", err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 2 { |
| + t.Fatalf("an undelivered request applied: apps = %d", got) |
| + } |
| + if _, err := rec.Now(); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Fatalf("no response gave a Date: %v", err) |
| + } |
| + if r, err := f.Send(ctx, p); err != nil || r.Replayed { |
| + t.Fatalf("resend after an undelivered request = %+v, %v; want a first execution", r, err) |
| + } |
| + |
| + f.LoseNextResponse = true |
| + p2 := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:2") |
| + if _, err := f.Send(ctx, p2); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("lost response: err = %v", err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 4 { |
| + t.Fatalf("a lost response did not apply: apps = %d", got) |
| + } |
| + if r, err := f.Send(ctx, p2); err != nil || !r.Replayed { |
| + t.Fatalf("resend after a lost response = %+v, %v", r, err) |
| + } |
| +} |
| + |
| +func TestFakeProviderClock(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + console := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC) |
| + f.SetConsoleClock(console) |
| + rec := f.Recorder() |
| + ctx := billing.WithClock(context.Background(), rec) |
| + |
| + s, err := f.Subscription(ctx, "sub_1") |
| + if err != nil || !s.ProviderTime.Equal(t0) { |
| + t.Fatalf("read = %+v, %v", s, err) |
| + } |
| + f.AdvanceMonotonic(30 * time.Second) |
| + if now, err := rec.Now(); err != nil || !now.Equal(t0.Add(30*time.Second)) { |
| + t.Fatalf("Now = %v, %v", now, err) |
| + } |
| + f.AdvanceMonotonic(31 * time.Second) |
| + if _, err := rec.Now(); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Fatalf("stale: %v", err) |
| + } |
| + // The three clocks move apart. |
| + f.AdvanceProvider(time.Hour) |
| + if !f.ConsoleNow().Equal(console) || f.Monotonic() != 61*time.Second { |
| + t.Fatalf("console %v mono %v moved with the provider", f.ConsoleNow(), f.Monotonic()) |
| + } |
| + f.Elapse(10 * time.Second) |
| + if !f.ConsoleNow().Equal(console.Add(10*time.Second)) || f.Monotonic() != 71*time.Second || |
| + !f.ProviderClock.Equal(t0.Add(time.Hour+10*time.Second)) { |
| + t.Fatal("Elapse moves all three clocks") |
| + } |
| + |
| + // The probe observes the clock and is counted. |
| + if err := f.ClockProbe(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now, err := rec.Now(); err != nil || !now.Equal(f.ProviderClock) { |
| + t.Fatalf("after the probe: %v, %v", now, err) |
| + } |
| + |
| + // Headerless: answers, but no Date and no ProviderTime. |
| + rec2 := f.Recorder() |
| + ctx2 := billing.WithClock(context.Background(), rec2) |
| + f.Headerless = true |
| + if err := f.ClockProbe(ctx2); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, _ = f.Subscription(ctx2, "sub_1") |
| + r, _ := f.Send(ctx2, prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1")) |
| + if _, err := rec2.Now(); !errors.Is(err, billing.ErrNoProviderTime) || !s.ProviderTime.IsZero() || !r.ProviderTime.IsZero() { |
| + t.Fatalf("headerless gave provider time: %v %v %v", err, s.ProviderTime, r.ProviderTime) |
| + } |
| + f.Headerless = false |
| + |
| + // A timeout before the headers: an error and no Date. |
| + f.HeaderlessTimeout = 2 |
| + if _, err := f.Subscription(ctx2, "sub_1"); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("headerless timeout on a read: %v", err) |
| + } |
| + if err := f.ClockProbe(ctx2); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("headerless timeout on the probe: %v", err) |
| + } |
| + if _, err := rec2.Now(); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Fatal("a headerless timeout gave a Date") |
| + } |
| + f.ProbeErr = errors.New("probe refused") |
| + if err := f.ClockProbe(ctx2); err == nil { |
| + t.Fatal("ProbeErr did not fail the probe") |
| + } |
| + if _, err := rec2.Now(); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Fatal("a failed probe gave a Date") |
| + } |
| + if f.CallsBy["ClockProbe"] != 4 { |
| + t.Fatalf("CallsBy[ClockProbe] = %d, want 4", f.CallsBy["ClockProbe"]) |
| + } |
| +} |
| + |
| +func TestFakeRenewWritesInvoice(t *testing.T) { |
| + f := newFake(t) |
| + s := seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + oldEnd := s.PeriodEnd |
| + |
| + f.FailPayment = 1 |
| + if _, err := f.Send(ctx, prepareApps(t, f, "sub_1", 3, billing.ProrateNow, "op:1")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ := f.Subscription(ctx, "sub_1") |
| + if !got.PeriodEnd.Equal(oldEnd.AddDate(1, 0, 0)) || got.PendingUpdate || got.Items[1].Quantity != 2 || len(got.Items) != 2 { |
| + t.Fatalf("after renewal = %+v", got) |
| + } |
| + |
| + // A later proration invoice does not hide the renewal one. |
| + if _, err := f.Send(ctx, prepareApps(t, f, "sub_1", 4, billing.ProrateNow, "op:2")); err != nil { |
| + t.Fatal(err) |
| + } |
| + inv, err := f.RenewalInvoice(ctx, "sub_1", oldEnd) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv.Invoice == "" || !inv.PeriodStart.Equal(oldEnd) || inv.ByPrice["price_plan"] != 1 || inv.ByPrice["price_apps"] != 2 || len(inv.ByPrice) != 2 { |
| + t.Fatalf("renewal invoice = %+v", inv) |
| + } |
| + if f.CallsBy["RenewalInvoice"] != 1 || f.CallsBy["RenewalInvoiceLines"] != 1 { |
| + t.Fatalf("CallsBy = %v", f.CallsBy) |
| + } |
| + if _, err := f.RenewalInvoice(ctx, "sub_1", oldEnd.AddDate(1, 0, 0)); !errors.Is(err, billing.ErrNotFound) { |
| + t.Fatalf("no invoice for that period: err = %v", err) |
| + } |
| + |
| + // Read failures, then a success. |
| + f.InvoiceReadFails(2) |
| + for range 2 { |
| + if _, err := f.RenewalInvoice(ctx, "sub_1", oldEnd); !errors.Is(err, ErrInjected) { |
| + t.Fatalf("injected failure: err = %v", err) |
| + } |
| + } |
| + if _, err := f.RenewalInvoice(ctx, "sub_1", oldEnd); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // A subscription set to stop renewing ends instead. |
| + f.Lock() |
| + f.Subs["sub_1"].CancelAtPeriodEnd = true |
| + f.Unlock() |
| + if err := f.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := f.Subscription(ctx, "sub_1"); got.Live || got.State != billing.StateEnded { |
| + t.Fatalf("a cancelling subscription renewed: %+v", got) |
| + } |
| +} |
| + |
| +func TestFakeApplyAfterRenewal(t *testing.T) { |
| + f := newFake(t) |
| + s := seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + oldEnd := s.PeriodEnd |
| + |
| + f.ApplyAfterRenewal("op:9") |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:9") |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("held send: err = %v", err) |
| + } |
| + if got := appsQty(t, f, "sub_1"); got != 2 { |
| + t.Fatalf("a held send applied before the renewal: apps = %d", got) |
| + } |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrInFlight) { |
| + t.Fatalf("resend of a held send: err = %v", err) |
| + } |
| + if err := f.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _ := f.Subscription(ctx, "sub_1") |
| + if got.Items[1].Quantity != 3 || !got.PeriodEnd.Equal(oldEnd.AddDate(1, 0, 0)) { |
| + t.Fatalf("after renewal = %+v", got) |
| + } |
| + inv, err := f.RenewalInvoice(ctx, "sub_1", oldEnd) |
| + if err != nil || inv.ByPrice["price_apps"] != 2 { |
| + t.Fatalf("the renewal billed %+v, %v; want the pre-restore 2", inv, err) |
| + } |
| + if r, err := f.Send(ctx, p); err != nil || !r.Replayed { |
| + t.Fatalf("resend after it applied = %+v, %v", r, err) |
| + } |
| +} |
| + |
| +func TestFakePagesLikeStripe(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + start := t0.AddDate(-300, 0, 0) |
| + for i := range 250 { |
| + f.AddInvoice(&Invoice{Subscription: "sub_1", Reason: ReasonCycle, PeriodStart: start.AddDate(i, 0, 0), |
| + Lines: []billing.Item{{PriceID: "price_plan", Quantity: 1}}}) |
| + } |
| + if _, err := f.RenewalInvoice(ctx, "sub_1", start.AddDate(17, 0, 0)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.CallsBy["RenewalInvoice"] != 3 || f.CallsBy["RenewalInvoiceLines"] != 1 { |
| + t.Fatalf("CallsBy = %v; want 3 invoice pages and 1 line page", f.CallsBy) |
| + } |
| + var invPages []PageRequest |
| + for _, pg := range f.PageLog { |
| + if pg.Method == "RenewalInvoice" { |
| + invPages = append(invPages, pg) |
| + } |
| + } |
| + if len(invPages) != 3 { |
| + t.Fatalf("page log = %+v", invPages) |
| + } |
| + wantHasMore := []bool{true, true, false} |
| + wantN := []int{100, 100, 50} |
| + for i, pg := range invPages { |
| + if pg.Limit != 100 || pg.HasMore != wantHasMore[i] || len(pg.IDs) != wantN[i] { |
| + t.Errorf("page %d = limit %d has_more %v n %d", i, pg.Limit, pg.HasMore, len(pg.IDs)) |
| + } |
| + if i == 0 && pg.StartingAfter != "" { |
| + t.Errorf("first page starts after %q", pg.StartingAfter) |
| + } |
| + if i > 0 && pg.StartingAfter != invPages[i-1].IDs[len(invPages[i-1].IDs)-1] { |
| + t.Errorf("page %d starts after %q, want the last id of page %d", i, pg.StartingAfter, i-1) |
| + } |
| + } |
| + |
| + // No invoices: one page, empty, and the invoice is not found. |
| + g := newFake(t) |
| + seedSub(g, "sub_1", "cus_1") |
| + if _, err := g.RenewalInvoice(ctx, "sub_1", start); !errors.Is(err, billing.ErrNotFound) { |
| + t.Fatalf("no invoices: err = %v", err) |
| + } |
| + if g.CallsBy["RenewalInvoice"] != 1 || g.CallsBy["RenewalInvoiceLines"] != 0 { |
| + t.Fatalf("no invoices: CallsBy = %v", g.CallsBy) |
| + } |
| + |
| + // Subscriptions page the same way, examined in every status. |
| + h := newFake(t) |
| + for i := range 250 { |
| + s := seedSub(h, fmt.Sprintf("sub_%03d", i), "cus_1") |
| + s.Live = i%5 != 0 |
| + } |
| + seedSub(h, "sub_other", "cus_2") |
| + live, err := h.LiveSubscriptions(ctx, "cus_1") |
| + if err != nil || len(live) != 200 || h.CallsBy["LiveSubscriptions"] != 3 { |
| + t.Fatalf("LiveSubscriptions = %d ids, %v, %d pages", len(live), err, h.CallsBy["LiveSubscriptions"]) |
| + } |
| + if ids, err := h.LiveSubscriptions(ctx, "cus_none"); err != nil || len(ids) != 0 || h.CallsBy["LiveSubscriptions"] != 4 { |
| + t.Fatalf("no subscriptions: %v, %v, %d pages", ids, err, h.CallsBy["LiveSubscriptions"]) |
| + } |
| +} |
| + |
| +func TestFakePagingAndIncomplete(t *testing.T) { |
| + ctx := context.Background() |
| + f := newFake(t) |
| + f.PageSize = 2 |
| + for i := range 20 { |
| + seedSub(f, fmt.Sprintf("sub_%02d", i), "cus_1") |
| + } |
| + if ids, err := f.LiveSubscriptions(ctx, "cus_1"); err != nil || len(ids) != 20 || f.CallsBy["LiveSubscriptions"] != 10 { |
| + t.Fatalf("10 full pages: %d ids, %v, %d pages", len(ids), err, f.CallsBy["LiveSubscriptions"]) |
| + } |
| + seedSub(f, "sub_20", "cus_1") |
| + if _, err := f.LiveSubscriptions(ctx, "cus_1"); !errors.Is(err, billing.ErrIncomplete) { |
| + t.Fatalf("an 11th page: err = %v, want ErrIncomplete", err) |
| + } |
| + if f.CallsBy["LiveSubscriptions"] != 20 { |
| + t.Fatalf("ErrIncomplete read %d pages, want 10 more", f.CallsBy["LiveSubscriptions"]-10) |
| + } |
| + |
| + // A page is never more than 100. |
| + g := newFake(t) |
| + g.PageSize = 500 |
| + for i := range 101 { |
| + seedSub(g, fmt.Sprintf("sub_%03d", i), "cus_1") |
| + } |
| + if _, err := g.LiveSubscriptions(ctx, "cus_1"); err != nil || g.CallsBy["LiveSubscriptions"] != 2 { |
| + t.Fatalf("101 at PageSize 500: %v, %d pages", err, g.CallsBy["LiveSubscriptions"]) |
| + } |
| + |
| + // Sessions: filtered by customer and creation time, then paged. |
| + h := newFake(t) |
| + h.PageSize = 3 |
| + for i := range 7 { |
| + h.AddSession(&Session{CheckoutInfo: billing.CheckoutInfo{Customer: "cus_1", IntentID: fmt.Sprintf("in_%d", i), |
| + State: billing.CheckoutOpen, ExpiresAt: t0.Add(time.Hour)}, Created: t0.Add(time.Duration(i) * time.Minute)}) |
| + } |
| + h.AddSession(&Session{CheckoutInfo: billing.CheckoutInfo{Customer: "cus_2", State: billing.CheckoutOpen}, Created: t0}) |
| + got, err := h.CustomerCheckouts(ctx, "cus_1", t0.Add(90*time.Second)) |
| + if err != nil || len(got) != 5 || h.CallsBy["CustomerCheckouts"] != 2 { |
| + t.Fatalf("CustomerCheckouts = %d, %v, %d pages", len(got), err, h.CallsBy["CustomerCheckouts"]) |
| + } |
| + for _, c := range got { |
| + if c.IntentID == "in_0" || c.IntentID == "in_1" || c.Customer != "cus_1" { |
| + t.Errorf("returned %+v", c) |
| + } |
| + } |
| + h.PageSize = 0 |
| + for i := range 1000 { |
| + h.AddSession(&Session{CheckoutInfo: billing.CheckoutInfo{Customer: "cus_1", State: billing.CheckoutExpired}, Created: t0.Add(time.Duration(i) * time.Second)}) |
| + } |
| + if _, err := h.CustomerCheckouts(ctx, "cus_1", t0.Add(-time.Hour)); !errors.Is(err, billing.ErrIncomplete) { |
| + t.Fatalf("1007 sessions: err = %v, want ErrIncomplete", err) |
| + } |
| + |
| + // Every request is counted once: CallsBy sums to Calls. |
| + sum := 0 |
| + for _, n := range h.CallsBy { |
| + sum += n |
| + } |
| + if sum != h.Calls { |
| + t.Fatalf("CallsBy sums to %d, Calls = %d", sum, h.Calls) |
| + } |
| +} |
| + |
| +func TestFakeCrashHooks(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + |
| + f.CrashBeforeSend = true |
| + p := prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1") |
| + if _, err := f.Send(ctx, p); !errors.Is(err, ErrCrash) { |
| + t.Fatalf("crash before send: err = %v", err) |
| + } |
| + if f.CallsBy["Send"] != 0 || len(f.Sent) != 0 || appsQty(t, f, "sub_1") != 2 || f.CrashBeforeSend { |
| + t.Fatalf("crash before send reached the provider: %v, %d sent", f.CallsBy, len(f.Sent)) |
| + } |
| + if r, err := f.Send(ctx, p); err != nil || r.Replayed { |
| + t.Fatalf("after a crash before send, the resend is a first execution: %+v, %v", r, err) |
| + } |
| + |
| + f.CrashAfterSend = true |
| + p2 := prepareApps(t, f, "sub_1", 4, billing.ProrateNone, "op:2") |
| + if _, err := f.Send(ctx, p2); !errors.Is(err, ErrCrash) { |
| + t.Fatalf("crash after send: err = %v", err) |
| + } |
| + if f.CallsBy["Send"] != 2 || appsQty(t, f, "sub_1") != 4 || f.CrashAfterSend { |
| + t.Fatalf("crash after send did not apply: %v", f.CallsBy) |
| + } |
| + if r, err := f.Send(ctx, p2); err != nil || !r.Replayed { |
| + t.Fatalf("after a crash after send, the resend replays: %+v, %v", r, err) |
| + } |
| + // ErrCrash is not one of the outcome classes. |
| + for _, cls := range []error{billing.ErrNoResponse, billing.ErrIndeterminate, billing.ErrRefused, billing.ErrNotExecuted, billing.ErrInFlight, billing.ErrPaymentFailed} { |
| + if errors.Is(ErrCrash, cls) { |
| + t.Errorf("ErrCrash is %v", cls) |
| + } |
| + } |
| +} |
| + |
| +func TestFakeCheckoutRaces(t *testing.T) { |
| + f := newFake(t) |
| + rec := f.Recorder() |
| + ctx := billing.WithClock(context.Background(), rec) |
| + |
| + pc, err := f.PrepareCustomer("bab", "customer:bab:1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r, err := f.Send(ctx, pc) |
| + if err != nil || r.Customer == "" || f.Customers[r.Customer] == nil || f.Customers[r.Customer].Account != "bab" { |
| + t.Fatalf("customer = %+v, %v", r, err) |
| + } |
| + cus := r.Customer |
| + |
| + newSession := func(intent string) billing.CheckoutInfo { |
| + t.Helper() |
| + p, err := f.PrepareCheckout(billing.CheckoutRequest{ |
| + Customer: cus, AccountSqid: "bab", IntentID: intent, Book: "example-v1", Currency: "usd", |
| + Items: []billing.CheckoutItem{{PriceID: "price_plan", Quantity: 1}, {PriceID: "price_apps", Quantity: 2}}, |
| + SuccessURL: "https://console.example.com/ok", CancelURL: "https://console.example.com/no", |
| + ExpiresAt: f.ProviderClock.Add(time.Hour), IdempotencyKey: "checkout:" + intent, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r, err := f.Send(ctx, p) |
| + if err != nil || r.Checkout == nil || r.Checkout.State != billing.CheckoutOpen || r.Checkout.URL == "" || r.Checkout.IntentID != intent { |
| + t.Fatalf("checkout = %+v, %v", r, err) |
| + } |
| + return *r.Checkout |
| + } |
| + |
| + // The buyer pays, then the console's expiry lands: refused. |
| + s1 := newSession("in_1") |
| + if got, err := f.Checkout(ctx, s1.ID); err != nil || got.State != billing.CheckoutOpen { |
| + t.Fatalf("read = %+v, %v", got, err) |
| + } |
| + if list, err := f.CustomerCheckouts(ctx, cus, t0.Add(-time.Minute)); err != nil || len(list) != 1 || list[0].IntentID != "in_1" { |
| + t.Fatalf("list = %+v, %v", list, err) |
| + } |
| + subID, err := f.CompleteCheckout(s1.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pe, _ := f.PrepareExpire(s1.ID, "expire:in_1") |
| + if _, err := f.Send(ctx, pe); !errors.Is(err, billing.ErrRefused) { |
| + t.Fatalf("expiring a completed session: err = %v", err) |
| + } |
| + if got, _ := f.Checkout(ctx, s1.ID); got.State != billing.CheckoutComplete || got.Subscription != subID { |
| + t.Fatalf("completed session = %+v", got) |
| + } |
| + if got, _ := f.CheckoutSubscription(ctx, s1.ID); got != subID { |
| + t.Fatalf("CheckoutSubscription = %q", got) |
| + } |
| + sub, err := f.Subscription(ctx, subID) |
| + if err != nil || !sub.Live || sub.Account != "bab" || sub.Customer != cus || len(sub.Items) != 2 || sub.Items[0].ItemID == "" || |
| + !sub.PeriodEnd.Equal(f.ProviderClock.AddDate(1, 0, 0)) { |
| + t.Fatalf("checkout subscription = %+v, %v", sub, err) |
| + } |
| + if live, _ := f.LiveSubscriptions(ctx, cus); len(live) != 1 || live[0] != subID { |
| + t.Fatalf("live = %v", live) |
| + } |
| + |
| + // The console expires first; the buyer is too late. |
| + s2 := newSession("in_2") |
| + pe2, _ := f.PrepareExpire(s2.ID, "expire:in_2") |
| + r, err = f.Send(ctx, pe2) |
| + if err != nil || r.Checkout.State != billing.CheckoutExpired { |
| + t.Fatalf("expire = %+v, %v", r, err) |
| + } |
| + if _, err := f.CompleteCheckout(s2.ID); err == nil { |
| + t.Fatal("completed an expired session") |
| + } |
| + |
| + // The buyer pays in the instant before the expiry arrives. |
| + s3 := newSession("in_3") |
| + f.BeforeSend = func(p billing.Prepared) error { |
| + if p.Kind == billing.PreparedExpire { |
| + if _, err := f.CompleteCheckout(s3.ID); err != nil { |
| + t.Errorf("race completion: %v", err) |
| + } |
| + } |
| + return nil |
| + } |
| + pe3, _ := f.PrepareExpire(s3.ID, "expire:in_3") |
| + if _, err := f.Send(ctx, pe3); !errors.Is(err, billing.ErrRefused) { |
| + t.Fatalf("expiry after a racing completion: err = %v", err) |
| + } |
| + f.BeforeSend = nil |
| + |
| + // A session left open past its expiry expires at the provider. |
| + s4 := newSession("in_4") |
| + f.AdvanceProvider(time.Hour) |
| + if got, _ := f.Checkout(ctx, s4.ID); got.State != billing.CheckoutExpired { |
| + t.Fatalf("session past expires_at = %+v", got) |
| + } |
| + if _, err := f.CompleteCheckout(s4.ID); err == nil { |
| + t.Fatal("completed a session past expires_at") |
| + } |
| + |
| + // A create whose expires_at has already passed is refused, and the |
| + // refusal is not stored: a validation error. |
| + stale, _ := f.PrepareCheckout(billing.CheckoutRequest{Customer: cus, AccountSqid: "bab", IntentID: "in_5", |
| + Currency: "usd", Items: []billing.CheckoutItem{{PriceID: "price_plan", Quantity: 1}}, |
| + ExpiresAt: f.ProviderClock.Add(-time.Minute), IdempotencyKey: "checkout:in_5"}) |
| + for range 2 { |
| + if r, err := f.Send(ctx, stale); !errors.Is(err, billing.ErrRefused) || r.Replayed { |
| + t.Fatalf("stale create = %+v, %v", r, err) |
| + } |
| + } |
| + |
| + // A create that lands after its lost response: a late session. |
| + f.CompleteLater(0) |
| + p, _ := f.PrepareCheckout(billing.CheckoutRequest{Customer: cus, AccountSqid: "bab", IntentID: "in_6", |
| + Currency: "usd", Items: []billing.CheckoutItem{{PriceID: "price_plan", Quantity: 1}}, |
| + ExpiresAt: f.ProviderClock.Add(time.Hour), IdempotencyKey: "checkout:in_6"}) |
| + if _, err := f.Send(ctx, p); !errors.Is(err, billing.ErrNoResponse) { |
| + t.Fatalf("late create: err = %v", err) |
| + } |
| + list, _ := f.CustomerCheckouts(ctx, cus, t0.Add(-time.Minute)) |
| + found := false |
| + for _, c := range list { |
| + found = found || c.IntentID == "in_6" |
| + } |
| + if !found { |
| + t.Fatal("the late session is not listed") |
| + } |
| + if _, err := f.Checkout(ctx, "cs_nope"); !errors.Is(err, billing.ErrNotFound) { |
| + t.Fatalf("unknown session: %v", err) |
| + } |
| +} |
| + |
| +func TestFakePortalAndWrites(t *testing.T) { |
| + f := newFake(t) |
| + seedSub(f, "sub_1", "cus_1") |
| + ctx := context.Background() |
| + u, err := f.PortalURL(ctx, "cus_1", "https://console.example.com/billing", "portal:cus_1:00") |
| + if err != nil || u == "" { |
| + t.Fatalf("portal = %q, %v", u, err) |
| + } |
| + if _, err := f.Subscription(ctx, "sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.Writes() != 1 { |
| + t.Fatalf("Writes = %d, want 1 (the portal)", f.Writes()) |
| + } |
| + if _, err := f.Send(ctx, prepareApps(t, f, "sub_1", 3, billing.ProrateNone, "op:1")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f.Writes() != 2 { |
| + t.Fatalf("Writes = %d, want 2", f.Writes()) |
| + } |
| +} |
| + |
| +// Seeded items without ids get stable ones the first time they are served. |
| +func TestFakeAssignsItemIDs(t *testing.T) { |
| + f := newFake(t) |
| + f.Subs["sub_1"] = &billing.Subscription{ID: "sub_1", Customer: "cus_1", Live: true, Currency: "usd", ItemsComplete: true, |
| + Items: []billing.Item{{PriceID: "price_plan", Quantity: 1}}} |
| + a, _ := f.Subscription(context.Background(), "sub_1") |
| + b, _ := f.Subscription(context.Background(), "sub_1") |
| + if a.Items[0].ItemID == "" || a.Items[0].ItemID != b.Items[0].ItemID { |
| + t.Fatalf("item ids %q, %q", a.Items[0].ItemID, b.Items[0].ItemID) |
| + } |
| + // Copies on read: editing a returned value changes nothing. |
| + a.Items[0].Quantity = 9 |
| + if c, _ := f.Subscription(context.Background(), "sub_1"); c.Items[0].Quantity != 1 { |
| + t.Fatal("a read shares its items with the Fake") |
| + } |
| +} |
diff --git a/internal/billing/clock.go b/internal/billing/clock.go| new file mode 100644 |
| index 000000000..8edf8088e |
| --- /dev/null |
| +++ b/internal/billing/clock.go |
| @@ -0,0 +1,101 @@ |
| +package billing |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// ProviderTimeMaxAge is how long one provider observation stays usable, |
| +// measured on the local monotonic clock. |
| +const ProviderTimeMaxAge = 60 * time.Second |
| + |
| +// ErrNoProviderTime is a ClockRecorder with no observation at most |
| +// ProviderTimeMaxAge old: every billing decision that needs provider time |
| +// refuses, or makes one ClockProbe first. |
| +var ErrNoProviderTime = errors.New("billing: no provider time") |
| + |
| +// processStart anchors the default monotonic source: time.Since on it |
| +// reads the process's monotonic clock, which a wall-clock change never |
| +// moves. |
| +var processStart = time.Now() |
| + |
| +// ClockRecorder is provider time for one console request (Invariant 9). The |
| +// adapter reports the Date header of every provider response it gets |
| +// through a context carrying the recorder (ObserveDate); Now is the last |
| +// such Date plus the monotonic time elapsed since it arrived. |
| +// |
| +// The console's wall clock never enters: a wrong or corrected console clock, |
| +// or a restart, cannot move provider time. The monotonic reading never |
| +// leaves the process, so a recorder starts empty in every request. |
| +// |
| +// The zero value is ready to use, with the process's monotonic clock. |
| +type ClockRecorder struct { |
| + // Monotonic reads a monotonic clock as a duration since any fixed |
| + // point. nil is the process's own; tests inject theirs (the billingtest |
| + // Fake's Monotonic). It must not take a lock the adapter may hold. |
| + Monotonic func() time.Duration |
| + |
| + mu sync.Mutex |
| + date time.Time // the last observed Date |
| + at time.Duration // the monotonic reading when it arrived |
| + seen bool |
| +} |
| + |
| +func (r *ClockRecorder) mono() time.Duration { |
| + if r.Monotonic != nil { |
| + return r.Monotonic() |
| + } |
| + return time.Since(processStart) |
| +} |
| + |
| +// observe records date as received now. A zero date (a response with no |
| +// Date header) is not an observation and keeps the previous one. |
| +func (r *ClockRecorder) observe(date time.Time) { |
| + if date.IsZero() { |
| + return |
| + } |
| + at := r.mono() |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + r.date, r.at, r.seen = date, at, true |
| +} |
| + |
| +// Now is provider time: the last observed Date plus the monotonic time |
| +// since it arrived, while that is at most ProviderTimeMaxAge. Otherwise |
| +// ErrNoProviderTime. |
| +func (r *ClockRecorder) Now() (time.Time, error) { |
| + now := r.mono() |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if !r.seen { |
| + return time.Time{}, ErrNoProviderTime |
| + } |
| + elapsed := max(now-r.at, 0) |
| + if elapsed > ProviderTimeMaxAge { |
| + return time.Time{}, ErrNoProviderTime |
| + } |
| + return r.date.Add(elapsed), nil |
| +} |
| + |
| +type clockKey struct{} |
| + |
| +// WithClock returns ctx carrying r: provider responses to requests made with |
| +// the returned context are observed into r. |
| +func WithClock(ctx context.Context, r *ClockRecorder) context.Context { |
| + return context.WithValue(ctx, clockKey{}, r) |
| +} |
| + |
| +// ObserveDate reports one provider response's Date header to the recorder |
| +// ctx carries. It is a no-op when ctx carries none, and for a zero date (a |
| +// response with no Date header). Adapters call it on every response they |
| +// receive, errors included. |
| +func ObserveDate(ctx context.Context, date time.Time) { |
| + if ctx == nil { |
| + return |
| + } |
| + if r, ok := ctx.Value(clockKey{}).(*ClockRecorder); ok && r != nil { |
| + r.observe(date) |
| + } |
| +} |
diff --git a/internal/billing/clock_test.go b/internal/billing/clock_test.go| new file mode 100644 |
| index 000000000..682107bd6 |
| --- /dev/null |
| +++ b/internal/billing/clock_test.go |
| @@ -0,0 +1,97 @@ |
| +package billing |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// fakeMono is a monotonic source a test moves by hand. |
| +type fakeMono struct{ d time.Duration } |
| + |
| +func (m *fakeMono) read() time.Duration { return m.d } |
| + |
| +func TestClockFreshObservation(t *testing.T) { |
| + mono := &fakeMono{d: 5 * time.Second} |
| + rec := &ClockRecorder{Monotonic: mono.read} |
| + ctx := WithClock(context.Background(), rec) |
| + date := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + ObserveDate(ctx, date) |
| + |
| + mono.d += 20 * time.Second |
| + got, err := rec.Now() |
| + if err != nil || !got.Equal(date.Add(20*time.Second)) { |
| + t.Fatalf("Now = %v, %v; want %v", got, err, date.Add(20*time.Second)) |
| + } |
| + |
| + // Exactly 60 s old is still provider time. |
| + mono.d += 40 * time.Second |
| + if got, err := rec.Now(); err != nil || !got.Equal(date.Add(60*time.Second)) { |
| + t.Fatalf("at 60 s: Now = %v, %v", got, err) |
| + } |
| + |
| + // A later observation replaces the earlier one. |
| + later := date.Add(time.Hour) |
| + ObserveDate(ctx, later) |
| + if got, err := rec.Now(); err != nil || !got.Equal(later) { |
| + t.Fatalf("after a second observation: Now = %v, %v; want %v", got, err, later) |
| + } |
| +} |
| + |
| +func TestClockStaleObservation(t *testing.T) { |
| + mono := &fakeMono{} |
| + rec := &ClockRecorder{Monotonic: mono.read} |
| + ctx := WithClock(context.Background(), rec) |
| + ObserveDate(ctx, time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)) |
| + mono.d = 61 * time.Second |
| + if _, err := rec.Now(); !errors.Is(err, ErrNoProviderTime) { |
| + t.Fatalf("61 s stale: err = %v, want ErrNoProviderTime", err) |
| + } |
| +} |
| + |
| +func TestClockNoRecorder(t *testing.T) { |
| + // No recorder on the context: observing is a no-op and must not panic. |
| + ObserveDate(context.Background(), time.Now()) |
| + |
| + // A recorder that never saw a response has no provider time. |
| + rec := &ClockRecorder{} |
| + if _, err := rec.Now(); !errors.Is(err, ErrNoProviderTime) { |
| + t.Fatalf("empty recorder: err = %v, want ErrNoProviderTime", err) |
| + } |
| + // A recorder on one context does not see another context's responses. |
| + ObserveDate(WithClock(context.Background(), &ClockRecorder{}), time.Now()) |
| + if _, err := rec.Now(); !errors.Is(err, ErrNoProviderTime) { |
| + t.Fatalf("other context: err = %v", err) |
| + } |
| +} |
| + |
| +func TestClockHeaderless(t *testing.T) { |
| + // A response with no Date header gives the adapter a zero time: it is |
| + // not an observation, and it does not erase an earlier one. |
| + mono := &fakeMono{} |
| + rec := &ClockRecorder{Monotonic: mono.read} |
| + ctx := WithClock(context.Background(), rec) |
| + ObserveDate(ctx, time.Time{}) |
| + if _, err := rec.Now(); !errors.Is(err, ErrNoProviderTime) { |
| + t.Fatalf("headerless only: err = %v, want ErrNoProviderTime", err) |
| + } |
| + date := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + ObserveDate(ctx, date) |
| + mono.d = 10 * time.Second |
| + ObserveDate(ctx, time.Time{}) |
| + if got, err := rec.Now(); err != nil || !got.Equal(date.Add(10*time.Second)) { |
| + t.Fatalf("headerless after a date: Now = %v, %v", got, err) |
| + } |
| +} |
| + |
| +// The zero recorder uses the process's monotonic clock. |
| +func TestClockDefaultMonotonic(t *testing.T) { |
| + rec := &ClockRecorder{} |
| + date := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC) |
| + ObserveDate(WithClock(context.Background(), rec), date) |
| + got, err := rec.Now() |
| + if err != nil || got.Before(date) || got.After(date.Add(5*time.Second)) { |
| + t.Fatalf("Now = %v, %v", got, err) |
| + } |
| +} |
diff --git a/internal/billing/recognise.go b/internal/billing/recognise.go| index 07212a3e4..25e737cbc 100644 |
| --- a/internal/billing/recognise.go |
| +++ b/internal/billing/recognise.go |
| @@ -9,10 +9,12 @@ import ( |
| ) |
| // Purchase is what a subscription bought: one paid plan and the packs on |
| -// it, under one book, in one currency. |
| +// it, under one book, in one currency. Seats is a team plan's billed |
| +// member count (its plan item's quantity); 0 on any other plan. |
| type Purchase struct { |
| Book, Currency, Plan string |
| Packs map[string]int |
| + Seats int |
| } |
| // ErrUnrecognised is a subscription whose items are not a purchase the |
| @@ -24,7 +26,8 @@ func unrecognised(format string, a ...any) error { |
| } |
| // Recognise turns a subscription's items into a purchase: exactly one paid |
| -// plan at quantity 1, and at most one item per pack that plan offers, each |
| +// plan, at quantity 1 or, for a team plan, at its billed seats (the plan's |
| +// minimum to plans.MaxTeamMembers), and at most one item per pack that plan offers, each |
| // within its quantity bounds, all under one book and in the subscription's |
| // currency. A subscription under an earlier book is read from its keys |
| // alone; the current book is not consulted. |
| @@ -53,13 +56,18 @@ func Recognise(sub *Subscription, prices PriceMap, cat *plans.Catalog) (Purchase |
| if p.Plan != "" { |
| return Purchase{}, unrecognised("more than one plan item") |
| } |
| - if it.Quantity != 1 { |
| - return Purchase{}, unrecognised("plan %s has quantity %d", ref.Name, it.Quantity) |
| - } |
| plan, ok := cat.Plans[ref.Name] |
| if !ok || !plan.Paid { |
| return Purchase{}, unrecognised("plan %q is not a paid plan in the catalog", ref.Name) |
| } |
| + if t := plan.Team; t != nil { |
| + if it.Quantity < int64(t.MinMembers) || it.Quantity > plans.MaxTeamMembers { |
| + return Purchase{}, unrecognised("team plan %s has quantity %d, allowed %d to %d", ref.Name, it.Quantity, t.MinMembers, plans.MaxTeamMembers) |
| + } |
| + p.Seats = int(it.Quantity) |
| + } else if it.Quantity != 1 { |
| + return Purchase{}, unrecognised("plan %s has quantity %d", ref.Name, it.Quantity) |
| + } |
| p.Plan = ref.Name |
| case KindPack: |
| packItems = append(packItems, ref) |
diff --git a/internal/billing/recognise_test.go b/internal/billing/recognise_test.go| index 21aa7cf8a..8ae1f5018 100644 |
| --- a/internal/billing/recognise_test.go |
| +++ b/internal/billing/recognise_test.go |
| @@ -71,6 +71,103 @@ func TestRecogniseEarlierBook(t *testing.T) { |
| } |
| } |
| +// A team plan item's quantity is the billed seats: from the plan's minimum |
| +// to plans.MaxTeamMembers. |
| +func TestRecogniseTeamSeats(t *testing.T) { |
| + m, item := recogniseFixture(t, nil) |
| + cat := exampleCatalog(t) |
| + for _, tc := range []struct { |
| + key string |
| + qty int64 |
| + plan string |
| + seats int |
| + }{ |
| + {"example-v1/community/usd", 10, "community", 10}, |
| + {"example-v1/community/usd", 37, "community", 37}, |
| + {"example-v1/business/usd", 10000, "business", 10000}, |
| + } { |
| + sub := &Subscription{ID: "sub_1", Currency: "usd", ItemsComplete: true, Items: []Item{ |
| + item(tc.key, tc.qty, "usd"), item("example-v1/pack/apps/usd", 2, "usd"), |
| + }} |
| + got, err := Recognise(sub, m, cat) |
| + if err != nil { |
| + t.Fatalf("%s x%d: %v", tc.key, tc.qty, err) |
| + } |
| + if got.Plan != tc.plan || got.Seats != tc.seats || got.Packs["apps"] != 2 { |
| + t.Errorf("%s x%d: %+v", tc.key, tc.qty, got) |
| + } |
| + } |
| + // A plan that is not a team plan has no seats. |
| + sub := &Subscription{ID: "sub_1", Currency: "usd", ItemsComplete: true, Items: []Item{item("example-v1/personal/usd", 1, "usd")}} |
| + if got, err := Recognise(sub, m, cat); err != nil || got.Seats != 0 { |
| + t.Errorf("personal: %+v, %v", got, err) |
| + } |
| +} |
| + |
| +func TestRecogniseTeamRefuses(t *testing.T) { |
| + m, item := recogniseFixture(t, nil) |
| + cat := exampleCatalog(t) |
| + for name, qty := range map[string]int64{ |
| + "below the minimum": 9, |
| + "one": 1, |
| + "zero": 0, |
| + "above the maximum": 10001, |
| + } { |
| + sub := &Subscription{Currency: "usd", ItemsComplete: true, Items: []Item{item("example-v1/community/usd", qty, "usd")}} |
| + if _, err := Recognise(sub, m, cat); !errors.Is(err, ErrUnrecognised) { |
| + t.Errorf("%s (%d): err = %v, want ErrUnrecognised", name, qty, err) |
| + } |
| + } |
| + // A team plan and another plan together are still two plan items. |
| + sub := &Subscription{Currency: "usd", ItemsComplete: true, Items: []Item{ |
| + item("example-v1/community/usd", 10, "usd"), item("example-v1/personal/usd", 1, "usd"), |
| + }} |
| + if _, err := Recognise(sub, m, cat); !errors.Is(err, ErrUnrecognised) { |
| + t.Errorf("team and personal: err = %v", err) |
| + } |
| +} |
| + |
| +func TestFindItem(t *testing.T) { |
| + m, item := recogniseFixture(t, nil) |
| + plan := item("example-v1/community/usd", 12, "usd") |
| + plan.ItemID = "si_plan" |
| + apps := item("example-v1/pack/apps/usd", 3, "usd") |
| + apps.ItemID = "si_apps" |
| + sub := &Subscription{Currency: "usd", Items: []Item{plan, apps, {ItemID: "si_unknown", PriceID: "price_nope", Quantity: 1}}} |
| + |
| + if got, ok := FindItem(sub, m, KindPack, "apps"); !ok || got.ItemID != "si_apps" || got.Quantity != 3 { |
| + t.Errorf("apps = %+v, %v", got, ok) |
| + } |
| + if got, ok := FindItem(sub, m, KindPlan, "community"); !ok || got.ItemID != "si_plan" { |
| + t.Errorf("community = %+v, %v", got, ok) |
| + } |
| + // An empty name finds the item of that kind, whatever it is: the plan |
| + // item when the plan is not known yet. |
| + if got, ok := FindItem(sub, m, KindPlan, ""); !ok || got.ItemID != "si_plan" { |
| + t.Errorf("any plan = %+v, %v", got, ok) |
| + } |
| + for _, q := range [][2]string{{KindPack, "email"}, {KindPlan, "personal"}, {KindPack, "community"}} { |
| + if got, ok := FindItem(sub, m, q[0], q[1]); ok { |
| + t.Errorf("%s %s found %+v", q[0], q[1], got) |
| + } |
| + } |
| + if _, ok := FindItem(nil, m, KindPlan, ""); ok { |
| + t.Error("nil subscription found an item") |
| + } |
| +} |
| + |
| +func TestRenewing(t *testing.T) { |
| + cases := []struct { |
| + live, cancel, want bool |
| + }{{true, false, true}, {true, true, false}, {false, false, false}} |
| + for _, c := range cases { |
| + s := &Subscription{Live: c.live, CancelAtPeriodEnd: c.cancel} |
| + if got := s.Renewing(); got != c.want { |
| + t.Errorf("live %v cancel %v: Renewing = %v", c.live, c.cancel, got) |
| + } |
| + } |
| +} |
| + |
| func TestRecogniseRefuses(t *testing.T) { |
| m, item := recogniseFixture(t, map[string]string{ |
| "example-v0/personal/usd": "price_v0personalusd", |
diff --git a/internal/billingstripe/unimplemented.go b/internal/billingstripe/unimplemented.go| new file mode 100644 |
| index 000000000..b89812c3d |
| --- /dev/null |
| +++ b/internal/billingstripe/unimplemented.go |
| @@ -0,0 +1,60 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// errNotImplemented is every Plan 6b provider method until Task 5 builds |
| +// the Stripe encoding and outcome classification. Nothing here makes a |
| +// request. |
| +var errNotImplemented = errors.New("billingstripe: not implemented yet (plan 6b task 5)") |
| + |
| +func (p *Provider) PrepareCustomer(string, string) (billing.Prepared, error) { |
| + return billing.Prepared{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) PrepareCheckout(billing.CheckoutRequest) (billing.Prepared, error) { |
| + return billing.Prepared{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) PrepareExpire(string, string) (billing.Prepared, error) { |
| + return billing.Prepared{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) PrepareChange(billing.ChangeRequest) (billing.Prepared, error) { |
| + return billing.Prepared{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) PrepareRenewal(string, bool, string) (billing.Prepared, error) { |
| + return billing.Prepared{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) Send(context.Context, billing.Prepared) (billing.Result, error) { |
| + return billing.Result{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) LiveSubscriptions(context.Context, string) ([]string, error) { |
| + return nil, errNotImplemented |
| +} |
| + |
| +func (p *Provider) CustomerCheckouts(context.Context, string, time.Time) ([]billing.CheckoutInfo, error) { |
| + return nil, errNotImplemented |
| +} |
| + |
| +func (p *Provider) Checkout(context.Context, string) (billing.CheckoutInfo, error) { |
| + return billing.CheckoutInfo{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) RenewalInvoice(context.Context, string, time.Time) (billing.InvoiceQuantities, error) { |
| + return billing.InvoiceQuantities{}, errNotImplemented |
| +} |
| + |
| +func (p *Provider) PortalURL(context.Context, string, string, string) (string, error) { |
| + return "", errNotImplemented |
| +} |
| + |
| +func (p *Provider) ClockProbe(context.Context) error { return errNotImplemented } |