console: operations as prepared requests resolved by Stripe's idempotent result or a positive read; one outstanding predicate and one recovery gate; orphaned sends recovered; durable late-restore obligations; passes only read (plans 6b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
19 files changed,
+3,673
−28
internal/billing/clock.go+12 −0internal/console/apibilling.go+88 −16internal/console/apibilling_copy.go+4 −0internal/console/billing.go+9 −0internal/console/billinghold.go+138 −0internal/console/billinglate.go+330 −0internal/console/billinglate_test.go+542 −0internal/console/billinglint_test.go+351 −0internal/console/billingops.go+723 −0internal/console/billingops_test.go+1,160 −0internal/console/billingpage_copy.go+19 −0internal/console/billingpass.go+129 −7internal/console/billingstore.go+63 −1internal/console/billingsync.go+88 −4internal/console/claim_invariant_fixtures_test.go+4 −0internal/console/claim_invariant_probes_nonapp_test.go+8 −0internal/console/server.go+3 −0internal/console/store_gate.go+1 −0internal/console/testdata/claim-routes.txt+1 −0
diff --git a/internal/billing/clock.go b/internal/billing/clock.go| index 8edf8088e..bfd21a94d 100644 |
| --- a/internal/billing/clock.go |
| +++ b/internal/billing/clock.go |
| @@ -87,6 +87,18 @@ func WithClock(ctx context.Context, r *ClockRecorder) context.Context { |
| return context.WithValue(ctx, clockKey{}, r) |
| } |
| +// ClockFrom is the recorder ctx carries, nil when it carries none. A caller |
| +// that needs provider time and finds none installs a recorder before its |
| +// first provider request; one that finds one shares it (a pass round's |
| +// observations serve every decision in the round while they are fresh). |
| +func ClockFrom(ctx context.Context) *ClockRecorder { |
| + if ctx == nil { |
| + return nil |
| + } |
| + r, _ := ctx.Value(clockKey{}).(*ClockRecorder) |
| + return 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 |
diff --git a/internal/console/apibilling.go b/internal/console/apibilling.go| index 95a1082ca..0efe13c23 100644 |
| --- a/internal/console/apibilling.go |
| +++ b/internal/console/apibilling.go |
| @@ -127,10 +127,11 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| return |
| } |
| now := time.Now() |
| - // A quick refusal outside the lock while the subscription is live. The |
| - // deciding read is made again under the account's billing lock, with |
| - // the problem re-checked there (Astra round 2 finding 3). |
| - if p.Subscription != "" { |
| + // A quick refusal outside the lock while the subscription is live, for |
| + // the reasons closed only once it has ended. The deciding read is made |
| + // again under the account's billing hold, with the problem re-checked |
| + // there (Astra round 2 finding 3). |
| + if p.Subscription != "" && !problemClosableWhileLive(p.Reason) { |
| sub, err := s.billing.cfg.Provider.Subscription(r.Context(), p.Subscription) |
| switch { |
| case errors.Is(err, billing.ErrNotFound): |
| @@ -143,7 +144,7 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| return |
| } |
| } |
| - if status, msg := s.closeBillingProblemLocked(r.Context(), p, addr, note, now); status != http.StatusOK { |
| + if status, msg := s.closeBillingProblem(r.Context(), p, addr, note, now); status != http.StatusOK { |
| jsonError(w, status, msg) |
| return |
| } |
| @@ -157,13 +158,37 @@ func (s *Server) handleAPIBillingProblemClose(w http.ResponseWriter, r *http.Req |
| writeJSON(w, http.StatusOK, s.billingProblemReplyFor(*closed)) |
| } |
| +// closeBillingProblem closes problem p under its account's billing hold, the |
| +// hold every sync of that account takes: it looks the account up, takes the |
| +// hold and runs closeBillingProblemLocked. A problem with no account (an |
| +// unknown customer) is closed without a hold. |
| +func (s *Server) closeBillingProblem(ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) { |
| + if p.AccountID != 0 { |
| + acct, err := s.store.AccountByID(p.AccountID) |
| + if err != nil { |
| + log.Printf("console: api billing close %d: account: %v", p.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + if acct != nil { |
| + h, release := s.holdBilling(acct.Sqid) |
| + defer release() |
| + return s.closeBillingProblemLocked(h, ctx, p, addr, note, now) |
| + } |
| + } |
| + return s.closeBillingProblemLocked(billingHold{}, ctx, p, addr, note, now) |
| +} |
| + |
| // closeBillingProblemLocked closes problem p under its account's billing |
| -// lock, the lock every sync of that account holds: it re-reads the problem |
| -// (a sync may have resolved it), makes the deciding provider read there, |
| -// refuses while the subscription is live, and for a missing subscription |
| -// the provider still has no record of, ends it in the same critical |
| -// section. It answers the HTTP status and, for a refusal, the door copy. |
| -func (s *Server) closeBillingProblemLocked(ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) { |
| +// hold: it re-reads the problem (a sync may have resolved it), makes the |
| +// deciding provider read there, refuses 6a's reasons while the subscription |
| +// is live, and for a missing subscription the provider still has no record |
| +// of, ends it in the same critical section. An operation_unresolved problem |
| +// (Call 17) closes when the fresh read shows the operation's target (then |
| +// applied), or on the operator's note saying what the Dashboard request log |
| +// shows: executed without the target visible is a 409; not-executed records |
| +// the operation abandoned. It answers the HTTP status and, for a refusal, |
| +// the door copy. |
| +func (s *Server) closeBillingProblemLocked(h billingHold, ctx context.Context, p *billingProblem, addr, note string, now time.Time) (int, string) { |
| var acct *Account |
| if p.AccountID != 0 { |
| a, err := s.store.AccountByID(p.AccountID) |
| @@ -173,9 +198,6 @@ func (s *Server) closeBillingProblemLocked(ctx context.Context, p *billingProble |
| } |
| acct = a |
| } |
| - if acct != nil { |
| - defer s.billing.locks.lock(acct.Sqid)() |
| - } |
| cur, err := s.store.BillingProblem(p.ID) |
| if err != nil { |
| log.Printf("console: api billing close %d: %v", p.ID, err) |
| @@ -188,11 +210,12 @@ func (s *Server) closeBillingProblemLocked(ctx context.Context, p *billingProble |
| return http.StatusConflict, billingCopyClosed |
| } |
| if cur.Subscription != "" { |
| + ctx = s.billingClock(ctx) |
| sub, err := s.billing.cfg.Provider.Subscription(ctx, cur.Subscription) |
| switch { |
| case errors.Is(err, billing.ErrNotFound): |
| if cur.Reason == problemSubscriptionMissing && acct != nil { |
| - if err := s.endMissingSubscriptionLocked(ctx, acct, cur.Subscription, now); err != nil { |
| + if err := s.endMissingSubscriptionLocked(h, ctx, acct, cur.Subscription, now); err != nil { |
| log.Printf("console: api billing close %d: ending the missing subscription: %v", p.ID, err) |
| return http.StatusInternalServerError, billingCopyFailed |
| } |
| @@ -200,7 +223,11 @@ func (s *Server) closeBillingProblemLocked(ctx context.Context, p *billingProble |
| case err != nil: |
| log.Printf("console: api billing close %d: reading subscription: %v", p.ID, err) |
| return http.StatusServiceUnavailable, billingCopyProviderDown |
| - case sub.Live: |
| + case cur.Reason == problemOperationUnresolved: |
| + if status, msg := s.closeUnresolvedOpLocked(h, acct, sub, note, now); status != http.StatusOK { |
| + return status, msg |
| + } |
| + case sub.Live && !problemClosableWhileLive(cur.Reason): |
| return http.StatusConflict, billingCopyStillLive |
| } |
| } |
| @@ -213,3 +240,48 @@ func (s *Server) closeBillingProblemLocked(ctx context.Context, p *billingProble |
| } |
| return http.StatusOK, "" |
| } |
| + |
| +// closeUnresolvedOpLocked is the operation_unresolved close's evidence check |
| +// (Call 17), under the hold and after a fresh read of the subscription: the |
| +// target visible settles the operation applied and the close goes ahead; |
| +// otherwise the note must start with what the Dashboard request log shows, |
| +// "executed" (a 409 while the target is not visible: the subscription must |
| +// be put right first) or "not-executed" (the operation is abandoned). |
| +func (s *Server) closeUnresolvedOpLocked(h billingHold, acct *Account, sub *billing.Subscription, note string, now time.Time) (int, string) { |
| + _, _ = h, acct |
| + op, err := s.store.OutstandingOp(sub.ID) |
| + if err != nil { |
| + log.Printf("console: api billing close: operation of %s: %v", sub.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + if op == nil || (op.State != opSending && op.State != opUnresolved) { |
| + return http.StatusOK, "" // settled meanwhile: nothing left to decide |
| + } |
| + if targetMet(op.Target, sub) { |
| + if err := s.store.MarkOpApplied(op.ID, sub.PeriodEnd, now); err != nil { |
| + log.Printf("console: api billing close: applying %s: %v", op.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + return http.StatusOK, "" |
| + } |
| + word := strings.ToLower(strings.TrimSpace(note)) |
| + if i := strings.IndexAny(word, " \t\n.,;:"); i >= 0 { |
| + word = word[:i] |
| + } |
| + switch word { |
| + case "executed": |
| + return http.StatusConflict, billingCopyOpExecutedUnseen |
| + case "not-executed": |
| + if op.State == opSending { |
| + if err := s.store.AdoptOrphanedSending(op.ID, now); err != nil { |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + } |
| + if err := s.store.PutBillingOpState(op.ID, opAbandoned, false, now); err != nil { |
| + log.Printf("console: api billing close: abandoning %s: %v", op.ID, err) |
| + return http.StatusInternalServerError, billingCopyFailed |
| + } |
| + return http.StatusOK, "" |
| + } |
| + return http.StatusConflict, billingCopyOpEvidence |
| +} |
diff --git a/internal/console/apibilling_copy.go b/internal/console/apibilling_copy.go| index 36e3b4802..6fee55f80 100644 |
| --- a/internal/console/apibilling_copy.go |
| +++ b/internal/console/apibilling_copy.go |
| @@ -10,4 +10,8 @@ const ( |
| billingCopyClosed = "this problem is already closed" |
| billingCopyProviderDown = "the billing provider did not answer. try again in a minute" |
| billingCopyFailed = "could not read or save billing problems. try again" |
| + // Plans 6b drafts (Call 17), for the operation_unresolved close; the Luna |
| + // pass replaces them. |
| + billingCopyOpEvidence = "start -note with executed or not-executed, from the request log in the stripe dashboard" |
| + billingCopyOpExecutedUnseen = "the request log says it executed, but the subscription does not show it. put the subscription right in stripe first, then close" |
| ) |
diff --git a/internal/console/billing.go b/internal/console/billing.go| index 1319b6aa0..c7f18542b 100644 |
| --- a/internal/console/billing.go |
| +++ b/internal/console/billing.go |
| @@ -1,7 +1,9 @@ |
| package console |
| import ( |
| + "context" |
| "sync/atomic" |
| + "time" |
| "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/plans" |
| @@ -30,6 +32,13 @@ type billingRuntime struct { |
| cfg *BillingConfig |
| ready atomic.Bool |
| locks keyedLocks |
| + // monotonic is the monotonic source every request's ClockRecorder reads |
| + // (plans 6b, Invariant 9): nil is the process's own clock; tests inject |
| + // the Fake's so provider time can be aged without waiting. |
| + monotonic func() time.Duration |
| + // wait is the in-handler retry backoff (Call 17): nil sleeps on the |
| + // console clock, honouring ctx; tests replace it. |
| + wait func(ctx context.Context, d time.Duration) |
| } |
| func newBillingRuntime(cfg *BillingConfig) *billingRuntime { |
diff --git a/internal/console/billinghold.go b/internal/console/billinghold.go| new file mode 100644 |
| index 000000000..e392c9e37 |
| --- /dev/null |
| +++ b/internal/console/billinghold.go |
| @@ -0,0 +1,138 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// The billing hold and provider time (plans 6b). |
| +// |
| +// Every piece of billing work on an account runs under that account's |
| +// billing lock, and the lock is taken in exactly one place: holdBilling. A |
| +// function that needs the lock held takes a billingHold as its first |
| +// parameter, which only holdBilling can mint, and never takes the lock |
| +// itself (TestBillingLockedHelpersNeverLock). Lock order: member, then |
| +// billing, then lapse, then the store. |
| +// |
| +// Every safety decision in billing (when a request may be resent, whether a |
| +// restore is far enough from the renewal, when a verification has stalled) |
| +// is made in provider time, never on the console's wall clock (Invariant 9). |
| +// Provider time comes from a request-scoped billing.ClockRecorder, fed by |
| +// the Date header of every provider response the adapter gets through the |
| +// request's context; when no observation at most observationMaxAge old |
| +// exists, providerNow makes one clock probe, and when that fails too there is |
| +// no provider time and nothing is sent. |
| + |
| +// billingHold is proof that its holder has the account's billing lock. Only |
| +// holdBilling makes one. |
| +type billingHold struct{ sqid string } |
| + |
| +const ( |
| + // restoreMargin: a restore (a free raise back to the period's paid |
| + // quantity) is first sent or resent only while the period end is more |
| + // than this far ahead in provider time (Invariant 4). |
| + restoreMargin = 25 * time.Hour |
| + // resendLifetime: a stored request is resent under its key only while |
| + // provider time is within this of its first send. The provider keeps a |
| + // key for at least 24 hours on its own clock; FirstSentAt is a provider |
| + // timestamp taken before the send, so the window can only be shorter |
| + // than the provider's, never longer (Invariant 9). |
| + resendLifetime = 22 * time.Hour |
| + // periodMargin: a subscription operation is not resent within this of |
| + // the period end, so a request prepared for one period never first |
| + // applies in the next by our hand. |
| + periodMargin = time.Hour |
| + // observationMaxAge is how long one provider Date observation stays |
| + // usable, on the monotonic clock. |
| + observationMaxAge = billing.ProviderTimeMaxAge |
| + // handlerRetries is how many times a handler retries a send whose |
| + // outcome is unknown (no response, 409 in flight, 429), each after a |
| + // read (Call 17): about 7 s of backoff in all. |
| + handlerRetries = 3 |
| +) |
| + |
| +// handlerBackoff is the wait before retry n (1-based): 1, 2, 4 s. |
| +func handlerBackoff(n int) time.Duration { |
| + return time.Second << (n - 1) |
| +} |
| + |
| +// billingRefusal is a request refused by a billing rule, carrying the |
| +// billingCopy key the page shows. It is an error so refusals travel through |
| +// ordinary returns. |
| +type billingRefusal struct{ Key string } |
| + |
| +func (r billingRefusal) Error() string { return "billing: refused: " + r.Key } |
| + |
| +// holdBilling takes the account's billing lock and returns the hold and its |
| +// release. It is the only place the billing lock is taken. |
| +// |
| +// h, release := s.holdBilling(acct.Sqid) |
| +// defer release() |
| +func (s *Server) holdBilling(sqid string) (billingHold, func()) { |
| + release := s.billing.locks.lock(sqid) |
| + return billingHold{sqid: sqid}, release |
| +} |
| + |
| +// billingClock is ctx with a provider-time recorder for one request or one |
| +// pass round. A context already carrying one is returned as it is, so a |
| +// round's observations are shared by every decision in it. |
| +func (s *Server) billingClock(ctx context.Context) context.Context { |
| + if billing.ClockFrom(ctx) != nil { |
| + return ctx |
| + } |
| + rec := &billing.ClockRecorder{} |
| + if s.billing != nil { |
| + rec.Monotonic = s.billing.monotonic |
| + } |
| + return billing.WithClock(ctx, rec) |
| +} |
| + |
| +// providerNow is provider time for a decision: the recorder's observation |
| +// when it is at most observationMaxAge old, else one clock probe (a price |
| +// GET) observed into the same recorder, else billing.ErrNoProviderTime. A |
| +// context without a recorder has no provider time. |
| +func (s *Server) providerNow(ctx context.Context) (time.Time, error) { |
| + rec := billing.ClockFrom(ctx) |
| + if rec == nil { |
| + return time.Time{}, fmt.Errorf("%w: no recorder on the context", billing.ErrNoProviderTime) |
| + } |
| + if t, err := rec.Now(); err == nil { |
| + return t, nil |
| + } |
| + if err := s.billing.cfg.Provider.ClockProbe(ctx); err != nil { |
| + return time.Time{}, fmt.Errorf("%w: probe: %w", billing.ErrNoProviderTime, err) |
| + } |
| + t, err := rec.Now() |
| + if err != nil { |
| + return time.Time{}, fmt.Errorf("%w: the probe carried no date", billing.ErrNoProviderTime) |
| + } |
| + return t, nil |
| +} |
| + |
| +// waitBackoff sleeps the handler backoff on the console clock (a console- |
| +// local timer, never compared with provider time), or returns early when ctx |
| +// ends. |
| +func (s *Server) waitBackoff(ctx context.Context, d time.Duration) { |
| + if s.billing.wait != nil { |
| + s.billing.wait(ctx, d) |
| + return |
| + } |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + case <-t.C: |
| + } |
| +} |
| + |
| +// errNoProviderTimeRefusal is the refusal a request answers when a decision |
| +// needed provider time and none was available. |
| +var errNoProviderTimeRefusal = billingRefusal{Key: "change.clock"} |
| + |
| +// isNoProviderTime reports whether err is the missing-provider-time |
| +// condition, from the recorder or a failed probe. |
| +func isNoProviderTime(err error) bool { return errors.Is(err, billing.ErrNoProviderTime) } |
diff --git a/internal/console/billinglate.go b/internal/console/billinglate.go| new file mode 100644 |
| index 000000000..26e24bef2 |
| --- /dev/null |
| +++ b/internal/console/billinglate.go |
| @@ -0,0 +1,330 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// Late-restore obligations (plans 6b, Risk R1). |
| +// |
| +// A restore is a free raise back to the period's paid quantity, sent well |
| +// before the period end. Nothing documented bounds when the provider |
| +// executes it, so one could first apply after the renewal and give the |
| +// account free packs or seats for the new period. Every restore therefore |
| +// writes a durable verification obligation in the same transaction as the |
| +// operation, and every later observation of the subscription runs |
| +// restoreCheckLocked until the obligation is clear or flagged. Detection |
| +// writes nothing to the provider. |
| + |
| +// The states of an obligation. |
| +const ( |
| + restoreOpen = "open" // not yet decided; checked at every observation |
| + restoreClear = "clear" // the restore applied in its own period, or never executed, or the renewal billed it |
| + restoreFlagged = "flagged" // the quantity is above what the renewal billed: restore_after_renewal is open |
| +) |
| + |
| +// restoreStallAfter is how long after the renewal (both in provider time) an |
| +// obligation still open opens restore_check_stalled for an operator. |
| +const restoreStallAfter = 7 * 24 * time.Hour |
| + |
| +// restoreCheck is one obligation: the restore's operation, its period end |
| +// (the renewal boundary), the price and quantity it restored, and once the |
| +// period has moved, the renewal invoice's quantities by price as the |
| +// baseline. Attempts and LastError record failed baseline reads; StalledAt |
| +// is the provider time the stall was first reported. |
| +type restoreCheck struct { |
| + OpID string |
| + AccountID int64 |
| + Subscription string |
| + PeriodEnd time.Time |
| + Price string |
| + Target int64 |
| + State string |
| + Baseline map[string]int64 // nil until the renewal invoice was read |
| + Attempts int |
| + LastError string |
| + CreatedAt time.Time |
| + CheckedAt time.Time |
| + StalledAt time.Time |
| +} |
| + |
| +const restoreCheckColumns = `op_id, account_id, subscription, period_end, price, target, state, baseline, attempts, last_error, created_at, checked_at, stalled_at` |
| + |
| +func scanRestoreCheck(sc interface{ Scan(...any) error }) (*restoreCheck, error) { |
| + var c restoreCheck |
| + var baseline string |
| + var periodEnd, created, checked, stalled int64 |
| + if err := sc.Scan(&c.OpID, &c.AccountID, &c.Subscription, &periodEnd, &c.Price, &c.Target, &c.State, &baseline, &c.Attempts, &c.LastError, |
| + &created, &checked, &stalled); err != nil { |
| + return nil, err |
| + } |
| + if baseline != "" { |
| + if err := json.Unmarshal([]byte(baseline), &c.Baseline); err != nil { |
| + return nil, err |
| + } |
| + } |
| + c.PeriodEnd, c.CreatedAt, c.CheckedAt, c.StalledAt = timeOrZero(periodEnd), timeOrZero(created), timeOrZero(checked), timeOrZero(stalled) |
| + return &c, nil |
| +} |
| + |
| +func (s *Store) restoreChecksWhere(where string, args ...any) ([]restoreCheck, error) { |
| + rows, err := s.db.Query(`SELECT `+restoreCheckColumns+` FROM billing_restore_checks WHERE `+where, args...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []restoreCheck |
| + for rows.Next() { |
| + c, err := scanRestoreCheck(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, *c) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// RestoreCheck is the restore operation's obligation, nil when it has none. |
| +func (s *Store) RestoreCheck(opID string) (*restoreCheck, error) { |
| + c, err := scanRestoreCheck(s.db.QueryRow(`SELECT `+restoreCheckColumns+` FROM billing_restore_checks WHERE op_id = ?`, opID)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + return c, err |
| +} |
| + |
| +// OpenRestoreChecks is every open obligation of the subscription, oldest |
| +// first. |
| +func (s *Store) OpenRestoreChecks(subscription string) ([]restoreCheck, error) { |
| + return s.restoreChecksWhere(`subscription = ? AND state = ? ORDER BY created_at, op_id`, subscription, restoreOpen) |
| +} |
| + |
| +// OpenRestoreChecksAll is up to limit open obligations across every |
| +// subscription, oldest first: the pass selects open rows directly, so a |
| +// renewal the console saved and then crashed on is still checked. |
| +func (s *Store) OpenRestoreChecksAll(limit int) ([]restoreCheck, error) { |
| + return s.restoreChecksWhere(`state = ? ORDER BY created_at, op_id LIMIT ?`, restoreOpen, limit) |
| +} |
| + |
| +// PutRestoreCheck writes an obligation's progress: its baseline, attempts, |
| +// last error and checked time, and its state, which here is only open or |
| +// clear (flagging and stalling have their own transactions). |
| +func (s *Store) PutRestoreCheck(c restoreCheck) error { |
| + if c.State != restoreOpen && c.State != restoreClear { |
| + return fmt.Errorf("billing: PutRestoreCheck writes open or clear, not %q", c.State) |
| + } |
| + baseline := "" |
| + if c.Baseline != nil { |
| + b, err := json.Marshal(c.Baseline) |
| + if err != nil { |
| + return err |
| + } |
| + baseline = string(b) |
| + } |
| + _, err := s.db.Exec(`UPDATE billing_restore_checks SET state = ?, baseline = ?, attempts = ?, last_error = ?, checked_at = ? WHERE op_id = ? AND state = ?`, |
| + c.State, baseline, c.Attempts, c.LastError, unixOrZero(c.CheckedAt), c.OpID, restoreOpen) |
| + return err |
| +} |
| + |
| +// FlagRestoreCheck sets the obligation flagged and opens restore_after_renewal |
| +// for its account and subscription, in one transaction: if either write |
| +// fails, neither commits and the obligation stays open for the next |
| +// observation. |
| +func (s *Store) FlagRestoreCheck(opID, detail string, now time.Time) error { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var accountID int64 |
| + var subscription string |
| + err = tx.QueryRow(`UPDATE billing_restore_checks SET state = ?, checked_at = ? WHERE op_id = ? AND state = ? RETURNING account_id, subscription`, |
| + restoreFlagged, now.Unix(), opID, restoreOpen).Scan(&accountID, &subscription) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := openBillingProblemTx(tx, accountID, subscription, problemRestoreAfterRenewal, detail, now); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// StallRestoreCheck records when an open obligation was first found past its |
| +// deadline (providerNow, a provider time) and opens restore_check_stalled, |
| +// in one transaction, leaving the obligation open so it is still retried. A |
| +// stall already recorded does nothing more: the problem was opened with it, |
| +// and an operator who closed it is not asked again. |
| +func (s *Store) StallRestoreCheck(opID string, providerNow time.Time) error { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var accountID int64 |
| + var subscription string |
| + var periodEnd int64 |
| + err = tx.QueryRow(`UPDATE billing_restore_checks SET stalled_at = ? WHERE op_id = ? AND state = ? AND stalled_at = 0 RETURNING account_id, subscription, period_end`, |
| + providerNow.Unix(), opID, restoreOpen).Scan(&accountID, &subscription, &periodEnd) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + detail := fmt.Sprintf("restore %s has not been verified %s after the renewal of %s", opID, |
| + restoreStallAfter.String(), time.Unix(periodEnd, 0).UTC().Format(time.RFC3339)) |
| + if _, err := openBillingProblemTx(tx, accountID, subscription, problemRestoreCheckStalled, detail, providerNow); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// restoreCheckLocked runs every open obligation of the subscription against |
| +// a fresh read of it (Risk R1): |
| +// |
| +// 1. the restore's operation terminal and proved in its own period |
| +// (applied with the obligation's period end), or proved never executed |
| +// (failed, abandoned): clear; |
| +// 2. the read's period end still the obligation's: nothing yet; |
| +// 3. no baseline stored: read the renewal invoice for the period starting |
| +// at the obligation's period end, once; a failure counts an attempt and |
| +// leaves the obligation open; |
| +// 4. with a baseline: the item's quantity above it, not explained by an |
| +// applied operation first sent in the new period, is flagged, together |
| +// with its problem; otherwise a terminal operation clears, a live one |
| +// stays open; |
| +// 5. an obligation still open past PeriodEnd + restoreStallAfter in provider |
| +// time (the recorder, else one probe) is stalled; with no provider time |
| +// the stall waits for the next observation. |
| +// |
| +// It writes nothing to the provider. |
| +func (s *Server) restoreCheckLocked(h billingHold, ctx context.Context, acct *Account, sub *billing.Subscription, now time.Time) error { |
| + _, _ = h, acct |
| + open, err := s.store.OpenRestoreChecks(sub.ID) |
| + if err != nil || len(open) == 0 { |
| + return err |
| + } |
| + cfg := s.billing.cfg |
| + for _, c := range open { |
| + op, err := s.store.BillingOp(c.OpID) |
| + if err != nil { |
| + return err |
| + } |
| + if op == nil { |
| + return fmt.Errorf("billing: restore obligation %s has no operation", c.OpID) |
| + } |
| + terminal := opTerminal(op.State) |
| + if terminal && (op.State != opApplied || op.AppliedPeriodEnd.Equal(c.PeriodEnd)) { |
| + c.State, c.CheckedAt = restoreClear, now |
| + if err := s.store.PutRestoreCheck(c); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + if sub.PeriodEnd.Equal(c.PeriodEnd) { |
| + continue |
| + } |
| + if c.Baseline == nil { |
| + inv, err := cfg.Provider.RenewalInvoice(ctx, sub.ID, c.PeriodEnd) |
| + c.CheckedAt = now |
| + if err != nil { |
| + c.Attempts++ |
| + c.LastError = err.Error() |
| + if err := s.store.PutRestoreCheck(c); err != nil { |
| + return err |
| + } |
| + if err := s.stallIfDue(ctx, c); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + c.Baseline = inv.ByPrice |
| + if c.Baseline == nil { |
| + c.Baseline = map[string]int64{} |
| + } |
| + if err := s.store.PutRestoreCheck(c); err != nil { |
| + return err |
| + } |
| + } |
| + var current int64 |
| + itemID := c.Price |
| + for _, it := range sub.Items { |
| + if it.PriceID == c.Price { |
| + current += it.Quantity |
| + if it.ItemID != "" { |
| + itemID = it.ItemID |
| + } |
| + } |
| + } |
| + billed := c.Baseline[c.Price] |
| + if current > billed { |
| + explained, err := s.raiseExplained(sub.ID, c.Price, c.PeriodEnd, current) |
| + if err != nil { |
| + return err |
| + } |
| + if !explained { |
| + if err := s.store.FlagRestoreCheck(c.OpID, fmt.Sprintf("item %s is at %d, the renewal billed %d", itemID, current, billed), now); err != nil { |
| + return err |
| + } |
| + log.Printf("console: billing: restore %s on %s first applied after the renewal: item %s is at %d, the renewal billed %d", c.OpID, sub.ID, itemID, current, billed) |
| + continue |
| + } |
| + } |
| + if terminal { |
| + c.State, c.CheckedAt = restoreClear, now |
| + if err := s.store.PutRestoreCheck(c); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + c.CheckedAt = now |
| + if err := s.store.PutRestoreCheck(c); err != nil { |
| + return err |
| + } |
| + if err := s.stallIfDue(ctx, c); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// raiseExplained reports whether a quantity above the renewal's baseline is |
| +// accounted for by an applied operation first sent in the new period whose |
| +// target reaches it. |
| +func (s *Server) raiseExplained(subscription, price string, periodEnd time.Time, current int64) (bool, error) { |
| + ops, err := s.store.AppliedOpsSince(subscription, periodEnd) |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, op := range ops { |
| + if q, ok := op.Target.Quantities[price]; ok && q >= current { |
| + return true, nil |
| + } |
| + } |
| + return false, nil |
| +} |
| + |
| +// stallIfDue stalls an obligation still open once provider time is past its |
| +// deadline. The decision needs provider time: the recorder's observation, or |
| +// one probe; with none it waits for the next observation. |
| +func (s *Server) stallIfDue(ctx context.Context, c restoreCheck) error { |
| + pnow, err := s.providerNow(ctx) |
| + if err != nil { |
| + log.Printf("console: billing: restore %s: no provider time for the stall deadline; decided at the next observation", c.OpID) |
| + return nil |
| + } |
| + if !pnow.After(c.PeriodEnd.Add(restoreStallAfter)) { |
| + return nil |
| + } |
| + return s.store.StallRestoreCheck(c.OpID, pnow) |
| +} |
diff --git a/internal/console/billinglate_test.go b/internal/console/billinglate_test.go| new file mode 100644 |
| index 000000000..5d6c4e4e5 |
| --- /dev/null |
| +++ b/internal/console/billinglate_test.go |
| @@ -0,0 +1,542 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/billing/billingtest" |
| +) |
| + |
| +// newRestoreFixture is an ops fixture whose account paid for three apps |
| +// packs this period and now holds one: a restore to 3 is free (Invariant 4). |
| +func newRestoreFixture(t *testing.T) *opsFixture { |
| + t.Helper() |
| + o := newOpsFixture(t, map[string]int64{"apps": 3}) |
| + o.setQuantity("sub_1", o.packItem(t, "sub_1", "apps").PriceID, 1) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.reset() |
| + return o |
| +} |
| + |
| +func (o *opsFixture) restoreOp(t *testing.T, id, subID string) billingOp { |
| + t.Helper() |
| + return o.packOp(t, id, subID, "apps", 3, billing.ProrateNone, opRestore) |
| +} |
| + |
| +func (o *opsFixture) check(t *testing.T, opID string) *restoreCheck { |
| + t.Helper() |
| + c, err := o.st.RestoreCheck(opID) |
| + if err != nil || c == nil { |
| + t.Fatalf("restore check %s: %v", opID, err) |
| + } |
| + return c |
| +} |
| + |
| +// heldRestore sends a restore the provider will only apply at the next |
| +// renewal (Risk R1): the handler's send and retries end unresolved. |
| +func (o *opsFixture) heldRestore(t *testing.T, id, subID string) billingOp { |
| + t.Helper() |
| + o.observe() |
| + op := o.restoreOp(t, id, subID) |
| + o.fake.ApplyAfterRenewal(op.Prepared.Key) |
| + h, release := o.srv.holdBilling(o.sqidOf(t, subID)) |
| + out, _, err := o.srv.sendOpLocked(h, o.ctx, op, billingNow) |
| + release() |
| + if err != nil || out.State != opUnresolved { |
| + t.Fatalf("held restore: outcome %+v %v", out, err) |
| + } |
| + return op |
| +} |
| + |
| +func (o *opsFixture) sqidOf(t *testing.T, subID string) string { |
| + t.Helper() |
| + a, err := o.st.AccountByID(o.accountOf(t, subID)) |
| + if err != nil || a == nil { |
| + t.Fatal(err) |
| + } |
| + return a.Sqid |
| +} |
| + |
| +// secondAccount is another account, bound to cus_2 with sub_2 in the same |
| +// shape as the fixture's: paid for three apps packs, holding one. |
| +func (o *opsFixture) secondAccount(t *testing.T) *Account { |
| + t.Helper() |
| + acct := planAccount(t, o.consoleFixture, 502) |
| + if err := o.st.SetBillingCustomer(acct.ID, "cus_2", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.put(testPersonalSub("sub_2", "cus_2", acct.Sqid, "active", map[string]int64{"apps": 3})) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_2", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.setQuantity("sub_2", o.packItem(t, "sub_2", "apps").PriceID, 1) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_2", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.reset() |
| + return acct |
| +} |
| + |
| +func (o *opsFixture) invoiceLookups() (int, int) { |
| + c := o.counts() |
| + return c["RenewalInvoice"], c["RenewalInvoiceLines"] |
| +} |
| + |
| +func TestRestoreCheckClearsWhenAppliedInPeriod(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.observe() |
| + op := o.restoreOp(t, "op_1", "sub_1") |
| + out, sub, err := o.send(t, op) |
| + if err != nil || out.State != opApplied || sub == nil || !sub.PeriodEnd.Equal(periodEnd) { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + if c := o.check(t, "op_1"); c.State != restoreClear || c.Price != o.packItem(t, "sub_1", "apps").PriceID || c.Target != 3 || !c.PeriodEnd.Equal(periodEnd) { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 1}) |
| + if row := o.op(t, "op_1"); !row.AppliedPeriodEnd.Equal(periodEnd) { |
| + t.Fatalf("row = %+v", row) |
| + } |
| +} |
| + |
| +// Review Focus 5: a restore that first applies after renewal is detected as |
| +// restore_after_renewal, with no provider write. |
| +func TestLateRestoreDetected(t *testing.T) { |
| + t.Run("held_until_renewal", func(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + op := o.heldRestore(t, "op_1", "sub_1") |
| + wantCounts(t, o.counts(), map[string]int{"Send": 4, "Subscription": 3}) |
| + if c := o.check(t, "op_1"); c.State != restoreOpen { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + if err := o.fake.Renew("sub_1"); err != nil { // the invoice bills 1; then the held request applies |
| + t.Fatal(err) |
| + } |
| + if o.packItem(t, "sub_1", "apps").Quantity != 3 { |
| + t.Fatal("the Fake did not apply the held restore") |
| + } |
| + o.pass(billingNow) |
| + c := o.check(t, "op_1") |
| + if c.State != restoreFlagged || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + open, _ := o.st.BillingProblems(false) |
| + var detail string |
| + for _, p := range open { |
| + if p.Reason == problemRestoreAfterRenewal { |
| + detail = p.Detail |
| + } |
| + } |
| + if want := fmt.Sprintf("item %s is at 3, the renewal billed 1", o.packItem(t, "sub_1", "apps").ItemID); detail != want { |
| + t.Fatalf("problems = %+v, want %q", open, want) |
| + } |
| + if v, l := o.invoiceLookups(); v != 1 || l != 1 { |
| + t.Fatalf("invoice lookups = %d pages, %d line pages, want one lookup", v, l) |
| + } |
| + if o.fake.Writes() != 4 { |
| + t.Fatalf("writes = %d, want the handler's", o.fake.Writes()) |
| + } |
| + // Later observations neither re-read the invoice nor re-flag. |
| + o.pass(billingNow.Add(time.Hour)) |
| + if v, l := o.invoiceLookups(); v != 1 || l != 1 { |
| + t.Fatalf("a flagged obligation was read again: %d %d", v, l) |
| + } |
| + _ = op |
| + }) |
| + t.Run("applies_after_first_observation", func(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.observe() |
| + op := o.restoreOp(t, "op_1", "sub_1") |
| + // Lost, and still processing through three retries (six requests); |
| + // it lands as the first observation's last request (two sync reads, |
| + // an invoice page and a line page) is answered. |
| + o.fake.CompleteLater(10) |
| + if out, _, err := o.send(t, op); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + c := o.check(t, "op_1") |
| + if c.State != restoreOpen || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("after the first observation: %+v", c) |
| + } |
| + if o.packItem(t, "sub_1", "apps").Quantity != 3 { |
| + t.Fatal("the delayed apply did not land") |
| + } |
| + o.pass(billingNow.Add(time.Hour)) |
| + if c := o.check(t, "op_1"); c.State != restoreFlagged { |
| + t.Fatalf("after the delayed apply: %+v", c) |
| + } |
| + if got := o.openProblems(t); !slices.Contains(got, problemRestoreAfterRenewal) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if v, l := o.invoiceLookups(); v != 1 || l != 1 { |
| + t.Fatalf("invoice lookups = %d %d", v, l) |
| + } |
| + if o.fake.Writes() != 4 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| + }) |
| +} |
| + |
| +func TestRestoreCheckSurvivesInvoiceReadFailure(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.fake.InvoiceReadFails(2) |
| + for i := 1; i <= 2; i++ { |
| + o.pass(billingNow.Add(time.Duration(i) * time.Hour)) |
| + c := o.check(t, "op_1") |
| + if c.State != restoreOpen || c.Attempts != i || c.LastError == "" || c.Baseline != nil { |
| + t.Fatalf("observation %d: %+v", i, c) |
| + } |
| + } |
| + o.pass(billingNow.Add(3 * time.Hour)) |
| + if c := o.check(t, "op_1"); c.State != restoreFlagged || c.Attempts != 2 { |
| + t.Fatalf("third observation: %+v", c) |
| + } |
| + if v, l := o.invoiceLookups(); v != 3 || l != 1 { |
| + t.Fatalf("invoice lookups = %d %d", v, l) |
| + } |
| +} |
| + |
| +func TestRestoreCheckSurvivesCrashAfterSync(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The read is applied and saved (the row now records the new period), |
| + // then the console dies before the check. |
| + prev, _ := o.st.BillingAccount(o.acct.ID) |
| + sub, err := o.fake.Subscription(context.Background(), "sub_1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.srv.applyBillingRead(context.Background(), o.acct, prev, sub, billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b, _ := o.st.BillingAccount(o.acct.ID); !b.PaidPeriodEnd.Equal(sub.PeriodEnd) { |
| + t.Fatalf("row = %+v", b) |
| + } |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || c.Baseline != nil { |
| + t.Fatalf("obligation before the crash: %+v", c) |
| + } |
| + o.restart(t) |
| + // The restore pass selects open obligations, not period changes. |
| + o.srv.billingRestorePass(o.srv.billingClock(context.Background()), billingNow.Add(time.Hour), map[string]bool{}) |
| + if c := o.check(t, "op_1"); c.State != restoreFlagged { |
| + t.Fatalf("after the restart: %+v", c) |
| + } |
| +} |
| + |
| +func TestRestoreCheckBaselineIgnoresLaterInvoices(t *testing.T) { |
| + t.Run("stored_baseline", func(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + op := o.restoreOp(t, "op_1", "sub_1") |
| + o.unresolved(t, op) |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + c := o.check(t, "op_1") |
| + if c.State != restoreOpen || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("after the first observation: %+v", c) |
| + } |
| + // A proration invoice replaces the latest invoice, and the request |
| + // lands late. |
| + o.fake.AddInvoice(&billingtest.Invoice{Subscription: "sub_1", Reason: billingtest.ReasonUpdate, PeriodStart: o.providerClock(), |
| + Lines: []billing.Item{{PriceID: c.Price, Quantity: 3}}}) |
| + o.setQuantity("sub_1", c.Price, 3) |
| + o.pass(billingNow.Add(time.Hour)) |
| + c = o.check(t, "op_1") |
| + if c.State != restoreFlagged || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("after the late apply: %+v", c) |
| + } |
| + if v, l := o.invoiceLookups(); v != 1 || l != 1 { |
| + t.Fatalf("invoice lookups = %d %d, want the baseline read only", v, l) |
| + } |
| + }) |
| + t.Run("explained_by_a_new_period_op", func(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + op := o.restoreOp(t, "op_1", "sub_1") |
| + o.unresolved(t, op) |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + if c := o.check(t, "op_1"); c.State != restoreOpen { |
| + t.Fatalf("%+v", c) |
| + } |
| + // The operator finds it never executed; then a charged add in the |
| + // new period raises the quantity. |
| + if err := o.st.PutBillingOpState("op_1", opAbandoned, false, billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.fresh() |
| + o.observe() |
| + if out, _, err := o.send(t, o.packOp(t, "op_2", "sub_1", "apps", 4, billing.ProrateNow, opPack)); err != nil || out.State != opApplied { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + o.pass(billingNow.Add(time.Hour)) |
| + if c := o.check(t, "op_1"); c.State != restoreClear { |
| + t.Fatalf("explained raise flagged: %+v", c) |
| + } |
| + if got := o.openProblems(t); slices.Contains(got, problemRestoreAfterRenewal) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + }) |
| +} |
| + |
| +func TestRestoreCheckStalls(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.fake.InvoiceReadFails(100) |
| + o.fake.AdvanceProvider(6 * 24 * time.Hour) |
| + o.pass(billingNow) |
| + if got := o.openProblems(t); slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("stalled early: %v", got) |
| + } |
| + o.fake.AdvanceProvider(24*time.Hour + time.Minute) |
| + o.pass(billingNow.Add(time.Hour)) |
| + if got := o.openProblems(t); !slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + c := o.check(t, "op_1") |
| + if c.State != restoreOpen || !c.StalledAt.Equal(o.providerClock()) || c.Attempts != 2 { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + // Still retried: the next observation reads the invoice again. |
| + o.pass(billingNow.Add(2 * time.Hour)) |
| + if c := o.check(t, "op_1"); c.Attempts != 3 || c.State != restoreOpen { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| +} |
| + |
| +func TestRestoreStallUsesProviderTime(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.secondAccount(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + o.heldRestore(t, "op_2", "sub_2") |
| + for _, id := range []string{"sub_1", "sub_2"} { |
| + if err := o.fake.Renew(id); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + o.fake.InvoiceReadFails(100) |
| + deadline := periodEnd.Add(7 * 24 * time.Hour) |
| + behind := func() time.Time { return o.providerClock().Add(-14 * 24 * time.Hour) } |
| + ahead := func() time.Time { return o.providerClock().Add(14 * 24 * time.Hour) } |
| + observe := func(now1, now2 time.Time) { |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", now1); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.srv.syncSubscription(context.Background(), "sub_2", now2); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + o.fake.AdvanceProvider(6 * 24 * time.Hour) |
| + observe(behind(), ahead()) |
| + if got := o.openProblems(t); slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("a console clock 14 days ahead stalled early: %v", got) |
| + } |
| + // The clock is corrected and the console restarted: the deadline is the |
| + // provider's and does not move. |
| + o.restart(t) |
| + o.fake.AdvanceProvider(23 * time.Hour) |
| + observe(o.providerClock(), o.providerClock()) |
| + if got := o.openProblems(t); slices.Contains(got, problemRestoreCheckStalled) { |
| + t.Fatalf("stalled before the provider deadline: %v", got) |
| + } |
| + o.fake.AdvanceProvider(time.Hour + time.Minute) |
| + observe(behind(), ahead()) |
| + open, _ := o.st.BillingProblems(false) |
| + stalled := 0 |
| + for _, p := range open { |
| + if p.Reason == problemRestoreCheckStalled { |
| + stalled++ |
| + } |
| + } |
| + if stalled != 2 { |
| + t.Fatalf("stalled problems = %d of %+v", stalled, open) |
| + } |
| + for _, id := range []string{"op_1", "op_2"} { |
| + if c := o.check(t, id); !c.StalledAt.After(deadline) || c.StalledAt.Sub(deadline) > 2*time.Minute { |
| + t.Fatalf("%s stalled at %v, deadline %v", id, c.StalledAt, deadline) |
| + } |
| + } |
| +} |
| + |
| +func TestFlagAndProblemCommitTogether(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := o.st.db.Exec(`CREATE TRIGGER fail_problem BEFORE INSERT ON billing_problems BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + if c := o.check(t, "op_1"); c.State != restoreOpen || c.Baseline[c.Price] != 1 { |
| + t.Fatalf("obligation with the problem write failing: %+v", c) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if _, err := o.st.db.Exec(`DROP TRIGGER fail_problem`); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.restart(t) |
| + o.pass(billingNow.Add(time.Hour)) |
| + if c := o.check(t, "op_1"); c.State != restoreFlagged { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + if got := o.openProblems(t); !slices.Contains(got, problemRestoreAfterRenewal) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if v, _ := o.invoiceLookups(); v != 1 { |
| + t.Fatalf("the baseline was read %d times", v) |
| + } |
| +} |
| + |
| +func TestLateRestoreNotFlaggedWhenBilled(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.observe() |
| + op := o.restoreOp(t, "op_1", "sub_1") |
| + o.fake.CrashAfterSend = true // applied in this period; the console never recorded it |
| + if _, _, err := o.send(t, op); err == nil { |
| + t.Fatal("expected the crash") |
| + } |
| + if err := o.fake.Renew("sub_1"); err != nil { // the renewal bills 3 |
| + t.Fatal(err) |
| + } |
| + o.restart(t) |
| + o.pass(billingNow) |
| + if row := o.op(t, "op_1"); row.State != opApplied || row.AppliedPeriodEnd.Equal(periodEnd) { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if c := o.check(t, "op_1"); c.State != restoreClear || c.Baseline[c.Price] != 3 { |
| + t.Fatalf("obligation = %+v", c) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +// Three decisions on one account, all needing provider time, within 60 s of |
| +// one probe: two stall decisions and one escalation. |
| +func TestPassSharesAFreshObservation(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + price := o.packItem(t, "sub_1", "apps").PriceID |
| + p2 := periodEnd.AddDate(1, 0, 0) |
| + for _, id := range []string{"op_a", "op_b"} { |
| + op := o.restoreOp(t, id, "sub_1") |
| + op.FirstSentAt, op.State = o.providerClock(), opSending |
| + if err := o.st.BeginBillingOp(op); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Applied, but only seen in the next period: the obligation stays open. |
| + if err := o.st.MarkOpApplied(id, p2, billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + indeterminate := o.packOp(t, "op_c", "sub_1", "apps", 4, billing.ProrateNow, opPack) |
| + o.unresolved(t, indeterminate) |
| + if err := o.st.PutBillingOpState("op_c", opUnresolved, true, billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.setQuantity("sub_1", price, 1) |
| + o.fake.InvoiceReadFails(100) |
| + o.headerlessReads(true) |
| + o.pass(billingNow) |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "RenewalInvoice": 2, "ClockProbe": 1}) |
| + if got := o.openProblems(t); !slices.Equal(got, []string{problemOperationUnresolved}) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + for _, id := range []string{"op_a", "op_b"} { |
| + if c := o.check(t, id); c.State != restoreOpen || c.Attempts != 1 { |
| + t.Fatalf("%s: %+v", id, c) |
| + } |
| + } |
| +} |
| + |
| +// The second account's invoice pages are slow and headerless: by its stall |
| +// decision the round's observation is 80 s old, so it probes again. |
| +func TestPassProbesAgainAfterExpiry(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.secondAccount(t) |
| + for _, id := range []string{"sub_1", "sub_2"} { |
| + o.unresolved(t, o.restoreOp(t, "op_"+id, id)) |
| + if err := o.fake.Renew(id); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for i := 0; i < 6; i++ { |
| + o.fake.AddInvoice(&billingtest.Invoice{Subscription: "sub_2", Reason: billingtest.ReasonUpdate, PeriodStart: o.providerClock().Add(time.Duration(i+1) * time.Hour)}) |
| + } |
| + o.fake.PageSize = 1 |
| + decoy := &billing.ClockRecorder{Monotonic: func() time.Duration { o.fake.AdvanceMonotonic(10 * time.Second); return o.fake.Monotonic() }} |
| + o.srv.billing.cfg.Provider = stripDates{Provider: o.fake, reads: true, invoices: true, decoy: decoy, decoyFor: "sub_2"} |
| + o.pass(billingNow) |
| + c := o.counts() |
| + if c["ClockProbe"] != 2 { |
| + t.Fatalf("CallsBy = %v, want two probes", c) |
| + } |
| + if c["RenewalInvoice"] != 8 || c["RenewalInvoiceLines"] != 4 { |
| + t.Fatalf("CallsBy = %v, want 1 + 7 invoice pages and two line pages per renewal invoice", c) |
| + } |
| + for _, id := range []string{"op_sub_1", "op_sub_2"} { |
| + if ch := o.check(t, id); ch.State != restoreOpen || ch.Baseline == nil { |
| + t.Fatalf("%s: %+v", id, ch) |
| + } |
| + } |
| +} |
| + |
| +// The restore_after_renewal and restore_check_stalled problems are closed |
| +// while the subscription is live: the operator has fixed the quantity in the |
| +// Dashboard. |
| +func TestRestoreProblemsCloseWhileLive(t *testing.T) { |
| + o := newRestoreFixture(t) |
| + o.heldRestore(t, "op_1", "sub_1") |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + open, _ := o.st.BillingProblems(false) |
| + operator := planOperatorToken(t, o.consoleFixture, "ops@keymail.dev", "code-billing-restore-close") |
| + for _, p := range open { |
| + if p.Reason != problemRestoreAfterRenewal { |
| + continue |
| + } |
| + if status, out := postJSON(t, billingCloseURL(o.consoleFixture, p.ID), map[string]any{"note": "reduced in the dashboard"}, operator); status != http.StatusOK { |
| + t.Fatalf("close %s: %d %v", p.Reason, status, out) |
| + } |
| + } |
| + if got := o.openProblems(t); slices.Contains(got, problemRestoreAfterRenewal) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if !strings.Contains(billingCopyStillLive, "live") { |
| + t.Fatal("copy drifted") |
| + } |
| +} |
diff --git a/internal/console/billinglint_test.go b/internal/console/billinglint_test.go| new file mode 100644 |
| index 000000000..089cd6151 |
| --- /dev/null |
| +++ b/internal/console/billinglint_test.go |
| @@ -0,0 +1,351 @@ |
| +package console |
| + |
| +import ( |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The billing lint tests (plans 6b, Global Constraints): the lock discipline, |
| +// provider neutrality, the single outstanding predicate and the single |
| +// recovery gate are properties of the source, so they are checked there. |
| + |
| +// billingSourceFile is a billing file of this package: billing*.go and |
| +// apibilling*.go, tests excluded. |
| +func billingSourceFile(name string) bool { |
| + if strings.HasSuffix(name, "_test.go") { |
| + return false |
| + } |
| + return strings.HasPrefix(name, "billing") || strings.HasPrefix(name, "apibilling") |
| +} |
| + |
| +// parsePackageSources parses every non-test .go file of this package. |
| +func parsePackageSources(t *testing.T) (*token.FileSet, map[string]*ast.File) { |
| + t.Helper() |
| + names, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fset := token.NewFileSet() |
| + files := map[string]*ast.File{} |
| + for _, name := range names { |
| + if strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + src, err := os.ReadFile(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := parser.ParseFile(fset, name, src, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + files[name] = f |
| + } |
| + return fset, files |
| +} |
| + |
| +func parsePlanted(t *testing.T, fset *token.FileSet, name, src string) map[string]*ast.File { |
| + t.Helper() |
| + f, err := parser.ParseFile(fset, name, "package console\n"+src, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return map[string]*ast.File{name: f} |
| +} |
| + |
| +// exprText is a selector chain as written (s.billing.locks.lock). |
| +func exprText(e ast.Expr) string { |
| + switch x := e.(type) { |
| + case *ast.Ident: |
| + return x.Name |
| + case *ast.SelectorExpr: |
| + return exprText(x.X) + "." + x.Sel.Name |
| + case *ast.CallExpr: |
| + return exprText(x.Fun) + "()" |
| + } |
| + return "?" |
| +} |
| + |
| +func firstParamIsBillingHold(fd *ast.FuncDecl) bool { |
| + if fd.Type.Params == nil || len(fd.Type.Params.List) == 0 { |
| + return false |
| + } |
| + id, ok := fd.Type.Params.List[0].Type.(*ast.Ident) |
| + return ok && id.Name == "billingHold" && len(fd.Type.Params.List[0].Names) == 1 |
| +} |
| + |
| +func anyParamIsBillingHold(fd *ast.FuncDecl) bool { |
| + if fd.Type.Params == nil { |
| + return false |
| + } |
| + for _, p := range fd.Type.Params.List { |
| + if id, ok := p.Type.(*ast.Ident); ok && id.Name == "billingHold" { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// billingLockFindings selects (a) every function in a billing file whose name |
| +// ends in Locked and (b) every function anywhere with a billingHold parameter, |
| +// and reports each one that does not take billingHold first or that takes the |
| +// billing lock itself (holdBilling, syncSubscription, closeBillingProblem or |
| +// s.billing.locks.lock). It returns the selected names and the findings. |
| +func billingLockFindings(fset *token.FileSet, files map[string]*ast.File) (selected, findings []string) { |
| + for name, f := range files { |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok { |
| + continue |
| + } |
| + endsLocked := strings.HasSuffix(fd.Name.Name, "Locked") |
| + if !((billingSourceFile(name) && endsLocked) || anyParamIsBillingHold(fd)) { |
| + continue |
| + } |
| + selected = append(selected, fd.Name.Name) |
| + pos := fset.Position(fd.Pos()).String() |
| + if !firstParamIsBillingHold(fd) { |
| + findings = append(findings, pos+": "+fd.Name.Name+" does not take billingHold as its first parameter") |
| + } |
| + if fd.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if !ok { |
| + return true |
| + } |
| + switch sel.Sel.Name { |
| + case "holdBilling", "syncSubscription", "closeBillingProblem": |
| + findings = append(findings, fset.Position(call.Pos()).String()+": "+fd.Name.Name+" calls "+sel.Sel.Name) |
| + case "lock": |
| + if strings.HasSuffix(exprText(sel.X), "billing.locks") { |
| + findings = append(findings, fset.Position(call.Pos()).String()+": "+fd.Name.Name+" takes s.billing.locks.lock") |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + sort.Strings(selected) |
| + sort.Strings(findings) |
| + return selected, findings |
| +} |
| + |
| +// TestBillingLockedHelpersNeverLock: every *Locked helper in a billing file, |
| +// and every function taking a billingHold anywhere, takes the hold first and |
| +// never takes the lock itself. The two 6a helpers migrated by 6b are named, |
| +// and ensureLocked (a mailer helper in another file) is out of scope. |
| +func TestBillingLockedHelpersNeverLock(t *testing.T) { |
| + fset, files := parsePackageSources(t) |
| + selected, findings := billingLockFindings(fset, files) |
| + for _, f := range findings { |
| + t.Error(f) |
| + } |
| + for _, want := range []string{"closeBillingProblemLocked", "endMissingSubscriptionLocked", "syncSubscriptionLocked", "refreshLocked", |
| + "allowanceLocked", "sendOpLocked", "finishOpLocked", "settleOpsLocked", "restoreCheckLocked"} { |
| + if !slices.Contains(selected, want) { |
| + t.Errorf("%s was not selected (selected: %v)", want, selected) |
| + } |
| + } |
| + if slices.Contains(selected, "ensureLocked") { |
| + t.Error("ensureLocked (not billing code) was selected") |
| + } |
| + // The check catches what it is for: a billing-file *Locked helper with no |
| + // hold, and one that takes the lock itself. |
| + planted := parsePlanted(t, fset, "billingplanted.go", ` |
| +func (s *Server) fooLocked(ctx int) {} |
| +func (s *Server) barLocked(h billingHold) { s.holdBilling("x"); s.syncSubscription(nil, "", nil) } |
| +func (s *Server) baz(x int, h billingHold) { defer s.billing.locks.lock("x")() } |
| +`) |
| + _, got := billingLockFindings(fset, planted) |
| + if len(got) != 5 { |
| + t.Fatalf("planted findings = %d %v, want 5 (fooLocked no hold; barLocked holdBilling, syncSubscription; baz hold not first, locks.lock)", len(got), got) |
| + } |
| + // Outside billing files only the hold parameter selects. |
| + elsewhere := parsePlanted(t, fset, "mailer.go", ` |
| +func (m *mailer) ensureLocked() {} |
| +`) |
| + if sel, got := billingLockFindings(fset, elsewhere); len(sel) != 0 || len(got) != 0 { |
| + t.Fatalf("a non-billing *Locked was selected: %v %v", sel, got) |
| + } |
| +} |
| + |
| +// providerStatusWords are the provider's own status words, which stay inside |
| +// the adapter (Global Constraints: provider neutrality). |
| +var providerStatusWords = regexp.MustCompile(`\b(active|trialing|past_due|incomplete|incomplete_expired|unpaid|canceled|paused)\b`) |
| + |
| +func TestConsoleBillingHasNoProviderWords(t *testing.T) { |
| + names, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + checked := 0 |
| + for _, name := range names { |
| + if !billingSourceFile(name) { |
| + continue |
| + } |
| + checked++ |
| + src, err := os.ReadFile(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i, line := range strings.Split(string(src), "\n") { |
| + if m := providerStatusWords.FindString(line); m != "" { |
| + t.Errorf("%s:%d: provider status word %q: %s", name, i+1, m, strings.TrimSpace(line)) |
| + } |
| + } |
| + } |
| + if checked < 6 { |
| + t.Fatalf("checked only %d billing files", checked) |
| + } |
| +} |
| + |
| +// TestOpOutstandingMatchesIndex: the partial unique index on |
| +// billing_operations lists exactly the states opOutstanding is true for |
| +// (Invariant 7). |
| +func TestOpOutstandingMatchesIndex(t *testing.T) { |
| + st, err := Open(filepath.Join(t.TempDir(), "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + var ddl string |
| + if err := st.db.QueryRow(`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = 'billing_operations_outstanding'`).Scan(&ddl); err != nil { |
| + t.Fatalf("index billing_operations_outstanding: %v", err) |
| + } |
| + m := regexp.MustCompile(`(?i)state\s+IN\s*\(([^)]*)\)`).FindStringSubmatch(ddl) |
| + if m == nil { |
| + t.Fatalf("index DDL has no state IN (...) list: %s", ddl) |
| + } |
| + var indexed []string |
| + for _, s := range strings.Split(m[1], ",") { |
| + indexed = append(indexed, strings.Trim(strings.TrimSpace(s), `'"`)) |
| + } |
| + var predicate []string |
| + for _, s := range []string{opSending, opUnresolved, opPending, opApplied, opFailed, opAbandoned} { |
| + if opOutstanding(s) { |
| + predicate = append(predicate, s) |
| + } |
| + } |
| + sort.Strings(indexed) |
| + sort.Strings(predicate) |
| + if !slices.Equal(indexed, predicate) { |
| + t.Fatalf("index states %v, opOutstanding states %v", indexed, predicate) |
| + } |
| + if !slices.Equal(predicate, []string{opPending, opSending, opUnresolved}) { |
| + t.Fatalf("opOutstanding = %v, want sending, unresolved and pending", predicate) |
| + } |
| +} |
| + |
| +// sendGateFindings: in billing files, every function that calls Provider.Send |
| +// also calls recoveryEligible, and calls Send once, so no resend site exists |
| +// outside the gate (Invariant 8). |
| +func sendGateFindings(fset *token.FileSet, files map[string]*ast.File) []string { |
| + var findings []string |
| + for name, f := range files { |
| + if !billingSourceFile(name) { |
| + continue |
| + } |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + sends, gated := 0, false |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + switch fun := call.Fun.(type) { |
| + case *ast.SelectorExpr: |
| + if fun.Sel.Name == "Send" { |
| + sends++ |
| + } |
| + if fun.Sel.Name == "recoveryEligible" { |
| + gated = true |
| + } |
| + case *ast.Ident: |
| + if fun.Name == "recoveryEligible" { |
| + gated = true |
| + } |
| + } |
| + return true |
| + }) |
| + pos := fset.Position(fd.Pos()).String() |
| + if sends > 0 && !gated { |
| + findings = append(findings, pos+": "+fd.Name.Name+" sends without recoveryEligible") |
| + } |
| + if sends > 1 { |
| + findings = append(findings, pos+": "+fd.Name.Name+" has more than one Send call site") |
| + } |
| + } |
| + } |
| + sort.Strings(findings) |
| + return findings |
| +} |
| + |
| +func TestRecoveryEligibleIsTheOnlyGate(t *testing.T) { |
| + fset, files := parsePackageSources(t) |
| + for _, f := range sendGateFindings(fset, files) { |
| + t.Error(f) |
| + } |
| + planted := parsePlanted(t, fset, "billingplanted.go", ` |
| +func (s *Server) resendAnyway(p int) { s.billing.cfg.Provider.Send(nil, p) } |
| +func (s *Server) twice(p int) { recoveryEligible(p, p); s.billing.cfg.Provider.Send(nil, p); s.billing.cfg.Provider.Send(nil, p) } |
| +`) |
| + if got := sendGateFindings(fset, planted); len(got) != 2 { |
| + t.Fatalf("planted findings = %v, want an ungated send and a double send", got) |
| + } |
| + // The gate is called by the code that sends: at least sendOpLocked and |
| + // finishOpLocked. |
| + gated := 0 |
| + for name, f := range files { |
| + if !billingSourceFile(name) { |
| + continue |
| + } |
| + for _, d := range f.Decls { |
| + if fd, ok := d.(*ast.FuncDecl); ok && (fd.Name.Name == "sendOpLocked" || fd.Name.Name == "finishOpLocked") { |
| + gated++ |
| + } |
| + } |
| + } |
| + if gated != 2 { |
| + t.Fatalf("sendOpLocked and finishOpLocked: found %d", gated) |
| + } |
| +} |
| + |
| +// passSourceWrites is every Send or PortalURL call in the pass files |
| +// (billingpass.go): there must be none (Invariant 5). |
| +func passSourceWrites(t *testing.T) []string { |
| + t.Helper() |
| + fset, files := parsePackageSources(t) |
| + var found []string |
| + for name, f := range files { |
| + if name != "billingpass.go" { |
| + continue |
| + } |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + if call, ok := n.(*ast.CallExpr); ok { |
| + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "Send" || sel.Sel.Name == "PortalURL") { |
| + found = append(found, fset.Position(call.Pos()).String()+": "+sel.Sel.Name) |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + return found |
| +} |
diff --git a/internal/console/billingops.go b/internal/console/billingops.go| new file mode 100644 |
| index 000000000..b5f16c58c |
| --- /dev/null |
| +++ b/internal/console/billingops.go |
| @@ -0,0 +1,723 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/subtle" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// Billing operations (plans 6b, Invariants 1, 7, 8 and 9; Call 17). |
| +// |
| +// A subscription change is a billing_operations row holding one prepared |
| +// request: the adapter's exact bytes and idempotency key, persisted before |
| +// the first send and never edited. Finality comes from the provider, as an |
| +// idempotent result or a positive read; never from elapsed time or a |
| +// negative read. The only resend is the stored bytes under the same key, |
| +// preceded by a read, and only while recoveryEligible says so. |
| + |
| +// The states of an operation. |
| +const ( |
| + opSending = "sending" // written before the first send; seen under the hold only after a crash |
| + opUnresolved = "unresolved" // sent, no definite outcome yet |
| + opPending = "pending" // the provider holds the change as a pending update until it is paid |
| + opApplied = "applied" // the provider shows the target |
| + opFailed = "failed" // a definite refusal or decline; nothing applied |
| + opAbandoned = "abandoned" // a pending update expired, or an operator found it never executed |
| +) |
| + |
| +// opOutstanding is the one predicate deciding "outstanding" (Invariant 7): |
| +// the partial unique index, admission, change refusal, revocation and the |
| +// retirement gate all use it. |
| +func opOutstanding(state string) bool { |
| + return state == opSending || state == opUnresolved || state == opPending |
| +} |
| + |
| +// opTerminal is an operation nothing more will happen to. |
| +func opTerminal(state string) bool { |
| + return state == opApplied || state == opFailed || state == opAbandoned |
| +} |
| + |
| +// The kinds of operation. |
| +const ( |
| + opPack = "pack" // a pack quantity change (a charged raise or a free reduction) |
| + opPlan = "plan" // a plan upgrade |
| + opSeat = "seat" // a charged seat for one join |
| + opRestore = "restore" // a free raise back to the period's paid quantity |
| + opRenewal = "renewal" // stop or resume renewal |
| +) |
| + |
| +// opTarget is what a read must show for the operation to have applied: |
| +// each named price at its quantity (0: the item is gone), and, for a |
| +// renewal operation, the cancel-at-period-end flag. |
| +type opTarget struct { |
| + Quantities map[string]int64 `json:"quantities,omitempty"` |
| + Renewal bool `json:"renewal,omitempty"` |
| + CancelAtPeriodEnd bool `json:"cancel_at_period_end,omitempty"` |
| +} |
| + |
| +// targetMet is positive evidence: the read shows every part of the target. |
| +// An empty target is never met. |
| +func targetMet(t opTarget, sub *billing.Subscription) bool { |
| + if sub == nil || (len(t.Quantities) == 0 && !t.Renewal) { |
| + return false |
| + } |
| + for price, want := range t.Quantities { |
| + var have int64 |
| + for _, it := range sub.Items { |
| + if it.PriceID == price { |
| + have += it.Quantity |
| + } |
| + } |
| + if have != want { |
| + return false |
| + } |
| + } |
| + if t.Renewal && sub.CancelAtPeriodEnd != t.CancelAtPeriodEnd { |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// billingOp is one operation. Prepared is exact and never edited. PeriodEnd |
| +// is the subscription's period end when the request was prepared. |
| +// FirstSentAt is provider time stamped immediately before the first send |
| +// and written once; LastSentAt moves with each resend. AppliedPeriodEnd is |
| +// the period end of the response or read that proved the target, which |
| +// says whether a restore applied in its own period (Risk R1). |
| +type billingOp struct { |
| + ID, Subscription, Kind string |
| + AccountID int64 |
| + PeriodEnd time.Time |
| + Target opTarget |
| + Prepared billing.Prepared |
| + InviteToken string // opSeat or opRestore for one join |
| + AuthorisedBy string // the invite token whose seat authorisation an opSeat consumes |
| + State string |
| + Indeterminate bool |
| + FirstSentAt, LastSentAt, SettledAt time.Time |
| + AppliedPeriodEnd time.Time |
| + CreatedAt time.Time |
| +} |
| + |
| +// resendUntil is the end of the operation's resend window in provider time: |
| +// the key lifetime from the first send, cut off before the period end. |
| +func (op billingOp) resendUntil() time.Time { |
| + until := op.FirstSentAt.Add(resendLifetime) |
| + if !op.PeriodEnd.IsZero() && op.PeriodEnd.Add(-periodMargin).Before(until) { |
| + until = op.PeriodEnd.Add(-periodMargin) |
| + } |
| + return until |
| +} |
| + |
| +// ErrOpOutstanding refuses a second operation while one is outstanding on |
| +// the subscription. |
| +var ErrOpOutstanding = errors.New("billing: an operation is outstanding on the subscription") |
| + |
| +const billingOpColumns = `id, account_id, subscription, kind, period_end, target, prepared, invite_token, authorised_by, |
| + state, indeterminate, first_sent_at, last_sent_at, settled_at, applied_period_end, created_at` |
| + |
| +func scanBillingOp(sc interface{ Scan(...any) error }) (*billingOp, error) { |
| + var op billingOp |
| + var target, prepared []byte |
| + var periodEnd, firstSent, lastSent, settled, applied, created int64 |
| + var indeterminate int |
| + if err := sc.Scan(&op.ID, &op.AccountID, &op.Subscription, &op.Kind, &periodEnd, &target, &prepared, &op.InviteToken, &op.AuthorisedBy, |
| + &op.State, &indeterminate, &firstSent, &lastSent, &settled, &applied, &created); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal(target, &op.Target); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal(prepared, &op.Prepared); err != nil { |
| + return nil, err |
| + } |
| + op.Indeterminate = indeterminate != 0 |
| + op.PeriodEnd, op.FirstSentAt, op.LastSentAt = timeOrZero(periodEnd), timeOrZero(firstSent), timeOrZero(lastSent) |
| + op.SettledAt, op.AppliedPeriodEnd, op.CreatedAt = timeOrZero(settled), timeOrZero(applied), timeOrZero(created) |
| + return &op, nil |
| +} |
| + |
| +func (s *Store) billingOpWhere(where string, args ...any) (*billingOp, error) { |
| + op, err := scanBillingOp(s.db.QueryRow(`SELECT `+billingOpColumns+` FROM billing_operations WHERE `+where, args...)) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil, nil |
| + } |
| + return op, err |
| +} |
| + |
| +func (s *Store) billingOpsWhere(where string, args ...any) ([]billingOp, error) { |
| + rows, err := s.db.Query(`SELECT `+billingOpColumns+` FROM billing_operations WHERE `+where, args...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []billingOp |
| + for rows.Next() { |
| + op, err := scanBillingOp(rows) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, *op) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// BeginBillingOp writes the operation in state sending, with its prepared |
| +// request and its first-send stamp, before anything is sent. It refuses |
| +// with ErrOpOutstanding while an outstanding operation holds the |
| +// subscription (the partial unique index is the backstop). A restore also |
| +// writes its verification obligation (Risk R1) in the same transaction. |
| +func (s *Store) BeginBillingOp(op billingOp) error { |
| + if op.ID == "" || op.Subscription == "" || op.Prepared.Key == "" { |
| + return errors.New("billing: an operation needs an id, a subscription and a prepared request") |
| + } |
| + if op.State == "" { |
| + op.State = opSending |
| + } |
| + target, err := json.Marshal(op.Target) |
| + if err != nil { |
| + return err |
| + } |
| + prepared, err := json.Marshal(op.Prepared) |
| + if err != nil { |
| + return err |
| + } |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var n int |
| + if err := tx.QueryRow(`SELECT COUNT(*) FROM billing_operations WHERE subscription = ? AND state IN (?, ?, ?)`, |
| + op.Subscription, opSending, opUnresolved, opPending).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return ErrOpOutstanding |
| + } |
| + if _, err := tx.Exec(`INSERT INTO billing_operations (`+billingOpColumns+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| + op.ID, op.AccountID, op.Subscription, op.Kind, unixOrZero(op.PeriodEnd), target, prepared, op.InviteToken, op.AuthorisedBy, |
| + op.State, boolInt(op.Indeterminate), unixOrZero(op.FirstSentAt), unixOrZero(op.LastSentAt), unixOrZero(op.SettledAt), |
| + unixOrZero(op.AppliedPeriodEnd), unixOrZero(op.CreatedAt)); err != nil { |
| + return err |
| + } |
| + if op.Kind == opRestore { |
| + if len(op.Target.Quantities) != 1 { |
| + return errors.New("billing: a restore targets exactly one price") |
| + } |
| + for price, q := range op.Target.Quantities { |
| + if _, err := tx.Exec(`INSERT INTO billing_restore_checks (op_id, account_id, subscription, period_end, price, target, state, created_at) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, op.ID, op.AccountID, op.Subscription, unixOrZero(op.PeriodEnd), price, q, restoreOpen, unixOrZero(op.CreatedAt)); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// BillingOp is one operation, nil when there is none with that id. |
| +func (s *Store) BillingOp(id string) (*billingOp, error) { return s.billingOpWhere(`id = ?`, id) } |
| + |
| +// OutstandingOp is the subscription's outstanding operation (sending, |
| +// unresolved or pending), nil when it has none. |
| +func (s *Store) OutstandingOp(subscription string) (*billingOp, error) { |
| + return s.billingOpWhere(`subscription = ? AND state IN (?, ?, ?)`, subscription, opSending, opUnresolved, opPending) |
| +} |
| + |
| +// OutstandingBillingOps pages every outstanding operation by id after |
| +// afterID: the pass's observation list. |
| +func (s *Store) OutstandingBillingOps(afterID string, limit int) ([]billingOp, error) { |
| + return s.billingOpsWhere(`state IN (?, ?, ?) AND id > ? ORDER BY id LIMIT ?`, opSending, opUnresolved, opPending, afterID, limit) |
| +} |
| + |
| +// LatestOpForInvite is the newest operation made for the invite, nil when |
| +// none was. |
| +func (s *Store) LatestOpForInvite(token string) (*billingOp, error) { |
| + if token == "" { |
| + return nil, nil |
| + } |
| + return s.billingOpWhere(`invite_token = ? ORDER BY created_at DESC, rowid DESC LIMIT 1`, token) |
| +} |
| + |
| +// AppliedOpsSince is every applied operation of the subscription first sent |
| +// at or after since (provider time): what explains a quantity above a |
| +// renewal's baseline. |
| +func (s *Store) AppliedOpsSince(subscription string, since time.Time) ([]billingOp, error) { |
| + return s.billingOpsWhere(`subscription = ? AND state = ? AND first_sent_at >= ? ORDER BY first_sent_at, id`, subscription, opApplied, since.Unix()) |
| +} |
| + |
| +// MarkOpApplied is the only route to applied. provedPeriodEnd is the period |
| +// end of the response or read that showed the target. In one transaction it |
| +// records the state, consumes the seat authorisation the operation carried |
| +// (Invariant 2) and, when the proof is from the operation's own period, |
| +// clears its restore obligation. An operation already terminal is left as it |
| +// is, so reordered deliveries settle once. |
| +func (s *Store) MarkOpApplied(opID string, provedPeriodEnd, now time.Time) error { |
| + tx, err := s.db.Begin() |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + var authorisedBy string |
| + err = tx.QueryRow(`UPDATE billing_operations SET state = ?, indeterminate = 0, settled_at = ?, applied_period_end = ? |
| + WHERE id = ? AND state IN (?, ?, ?) RETURNING authorised_by`, opApplied, now.Unix(), unixOrZero(provedPeriodEnd), opID, opSending, opUnresolved, opPending).Scan(&authorisedBy) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if authorisedBy != "" { |
| + if err := consumeSeatAuthorisationTx(tx, authorisedBy); err != nil { |
| + return err |
| + } |
| + } |
| + if _, err := tx.Exec(`UPDATE billing_restore_checks SET state = ?, checked_at = ? WHERE op_id = ? AND state = ? AND period_end = ?`, |
| + restoreClear, now.Unix(), opID, restoreOpen, unixOrZero(provedPeriodEnd)); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// consumeSeatAuthorisationTx spends the invite's seat authorisation in the |
| +// transaction that applies the operation it authorised (Invariant 2: single |
| +// use). Seat authorisations are recorded on invites by the membership |
| +// billing work (Task 11), which fills this in; until then there is none to |
| +// consume. |
| +func consumeSeatAuthorisationTx(tx *sql.Tx, token string) error { |
| + _ = tx |
| + _ = token |
| + return nil |
| +} |
| + |
| +// PutBillingOpState moves an outstanding operation to state (never applied: |
| +// that is MarkOpApplied), recording whether the outcome is indeterminate |
| +// and, for a terminal state, when it settled. A terminal operation is left |
| +// as it is. |
| +func (s *Store) PutBillingOpState(opID, state string, indeterminate bool, now time.Time) error { |
| + if state == opApplied { |
| + return errors.New("billing: applied is recorded only by MarkOpApplied") |
| + } |
| + settled := int64(0) |
| + if opTerminal(state) { |
| + settled = now.Unix() |
| + } |
| + _, err := s.db.Exec(`UPDATE billing_operations SET state = ?, indeterminate = ?, settled_at = ? WHERE id = ? AND state IN (?, ?, ?)`, |
| + state, boolInt(indeterminate), settled, opID, opSending, opUnresolved, opPending) |
| + return err |
| +} |
| + |
| +// AdoptOrphanedSending turns a sending row into unresolved: a sending row |
| +// seen under the hold outlived the handler that wrote it (a crash), and is |
| +// treated exactly as unresolved (Invariant 9). |
| +func (s *Store) AdoptOrphanedSending(opID string, now time.Time) error { |
| + _ = now |
| + _, err := s.db.Exec(`UPDATE billing_operations SET state = ? WHERE id = ? AND state = ?`, opUnresolved, opID, opSending) |
| + return err |
| +} |
| + |
| +// NoteOpSent records a resend's provider time. FirstSentAt is never touched. |
| +func (s *Store) NoteOpSent(opID string, providerNow time.Time) error { |
| + _, err := s.db.Exec(`UPDATE billing_operations SET last_sent_at = ? WHERE id = ?`, providerNow.Unix(), opID) |
| + return err |
| +} |
| + |
| +// quantityPlan splits a raise from current to target into a free restore |
| +// (up to paidHighest, the period's highest paid quantity, Invariant 2) and a |
| +// charged step beyond it. A reduction or no change plans nothing. |
| +func quantityPlan(current, target, paidHighest int64) (restoreTo, chargeTo int64) { |
| + if target <= current { |
| + return 0, 0 |
| + } |
| + if paidHighest > current { |
| + restoreTo = min(target, paidHighest) |
| + } |
| + if target > max(current, paidHighest) { |
| + chargeTo = target |
| + } |
| + return restoreTo, chargeTo |
| +} |
| + |
| +// resendState is what recoveryEligible looks at, for an operation, a |
| +// customer create, a Checkout create or an expiry alike. FirstSent and |
| +// ResendUntil are provider times; ResendUntil is the request's own cap |
| +// (an operation's period margin, an intent's expiry), zero for none. |
| +type resendState struct { |
| + State string |
| + Indeterminate bool |
| + FirstSent time.Time |
| + ResendUntil time.Time |
| + ContextCurrent bool // the invite is still pending, the period and subscription unchanged, the intent not expired |
| + Restore bool |
| + PeriodEnd time.Time |
| +} |
| + |
| +// The reasons recoveryEligible refuses. |
| +const ( |
| + ineligibleState = "state" // already settled or pending |
| + ineligibleIndeterminate = "indeterminate" // a cached 5xx: a resend replays it (fact 5) |
| + ineligibleClock = "clock" // no provider time |
| + ineligibleWindow = "window" // past the key lifetime or the request's own cap |
| + ineligibleMargin = "margin" // a restore inside the renewal margin |
| + ineligibleContext = "context" // the request's context has gone stale |
| +) |
| + |
| +// recoveryEligible is the one decision to resend (Invariant 8). All times |
| +// are provider time. It is true only when the state is sending or |
| +// unresolved, the outcome is not indeterminate, providerNow is inside both |
| +// the key lifetime from the first send and the request's own cap, a |
| +// restore keeps Invariant 4's margin, and the request's context is current. |
| +func recoveryEligible(r resendState, providerNow time.Time) (bool, string) { |
| + if r.State != opSending && r.State != opUnresolved { |
| + return false, ineligibleState |
| + } |
| + if r.Indeterminate { |
| + return false, ineligibleIndeterminate |
| + } |
| + if providerNow.IsZero() { |
| + return false, ineligibleClock |
| + } |
| + if r.FirstSent.IsZero() || !providerNow.Before(r.FirstSent.Add(resendLifetime)) { |
| + return false, ineligibleWindow |
| + } |
| + if !r.ResendUntil.IsZero() && !providerNow.Before(r.ResendUntil) { |
| + return false, ineligibleWindow |
| + } |
| + if r.Restore && r.PeriodEnd.Sub(providerNow) <= restoreMargin { |
| + return false, ineligibleMargin |
| + } |
| + if !r.ContextCurrent { |
| + return false, ineligibleContext |
| + } |
| + return true, "" |
| +} |
| + |
| +// permanentlyIneligible is a refusal that no later moment undoes: the pass |
| +// escalates exactly these (Invariant 8). |
| +func permanentlyIneligible(reason string) bool { |
| + return reason == ineligibleIndeterminate || reason == ineligibleWindow || reason == ineligibleMargin |
| +} |
| + |
| +// opOutcome is what a send or a recovery recorded: the operation's new |
| +// state, whether it is indeterminate, and whether the provider replayed a |
| +// stored answer. |
| +type opOutcome struct { |
| + State string |
| + Indeterminate bool |
| + Replayed bool |
| +} |
| + |
| +// retryableSend is an unknown delivery: no response, 409 in flight or 429 |
| +// (facts 2 to 4). |
| +func retryableSend(err error) bool { |
| + return errors.Is(err, billing.ErrNoResponse) || errors.Is(err, billing.ErrInFlight) || errors.Is(err, billing.ErrNotExecuted) |
| +} |
| + |
| +// resendStateOf is the operation's resend state against a read of its |
| +// subscription (nil when none was possible). |
| +func (s *Server) resendStateOf(op *billingOp, sub *billing.Subscription, now time.Time) resendState { |
| + r := resendState{State: op.State, Indeterminate: op.Indeterminate, FirstSent: op.FirstSentAt, ResendUntil: op.resendUntil(), |
| + Restore: op.Kind == opRestore, PeriodEnd: op.PeriodEnd, ContextCurrent: true} |
| + if sub != nil && (!sub.Live || !sub.PeriodEnd.Equal(op.PeriodEnd)) { |
| + r.ContextCurrent = false |
| + } |
| + if op.InviteToken != "" { |
| + if _, pending := s.store.PendingInviteAddress(op.InviteToken, now); !pending { |
| + r.ContextCurrent = false |
| + } |
| + } |
| + return r |
| +} |
| + |
| +// settleFromRead records what a read of the subscription proves: the target |
| +// visible is applied, a pending update is pending. Anything else proves |
| +// nothing and records nothing. |
| +func (s *Server) settleFromRead(op *billingOp, sub *billing.Subscription, now time.Time) (opOutcome, bool, error) { |
| + switch { |
| + case targetMet(op.Target, sub): |
| + if err := s.store.MarkOpApplied(op.ID, sub.PeriodEnd, now); err != nil { |
| + return opOutcome{}, false, err |
| + } |
| + op.State, op.AppliedPeriodEnd = opApplied, sub.PeriodEnd |
| + return opOutcome{State: opApplied}, true, nil |
| + case sub.PendingUpdate: |
| + if op.State != opPending { |
| + if err := s.store.PutBillingOpState(op.ID, opPending, false, now); err != nil { |
| + return opOutcome{}, false, err |
| + } |
| + } |
| + op.State = opPending |
| + return opOutcome{State: opPending}, true, nil |
| + } |
| + return opOutcome{}, false, nil |
| +} |
| + |
| +// recordSendOutcome records a send's answer (Call 17): success at the |
| +// target is applied; success with a pending update is pending; a decline or |
| +// refusal is failed; a cached 5xx is unresolved and indeterminate; an |
| +// unknown delivery is unresolved; a reused key is a programming error, |
| +// logged and left unresolved. An error outside every class (a crash) is |
| +// returned at once with nothing recorded, so the row stays as it was. |
| +func (s *Server) recordSendOutcome(op *billingOp, res billing.Result, err error, now time.Time) (opOutcome, *billing.Subscription, error) { |
| + put := func(state string, indeterminate bool) (opOutcome, *billing.Subscription, error) { |
| + if err := s.store.PutBillingOpState(op.ID, state, indeterminate, now); err != nil { |
| + return opOutcome{}, nil, err |
| + } |
| + op.State, op.Indeterminate = state, indeterminate |
| + return opOutcome{State: state, Indeterminate: indeterminate, Replayed: res.Replayed}, res.Subscription, nil |
| + } |
| + switch { |
| + case err == nil: |
| + sub := res.Subscription |
| + if sub != nil { |
| + out, settled, err := s.settleFromRead(op, sub, now) |
| + if err != nil { |
| + return opOutcome{}, nil, err |
| + } |
| + if settled { |
| + out.Replayed = res.Replayed |
| + return out, sub, nil |
| + } |
| + } |
| + log.Printf("console: billing: operation %s: a definite answer shows neither the target nor a pending update; left unresolved", op.ID) |
| + return put(opUnresolved, false) |
| + case errors.Is(err, billing.ErrPaymentFailed), errors.Is(err, billing.ErrRefused): |
| + return put(opFailed, false) |
| + case errors.Is(err, billing.ErrIndeterminate): |
| + return put(opUnresolved, true) |
| + case errors.Is(err, billing.ErrIdempotencyMismatch): |
| + log.Printf("console: billing: operation %s: %v (a programming error; left unresolved)", op.ID, err) |
| + return put(opUnresolved, false) |
| + case retryableSend(err): |
| + return put(opUnresolved, false) |
| + } |
| + return opOutcome{}, nil, err |
| +} |
| + |
| +// sendOpLocked writes the operation (sending, with its prepared request and |
| +// FirstSentAt from the request's provider time) and sends it. An unknown |
| +// delivery is retried up to handlerRetries times, each after a backoff and a |
| +// read of the subscription, which settles on positive evidence; the same |
| +// bytes are resent only while recoveryEligible. The outcome is recorded as |
| +// recordSendOutcome says. With no provider time nothing is written or sent |
| +// and the request is refused with change.clock. |
| +func (s *Server) sendOpLocked(h billingHold, ctx context.Context, op billingOp, now time.Time) (opOutcome, *billing.Subscription, error) { |
| + _ = h |
| + cfg := s.billing.cfg |
| + pnow, err := s.providerNow(ctx) |
| + if err != nil { |
| + return opOutcome{}, nil, errNoProviderTimeRefusal |
| + } |
| + op.FirstSentAt, op.LastSentAt, op.State, op.Indeterminate, op.CreatedAt = pnow, pnow, opSending, false, now |
| + if err := s.store.BeginBillingOp(op); err != nil { |
| + return opOutcome{}, nil, err |
| + } |
| + for attempt := 0; ; attempt++ { |
| + res, err := cfg.Provider.Send(ctx, op.Prepared) |
| + if !retryableSend(err) || attempt == handlerRetries { |
| + return s.recordSendOutcome(&op, res, err, now) |
| + } |
| + // Delivery unknown: wait, read, settle on what the read shows, and |
| + // otherwise resend the same bytes while that is allowed. |
| + s.waitBackoff(ctx, handlerBackoff(attempt+1)) |
| + sub, err := cfg.Provider.Subscription(ctx, op.Subscription) |
| + if err != nil { |
| + log.Printf("console: billing: operation %s: read after an unknown delivery failed: %v; left unresolved", op.ID, err) |
| + return s.recordSendOutcome(&op, billing.Result{}, billing.ErrNoResponse, now) |
| + } |
| + if out, settled, err := s.settleFromRead(&op, sub, now); err != nil || settled { |
| + return out, sub, err |
| + } |
| + pnow, err := s.providerNow(ctx) |
| + if err != nil { |
| + return s.recordSendOutcome(&op, billing.Result{}, billing.ErrNoResponse, now) |
| + } |
| + if ok, reason := recoveryEligible(s.resendStateOf(&op, sub, now), pnow); !ok { |
| + log.Printf("console: billing: operation %s: not resent (%s); left unresolved", op.ID, reason) |
| + return s.recordSendOutcome(&op, billing.Result{}, billing.ErrNoResponse, now) |
| + } |
| + if err := s.store.NoteOpSent(op.ID, pnow); err != nil { |
| + return opOutcome{}, nil, err |
| + } |
| + } |
| +} |
| + |
| +// finishOpLocked is a user's request finishing an operation left sending or |
| +// unresolved: an orphaned sending row is adopted as unresolved, the |
| +// subscription is read and applied, the read settles on positive evidence, |
| +// and otherwise the same bytes are sent once more while recoveryEligible. |
| +// It runs only inside an owner's or invitee's request (Invariant 5). |
| +func (s *Server) finishOpLocked(h billingHold, ctx context.Context, acct *Account, op *billingOp, now time.Time) (opOutcome, error) { |
| + if op.State != opSending && op.State != opUnresolved { |
| + return opOutcome{State: op.State, Indeterminate: op.Indeterminate}, nil |
| + } |
| + cfg := s.billing.cfg |
| + if op.State == opSending { |
| + if err := s.store.AdoptOrphanedSending(op.ID, now); err != nil { |
| + return opOutcome{}, err |
| + } |
| + op.State = opUnresolved |
| + } |
| + sub, err := cfg.Provider.Subscription(ctx, op.Subscription) |
| + if errors.Is(err, billing.ErrNotFound) { |
| + return opOutcome{State: opUnresolved, Indeterminate: op.Indeterminate}, s.subscriptionMissing(op.Subscription, now) |
| + } |
| + if err != nil { |
| + return opOutcome{}, fmt.Errorf("billing: reading subscription %s: %w", op.Subscription, err) |
| + } |
| + prev, err := s.store.BillingAccount(acct.ID) |
| + if err != nil { |
| + return opOutcome{}, err |
| + } |
| + if prev != nil && prev.Subscription == sub.ID && prev.Customer == sub.Customer { |
| + if err := s.applyBillingRead(ctx, acct, prev, sub, now); err != nil { |
| + return opOutcome{}, err |
| + } |
| + } |
| + if err := s.settleOpsLocked(h, acct, sub, now); err != nil { |
| + return opOutcome{}, err |
| + } |
| + if err := s.restoreCheckLocked(h, ctx, acct, sub, now); err != nil { |
| + return opOutcome{}, err |
| + } |
| + cur, err := s.store.BillingOp(op.ID) |
| + if err != nil || cur == nil { |
| + return opOutcome{}, fmt.Errorf("billing: operation %s vanished: %w", op.ID, err) |
| + } |
| + *op = *cur |
| + if op.State != opUnresolved { |
| + return opOutcome{State: op.State, Indeterminate: op.Indeterminate}, nil |
| + } |
| + pnow, err := s.providerNow(ctx) |
| + if err != nil { |
| + log.Printf("console: billing: operation %s: no provider time; not resent", op.ID) |
| + return opOutcome{State: opUnresolved, Indeterminate: op.Indeterminate}, nil |
| + } |
| + if ok, reason := recoveryEligible(s.resendStateOf(op, sub, now), pnow); !ok { |
| + log.Printf("console: billing: operation %s: not resent (%s)", op.ID, reason) |
| + return opOutcome{State: opUnresolved, Indeterminate: op.Indeterminate}, nil |
| + } |
| + if err := s.store.NoteOpSent(op.ID, pnow); err != nil { |
| + return opOutcome{}, err |
| + } |
| + res, err := cfg.Provider.Send(ctx, op.Prepared) |
| + out, _, err := s.recordSendOutcome(op, res, err, now) |
| + return out, err |
| +} |
| + |
| +// settleOpsLocked records what a fresh read of the subscription proves |
| +// about its outstanding operation, using positive evidence only: an |
| +// orphaned sending row is adopted as unresolved first; the target visible is |
| +// applied; a pending update is pending; a pending operation whose pending |
| +// update is gone with the target unmet is abandoned (fact 8). A negative |
| +// read never abandons an unresolved operation. |
| +func (s *Server) settleOpsLocked(h billingHold, acct *Account, sub *billing.Subscription, now time.Time) error { |
| + _, _ = h, acct |
| + op, err := s.store.OutstandingOp(sub.ID) |
| + if err != nil || op == nil { |
| + return err |
| + } |
| + if op.State == opSending { |
| + if err := s.store.AdoptOrphanedSending(op.ID, now); err != nil { |
| + return err |
| + } |
| + op.State = opUnresolved |
| + log.Printf("console: billing: operation %s was left sending by an earlier process; treated as unresolved", op.ID) |
| + } |
| + if _, settled, err := s.settleFromRead(op, sub, now); err != nil || settled { |
| + return err |
| + } |
| + if op.State == opPending { |
| + return s.store.PutBillingOpState(op.ID, opAbandoned, false, now) |
| + } |
| + return nil |
| +} |
| + |
| +// outcomeCopy is the billingCopy key a request's flash shows for an outcome. |
| +func outcomeCopy(out opOutcome) (kind, key string) { |
| + switch out.State { |
| + case opApplied: |
| + return "ok", "change.done" |
| + case opPending: |
| + return "err", "change.pending" |
| + case opFailed: |
| + return "err", "change.declined" |
| + } |
| + return "err", "change.uncertain" |
| +} |
| + |
| +// confirmBillingLocked is Confirm now under the hold: an operation left |
| +// sending or unresolved on the account's subscription is finished |
| +// (finishOpLocked), then the subscription is refreshed. It answers the |
| +// flash's kind and copy key, "" for none. The Checkout work (an unresolved |
| +// customer create or session create) is added here by the Checkout task. |
| +func (s *Server) confirmBillingLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (kind, key string, err error) { |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil || b == nil || b.Subscription == "" { |
| + return "", "", err |
| + } |
| + op, err := s.store.OutstandingOp(b.Subscription) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + if op != nil && (op.State == opSending || op.State == opUnresolved) { |
| + out, err := s.finishOpLocked(h, ctx, acct, op, now) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + kind, key = outcomeCopy(out) |
| + } |
| + if _, _, err := s.refreshLocked(h, ctx, acct, now); err != nil { |
| + return kind, key, err |
| + } |
| + return kind, key, nil |
| +} |
| + |
| +// handleBillingConfirm is POST /a/{sqid}/billing/confirm: an owner's |
| +// Confirm now (Call 17). Billing off answers 404; an owner with CSRF gets |
| +// the account's outstanding work finished under the hold, then a redirect |
| +// to the billing page with what happened. |
| +func (s *Server) handleBillingConfirm(w http.ResponseWriter, r *http.Request) { |
| + if s.billing == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + _, raw, acct, ok := s.owner(w, r) |
| + if !ok { |
| + return |
| + } |
| + if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 { |
| + s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| + return |
| + } |
| + back := "/a/" + url.PathEscape(acct.Sqid) + "/billing" |
| + if !s.billing.ready.Load() { |
| + s.setFlash(w, "err", billingCopy["change.failed"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + ctx := s.billingClock(r.Context()) |
| + now := time.Now() |
| + h, release := s.holdBilling(acct.Sqid) |
| + kind, key, err := s.confirmBillingLocked(h, ctx, acct, now) |
| + release() |
| + if err != nil { |
| + log.Printf("console: billing confirm %s: %v", acct.Sqid, err) |
| + if key == "" { |
| + kind, key = "err", "change.failed" |
| + } |
| + } |
| + if key != "" { |
| + s.setFlash(w, kind, billingCopy[key]) |
| + } |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| +} |
diff --git a/internal/console/billingops_test.go b/internal/console/billingops_test.go| new file mode 100644 |
| index 000000000..02c92946a |
| --- /dev/null |
| +++ b/internal/console/billingops_test.go |
| @@ -0,0 +1,1160 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "maps" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/billing/billingtest" |
| +) |
| + |
| +// opsFixture is a billing fixture with a synced Personal subscription, the |
| +// Fake's monotonic clock wired into the console's recorders, the in-handler |
| +// backoff replaced by a monotonic advance, and the Fake's counters reset, so |
| +// tests assert CallsBy exactly. |
| +type opsFixture struct { |
| + *billingFixture |
| + ctx context.Context // a request's context, with its recorder |
| + owner *http.Client |
| + csrf string |
| +} |
| + |
| +func newOpsFixture(t *testing.T, packs map[string]int64) *opsFixture { |
| + t.Helper() |
| + bf := newBillingFixture(t) |
| + bf.srv.billing.ready.Store(true) |
| + o := &opsFixture{billingFixture: bf} |
| + o.wire() |
| + bf.put(bf.personalSub("sub_1", "active", packs)) |
| + if err := bf.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.reset() |
| + return o |
| +} |
| + |
| +// wire points the server's clocks at the Fake and makes the handler backoff |
| +// an advance of the Fake's monotonic clock, then opens a request context. |
| +func (o *opsFixture) wire() { |
| + o.srv.billing.monotonic = o.fake.Monotonic |
| + o.srv.billing.wait = func(_ context.Context, d time.Duration) { o.fake.AdvanceMonotonic(d) } |
| + o.ctx = o.srv.billingClock(context.Background()) |
| +} |
| + |
| +// fresh is a new request context: an empty recorder. |
| +func (o *opsFixture) fresh() { o.ctx = o.srv.billingClock(context.Background()) } |
| + |
| +func (o *opsFixture) reset() { |
| + o.fake.Lock() |
| + defer o.fake.Unlock() |
| + o.fake.Calls = 0 |
| + o.fake.CallsBy = map[string]int{} |
| + o.fake.Sent = nil |
| + o.fake.PageLog = nil |
| +} |
| + |
| +func (o *opsFixture) counts() map[string]int { |
| + o.fake.Lock() |
| + defer o.fake.Unlock() |
| + out := map[string]int{} |
| + for k, v := range o.fake.CallsBy { |
| + if v != 0 { |
| + out[k] = v |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func (o *opsFixture) sent() []billing.Prepared { |
| + o.fake.Lock() |
| + defer o.fake.Unlock() |
| + return slices.Clone(o.fake.Sent) |
| +} |
| + |
| +func (o *opsFixture) providerClock() time.Time { |
| + o.fake.Lock() |
| + defer o.fake.Unlock() |
| + return o.fake.ProviderClock |
| +} |
| + |
| +// observe is the read that precedes a send in a request: the recorder sees |
| +// the provider's Date without a counted request. |
| +func (o *opsFixture) observe() { billing.ObserveDate(o.ctx, o.providerClock()) } |
| + |
| +// sub is a copy of the Fake's subscription, read without a request. |
| +func (o *opsFixture) sub(id string) *billing.Subscription { |
| + o.fake.Lock() |
| + defer o.fake.Unlock() |
| + s := *o.fake.Subs[id] |
| + s.Items = slices.Clone(s.Items) |
| + return &s |
| +} |
| + |
| +// setQuantity moves a pack item's quantity at the provider, as a change the |
| +// console did not make (or a late apply). |
| +func (o *opsFixture) setQuantity(subID, priceID string, q int64) { |
| + o.fake.Lock() |
| + defer o.fake.Unlock() |
| + s := o.fake.Subs[subID] |
| + for i := range s.Items { |
| + if s.Items[i].PriceID == priceID { |
| + s.Items[i].Quantity = q |
| + } |
| + } |
| +} |
| + |
| +func (o *opsFixture) packItem(t *testing.T, subID, name string) billing.Item { |
| + t.Helper() |
| + price := testPriceID("example-v1/pack/" + name + "/usd") |
| + for _, it := range o.sub(subID).Items { |
| + if it.PriceID == price { |
| + return it |
| + } |
| + } |
| + t.Fatalf("no %s item on %s", name, subID) |
| + return billing.Item{} |
| +} |
| + |
| +// packOp prepares a quantity change of the subscription's pack item through |
| +// the Fake, exactly as a change handler will: the proration timestamp is |
| +// provider time and the key is op:<id>. |
| +func (o *opsFixture) packOp(t *testing.T, id, subID, name string, qty int64, pr billing.Proration, kind string) billingOp { |
| + t.Helper() |
| + it := o.packItem(t, subID, name) |
| + // The proration timestamp is the request's provider time: the recorder's |
| + // observation when it has one, else (for a test that has made no read) |
| + // the provider's clock, without a counted probe. |
| + pnow, err := billing.ClockFrom(o.ctx).Now() |
| + if err != nil { |
| + pnow = o.providerClock() |
| + } |
| + p, err := o.fake.PrepareChange(billing.ChangeRequest{Subscription: subID, Items: []billing.ItemChange{{ItemID: it.ItemID, Quantity: qty}}, |
| + Proration: pr, ProrationDate: pnow, IdempotencyKey: "op:" + id}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sub := o.sub(subID) |
| + return billingOp{ID: id, Subscription: subID, Kind: kind, AccountID: o.accountOf(t, subID), PeriodEnd: sub.PeriodEnd, |
| + Target: opTarget{Quantities: map[string]int64{it.PriceID: qty}}, Prepared: p} |
| +} |
| + |
| +func (o *opsFixture) accountOf(t *testing.T, subID string) int64 { |
| + t.Helper() |
| + b, err := o.st.BillingAccountBySubscription(subID) |
| + if err != nil || b == nil { |
| + t.Fatalf("no billing row records %s: %v", subID, err) |
| + } |
| + return b.AccountID |
| +} |
| + |
| +func (o *opsFixture) renewalOp(t *testing.T, id, subID string, renew bool) billingOp { |
| + t.Helper() |
| + p, err := o.fake.PrepareRenewal(subID, renew, "op:"+id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sub := o.sub(subID) |
| + return billingOp{ID: id, Subscription: subID, Kind: opRenewal, AccountID: o.accountOf(t, subID), PeriodEnd: sub.PeriodEnd, |
| + Target: opTarget{Renewal: true, CancelAtPeriodEnd: !renew}, Prepared: p} |
| +} |
| + |
| +// unresolved stores op as sent once at the provider's current time and left |
| +// unresolved: a recovery's starting point, with no request counted. |
| +func (o *opsFixture) unresolved(t *testing.T, op billingOp) { |
| + t.Helper() |
| + op.FirstSentAt, op.LastSentAt, op.State = o.providerClock(), o.providerClock(), opSending |
| + if err := o.st.BeginBillingOp(op); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.st.PutBillingOpState(op.ID, opUnresolved, false, billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (o *opsFixture) hold() (billingHold, func()) { return o.srv.holdBilling(o.acct.Sqid) } |
| + |
| +func (o *opsFixture) send(t *testing.T, op billingOp) (opOutcome, *billing.Subscription, error) { |
| + t.Helper() |
| + h, release := o.hold() |
| + defer release() |
| + return o.srv.sendOpLocked(h, o.ctx, op, billingNow) |
| +} |
| + |
| +func (o *opsFixture) finish(t *testing.T, opID string) (opOutcome, error) { |
| + t.Helper() |
| + op := o.op(t, opID) |
| + h, release := o.hold() |
| + defer release() |
| + return o.srv.finishOpLocked(h, o.ctx, o.acct, op, billingNow) |
| +} |
| + |
| +func (o *opsFixture) op(t *testing.T, id string) *billingOp { |
| + t.Helper() |
| + op, err := o.st.BillingOp(id) |
| + if err != nil || op == nil { |
| + t.Fatalf("op %s: %v", id, err) |
| + } |
| + return op |
| +} |
| + |
| +// restart discards the server and builds another on the same store and |
| +// Fake: the recorder's monotonic readings are gone with the process. |
| +func (o *opsFixture) restart(t *testing.T) { |
| + t.Helper() |
| + srv, err := NewServer(o.srv.cfg, o.st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv.billing.ready.Store(true) |
| + o.srv = srv |
| + o.wire() |
| +} |
| + |
| +func (o *opsFixture) pass(now time.Time) { o.srv.billingSyncPass(context.Background(), now) } |
| + |
| +func (o *opsFixture) openProblems(t *testing.T) []string { |
| + t.Helper() |
| + open, err := o.st.BillingProblems(false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, p := range open { |
| + out = append(out, p.Reason) |
| + } |
| + sort0(out) |
| + return out |
| +} |
| + |
| +func sort0(s []string) { slices.Sort(s) } |
| + |
| +// signInOwner signs the fixture account's owner in through the front door. |
| +func (o *opsFixture) signInOwner(t *testing.T) { |
| + t.Helper() |
| + o.setUser("owner" + o.acct.Sqid + "@example.com") |
| + c := newBrowser(t) |
| + signUp(t, o.consoleFixture, c, "code-ops-"+o.acct.Sqid) |
| + o.owner, o.csrf = c, sessionToken(t, o.consoleFixture, c) |
| +} |
| + |
| +// confirm is the owner's Confirm now, served by the current server (which |
| +// may be a restarted one, so the request goes straight to ServeHTTP with the |
| +// browser's cookies). |
| +func (o *opsFixture) confirm(t *testing.T) (status int, loc string) { |
| + t.Helper() |
| + if o.owner == nil { |
| + o.signInOwner(t) |
| + } |
| + form := url.Values{"csrf": {o.csrf}} |
| + req := httptest.NewRequest(http.MethodPost, o.ts.URL+"/a/"+o.acct.Sqid+"/billing/confirm", strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + u, _ := url.Parse(o.ts.URL) |
| + for _, ck := range o.owner.Jar.Cookies(u) { |
| + req.AddCookie(ck) |
| + } |
| + rr := httptest.NewRecorder() |
| + o.srv.ServeHTTP(rr, req) |
| + return rr.Code, rr.Header().Get("Location") |
| +} |
| + |
| +// stripDates wraps the Fake so chosen reads arrive with no Date header: the |
| +// request is counted, the state is served, but nothing is observed. decoy, |
| +// when set, receives the observations instead (a page count that advances |
| +// the monotonic clock models slow pagination). |
| +type stripDates struct { |
| + billing.Provider |
| + reads, invoices bool |
| + decoy *billing.ClockRecorder |
| + decoyFor string // the subscription whose invoice pages observe into decoy |
| +} |
| + |
| +func (p stripDates) bare(subscription string) context.Context { |
| + if p.decoy != nil && subscription == p.decoyFor { |
| + return billing.WithClock(context.Background(), p.decoy) |
| + } |
| + return context.Background() |
| +} |
| + |
| +func (p stripDates) Subscription(ctx context.Context, id string) (*billing.Subscription, error) { |
| + if !p.reads { |
| + return p.Provider.Subscription(ctx, id) |
| + } |
| + s, err := p.Provider.Subscription(context.Background(), id) |
| + if s != nil { |
| + s.ProviderTime = time.Time{} |
| + } |
| + return s, err |
| +} |
| + |
| +func (p stripDates) RenewalInvoice(ctx context.Context, subscription string, periodStart time.Time) (billing.InvoiceQuantities, error) { |
| + if !p.invoices { |
| + return p.Provider.RenewalInvoice(ctx, subscription, periodStart) |
| + } |
| + return p.Provider.RenewalInvoice(p.bare(subscription), subscription, periodStart) |
| +} |
| + |
| +func (o *opsFixture) headerlessReads(invoices bool) { |
| + o.srv.billing.cfg.Provider = stripDates{Provider: o.fake, reads: true, invoices: invoices} |
| +} |
| + |
| +func wantCounts(t *testing.T, got, want map[string]int) { |
| + t.Helper() |
| + if !maps.Equal(got, want) { |
| + t.Fatalf("CallsBy = %v, want %v", got, want) |
| + } |
| +} |
| + |
| +// ---- the hold, refresh and allowance --------------------------------------- |
| + |
| +func TestSyncSubscriptionLockedSharesTheLock(t *testing.T) { |
| + o := newOpsFixture(t, nil) |
| + h, release := o.hold() |
| + done := make(chan error, 1) |
| + go func() { done <- o.srv.syncSubscription(context.Background(), "sub_1", billingNow) }() |
| + select { |
| + case err := <-done: |
| + t.Fatalf("syncSubscription ran under another holder's hold: %v", err) |
| + case <-time.After(150 * time.Millisecond): |
| + } |
| + // The locked form runs for the holder without taking the lock again. |
| + if err := o.srv.syncSubscriptionLocked(h, o.ctx, o.acct, "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + release() |
| + select { |
| + case err := <-done: |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("syncSubscription never got the lock back") |
| + } |
| +} |
| + |
| +func TestRefreshHasNoPeriodCheck(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + b, _ := o.st.BillingAccount(o.acct.ID) |
| + b.PaidPeriodEnd = periodEnd.AddDate(-1, 0, 0) // the row lags the provider by a period |
| + if err := o.st.PutBillingState(*b); err != nil { |
| + t.Fatal(err) |
| + } |
| + h, release := o.hold() |
| + defer release() |
| + got, sub, err := o.srv.refreshLocked(h, o.ctx, o.acct, billingNow) |
| + if err != nil || sub == nil || sub.ID != "sub_1" { |
| + t.Fatalf("refresh = %+v %v", sub, err) |
| + } |
| + if !got.PaidPeriodEnd.Equal(periodEnd) { |
| + t.Fatalf("the refresh did not follow the read: paid period %v", got.PaidPeriodEnd) |
| + } |
| + // An unrecognised subscription still refreshes without error: refresh is |
| + // the plain sync, with no period requirement. |
| + s := o.sub("sub_1") |
| + s.Items = append(s.Items, billing.Item{PriceID: "price_unknown", Quantity: 1, Currency: "usd"}) |
| + o.put(s) |
| + if _, sub, err := o.srv.refreshLocked(h, o.ctx, o.acct, billingNow); err != nil || sub == nil { |
| + t.Fatalf("refresh of an unrecognised subscription = %+v %v", sub, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 2}) |
| +} |
| + |
| +func TestAllowanceAppliesDelayedRenewal(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 2}) |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + h, release := o.hold() |
| + defer release() |
| + b, sub, purchase, err := o.srv.allowanceLocked(h, o.ctx, o.acct, billingNow) |
| + if err != nil { |
| + t.Fatalf("allowance after a renewal the console had not seen: %v", err) |
| + } |
| + if !sub.PeriodEnd.Equal(periodEnd.AddDate(1, 0, 0)) || !b.PaidPeriodEnd.Equal(sub.PeriodEnd) || purchase.Plan != "personal" || purchase.Packs["apps"] != 2 { |
| + t.Fatalf("allowance = row %+v sub period %v purchase %+v", b, sub.PeriodEnd, purchase) |
| + } |
| +} |
| + |
| +func TestAllowanceRefusesEndedOrMismatched(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + h, release := o.hold() |
| + defer release() |
| + s := o.sub("sub_1") |
| + s.Items = append(s.Items, billing.Item{PriceID: "price_unknown", Quantity: 1, Currency: "usd"}) |
| + o.put(s) |
| + var refusal billingRefusal |
| + if _, _, _, err := o.srv.allowanceLocked(h, o.ctx, o.acct, billingNow); !errors.As(err, &refusal) { |
| + t.Fatalf("mismatched allowance = %v, want a refusal", err) |
| + } |
| + o.put(o.personalSub("sub_1", "canceled", map[string]int64{"apps": 1})) |
| + if _, _, _, err := o.srv.allowanceLocked(h, o.ctx, o.acct, billingNow); !errors.As(err, &refusal) { |
| + t.Fatalf("ended allowance = %v, want a refusal", err) |
| + } |
| + if o.fake.Writes() != 0 { |
| + t.Fatal("a refused allowance wrote to the provider") |
| + } |
| +} |
| + |
| +func TestQuantityPlan(t *testing.T) { |
| + for _, c := range []struct{ cur, target, paid, restore, charge int64 }{ |
| + {1, 3, 1, 0, 3}, |
| + {1, 3, 3, 3, 0}, |
| + {1, 4, 3, 3, 4}, |
| + {0, 4, 3, 3, 4}, |
| + {2, 2, 5, 0, 0}, |
| + {3, 1, 5, 0, 0}, |
| + } { |
| + r, ch := quantityPlan(c.cur, c.target, c.paid) |
| + if r != c.restore || ch != c.charge { |
| + t.Errorf("quantityPlan(%d, %d, %d) = restore %d charge %d, want %d %d", c.cur, c.target, c.paid, r, ch, c.restore, c.charge) |
| + } |
| + } |
| +} |
| + |
| +// ---- sending ----------------------------------------------------------------- |
| + |
| +func TestPreparedPersistedBeforeSend(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.CrashBeforeSend = true |
| + _, _, err := o.send(t, op) |
| + if !errors.Is(err, billingtest.ErrCrash) { |
| + t.Fatalf("crash before send: err = %v", err) |
| + } |
| + row := o.op(t, "op_1") |
| + if row.State != opSending || !samePrepared(&row.Prepared, &op.Prepared) || !row.FirstSentAt.Equal(o.providerClock()) { |
| + t.Fatalf("row after the crash = %+v", row) |
| + } |
| + if len(o.sent()) != 0 || len(o.counts()) != 0 { |
| + t.Fatalf("the provider saw something: %v %v", o.sent(), o.counts()) |
| + } |
| +} |
| + |
| +func TestHandlerRetryReadsThenResendsVerbatim(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.CompleteLater(1) // lands once the retry's read has been answered: a negative read, then a replay |
| + out, sub, err := o.send(t, op) |
| + if err != nil || out.State != opApplied || !out.Replayed { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 2, "Subscription": 1}) |
| + sent := o.sent() |
| + if !samePrepared(&sent[0], &sent[1]) || !samePrepared(&sent[0], &op.Prepared) { |
| + t.Fatalf("the resend differed from the first send: %+v %+v", sent[0], sent[1]) |
| + } |
| + if sub == nil || o.op(t, "op_1").State != opApplied || o.packItem(t, "sub_1", "apps").Quantity != 3 { |
| + t.Fatalf("not applied: %+v", o.op(t, "op_1")) |
| + } |
| +} |
| + |
| +func TestTimeoutStillProcessingIsNotReleasedByANegativeRead(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + // Still processing through every retry (three reads and three resends), |
| + // and landing only as the next pass's second read (6a's sync reads |
| + // twice: a lookup, then the deciding read under the hold) is answered. |
| + o.fake.CompleteLater(9) |
| + out, _, err := o.send(t, op) |
| + if err != nil || out.State != opUnresolved || out.Indeterminate { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 4, "Subscription": 3}) |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("a negative read released the op: %+v", row) |
| + } |
| + // The pass reads it (negative, and the request lands as that read ends): |
| + // still unresolved, no problem, no write. |
| + o.pass(billingNow) |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("after the pass: %+v", row) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + // The next read shows the target: applied, from a pass, with no send. |
| + o.pass(billingNow.Add(time.Hour)) |
| + if row := o.op(t, "op_1"); row.State != opApplied { |
| + t.Fatalf("a positive read did not settle: %+v", row) |
| + } |
| + if o.fake.Writes() != 4 { |
| + t.Fatalf("writes = %d, want the handler's 4", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestInFlightWaitsAndResends(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.InFlight(1) |
| + out, _, err := o.send(t, op) |
| + if err != nil || out.State != opApplied { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 2, "Subscription": 1}) |
| +} |
| + |
| +func TestRateLimitResends(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.RateLimit = 2 |
| + out, _, err := o.send(t, op) |
| + if err != nil || out.State != opApplied { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 3, "Subscription": 2}) |
| +} |
| + |
| +func TestCached500GoesToTheOperator(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.Cached500Before = true |
| + out, _, err := o.send(t, op) |
| + if err != nil || out.State != opUnresolved || !out.Indeterminate { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 1}) |
| + if row := o.op(t, "op_1"); row.State != opUnresolved || !row.Indeterminate { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + o.pass(billingNow) |
| + if got := o.openProblems(t); !slices.Equal(got, []string{problemOperationUnresolved}) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("the pass wrote: writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestCached500LaterSeenApplied(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.Cached500After = true |
| + if out, _, err := o.send(t, op); err != nil || out.State != opUnresolved || !out.Indeterminate { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + o.pass(billingNow) |
| + if row := o.op(t, "op_1"); row.State != opApplied { |
| + t.Fatalf("the pass's read did not settle it: %+v", row) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestWindowClosesToOperator(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.FailBeforeDelivery = 4 |
| + if out, _, err := o.send(t, op); err != nil || out.State != opUnresolved || out.Indeterminate { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 4, "Subscription": 3}) |
| + o.pass(billingNow) |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("escalated inside the window: %v", got) |
| + } |
| + o.fake.AdvanceProvider(23 * time.Hour) |
| + o.pass(billingNow.Add(time.Hour)) |
| + if got := o.openProblems(t); !slices.Equal(got, []string{problemOperationUnresolved}) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if o.fake.Writes() != 4 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestNoResendAfterKeyLifetime(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + o.fake.AdvanceProvider(resendLifetime + time.Minute) |
| + o.fresh() |
| + if out, err := o.finish(t, "op_1"); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 1}) |
| + // Just inside the lifetime it is still resent. |
| + o.fake.AdvanceProvider(-2 * time.Minute) |
| + o.fresh() |
| + if out, err := o.finish(t, "op_1"); err != nil || out.State != opApplied { |
| + t.Fatalf("outcome inside the window = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1}) |
| +} |
| + |
| +func TestNoResendAfterPeriodMargin(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + s := o.sub("sub_1") |
| + s.PeriodEnd = o.providerClock().Add(30 * time.Minute) |
| + o.put(s) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.reset() |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.FailBeforeDelivery = 1 |
| + out, _, err := o.send(t, op) |
| + if err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Send": 1, "Subscription": 1}) |
| +} |
| + |
| +func TestNoProviderTimeNoSend(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + o.headerlessReads(false) |
| + o.fake.Headerless = true // the probe answers with no Date either |
| + o.fresh() |
| + if out, err := o.finish(t, "op_1"); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 1, "ClockProbe": 1}) |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("row = %+v", row) |
| + } |
| +} |
| + |
| +func TestPendingNeverEscalates(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.FailPayment = 1 |
| + if out, _, err := o.send(t, op); err != nil || out.State != opPending { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + o.fake.AdvanceProvider(20 * time.Hour) |
| + o.pass(billingNow) |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("a pending payment escalated: %v", got) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opPending { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if err := o.fake.PayPending("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow.Add(time.Hour)) |
| + if row := o.op(t, "op_1"); row.State != opApplied { |
| + t.Fatalf("paid later, row = %+v", row) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestPendingExpiryAbandons(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.FailPayment = 1 |
| + if out, _, err := o.send(t, op); err != nil || out.State != opPending { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + if err := o.fake.ExpirePending("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.pass(billingNow) |
| + if row := o.op(t, "op_1"); row.State != opAbandoned || row.SettledAt.IsZero() { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + // Abandoned is terminal: a new change may begin. |
| + if err := o.st.BeginBillingOp(o.packOp(t, "op_2", "sub_1", "apps", 2, billing.ProrateNone, opPack)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestOperatorCloseNeedsEvidence(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.Cached500Before = true |
| + if out, _, err := o.send(t, op); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + o.pass(billingNow) |
| + open, _ := o.st.BillingProblems(false) |
| + if len(open) != 1 || open[0].Reason != problemOperationUnresolved { |
| + t.Fatalf("problems = %+v", open) |
| + } |
| + operator := planOperatorToken(t, o.consoleFixture, "ops@keymail.dev", "code-billing-evidence") |
| + closeURL := billingCloseURL(o.consoleFixture, open[0].ID) |
| + if status, out := postJSON(t, closeURL, map[string]any{"note": "looked at it"}, operator); status != http.StatusConflict || out["error"] != billingCopyOpEvidence { |
| + t.Fatalf("a note without evidence: %d %v", status, out) |
| + } |
| + if status, out := postJSON(t, closeURL, map[string]any{"note": "executed per the request log"}, operator); status != http.StatusConflict || out["error"] != billingCopyOpExecutedUnseen { |
| + t.Fatalf("executed but not visible: %d %v", status, out) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("a refused close changed the op: %+v", row) |
| + } |
| + if status, _ := postJSON(t, closeURL, map[string]any{"note": "not-executed per the request log"}, operator); status != http.StatusOK { |
| + t.Fatalf("not-executed: %d", status) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opAbandoned { |
| + t.Fatalf("row after not-executed = %+v", row) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + |
| + // A fresh read showing the target settles and closes, whatever the note. |
| + o.observe() |
| + op2 := o.packOp(t, "op_2", "sub_1", "apps", 4, billing.ProrateNow, opPack) |
| + o.fake.Cached500After = true |
| + if out, _, err := o.send(t, op2); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_1", problemOperationUnresolved, "test", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + open, _ = o.st.BillingProblems(false) |
| + if status, _ := postJSON(t, billingCloseURL(o.consoleFixture, open[0].ID), map[string]any{"note": "checked"}, operator); status != http.StatusOK { |
| + t.Fatalf("close with the target visible: %d", status) |
| + } |
| + if row := o.op(t, "op_2"); row.State != opApplied { |
| + t.Fatalf("row after the evidenced close = %+v", row) |
| + } |
| + if o.fake.Writes() != 2 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestOneOutstandingPerSubscription(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + first := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + first.FirstSentAt, first.State = o.providerClock(), opSending |
| + if err := o.st.BeginBillingOp(first); err != nil { |
| + t.Fatal(err) |
| + } |
| + second := o.packOp(t, "op_2", "sub_1", "apps", 2, billing.ProrateNone, opPack) |
| + for _, state := range []string{opSending, opUnresolved, opPending} { |
| + if err := o.st.PutBillingOpState("op_1", state, false, billingNow); err != nil && state != opSending { |
| + t.Fatal(err) |
| + } |
| + if err := o.st.BeginBillingOp(second); !errors.Is(err, ErrOpOutstanding) { |
| + t.Fatalf("with op_1 %s: BeginBillingOp = %v, want ErrOpOutstanding", state, err) |
| + } |
| + } |
| + if _, _, err := o.send(t, second); !errors.Is(err, ErrOpOutstanding) { |
| + t.Fatalf("sendOpLocked with an outstanding op = %v", err) |
| + } |
| + if len(o.sent()) != 0 { |
| + t.Fatal("a refused op was sent") |
| + } |
| + if err := o.st.PutBillingOpState("op_1", opFailed, false, billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := o.st.BeginBillingOp(second); err != nil { |
| + t.Fatalf("after op_1 failed: %v", err) |
| + } |
| + // FirstSentAt is write-once: no later write moves it. |
| + if err := o.st.NoteOpSent("op_2", o.providerClock().Add(time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if row := o.op(t, "op_2"); !row.FirstSentAt.Equal(second.FirstSentAt) || !row.LastSentAt.Equal(o.providerClock().Add(time.Hour)) { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + // applied only through MarkOpApplied. |
| + if err := o.st.PutBillingOpState("op_2", opApplied, false, billingNow); err == nil { |
| + t.Fatal("PutBillingOpState wrote applied") |
| + } |
| +} |
| + |
| +func TestReorderedWebhooksSettleOnce(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + item := o.packItem(t, "sub_1", "apps") |
| + o.setQuantity("sub_1", item.PriceID, 3) // the provider applied it; the console never heard |
| + for i, now := range []time.Time{billingNow, billingNow.Add(time.Hour), billingNow.Add(2 * time.Hour)} { |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + row := o.op(t, "op_1") |
| + if row.State != opApplied || !row.SettledAt.Equal(billingNow) || !row.AppliedPeriodEnd.Equal(periodEnd) { |
| + t.Fatalf("delivery %d: row = %+v", i, row) |
| + } |
| + } |
| + if o.fake.Writes() != 0 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +// ---- crashes and recovery ------------------------------------------------------ |
| + |
| +func TestCrashBeforeSendRecovered(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.CrashBeforeSend = true |
| + if _, _, err := o.send(t, op); !errors.Is(err, billingtest.ErrCrash) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opSending { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if len(o.counts()) != 0 { |
| + t.Fatalf("the Fake saw %v", o.counts()) |
| + } |
| + o.restart(t) |
| + o.pass(billingNow) |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("the pass did not adopt the orphan: %+v", row) |
| + } |
| + if o.fake.Writes() != 0 { |
| + t.Fatalf("the pass wrote: %d", o.fake.Writes()) |
| + } |
| + if got := o.openProblems(t); len(got) != 0 { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + o.reset() |
| + if status, loc := o.confirm(t); status != http.StatusSeeOther || loc != "/a/"+o.acct.Sqid+"/billing" { |
| + t.Fatalf("confirm = %d %q", status, loc) |
| + } |
| + sent := o.sent() |
| + if len(sent) != 1 || !samePrepared(&sent[0], &op.Prepared) { |
| + t.Fatalf("sent = %+v, want the stored bytes once", sent) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opApplied { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if o.fake.Writes() != 1 || o.counts()["Subscription"] < 1 { |
| + t.Fatalf("calls = %v", o.counts()) |
| + } |
| +} |
| + |
| +func TestCrashAfterSendRecovered(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.CrashAfterSend = true |
| + if _, _, err := o.send(t, op); !errors.Is(err, billingtest.ErrCrash) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opSending { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if o.packItem(t, "sub_1", "apps").Quantity != 3 { |
| + t.Fatal("the Fake did not apply the request") |
| + } |
| + o.restart(t) |
| + if status, _ := o.confirm(t); status != http.StatusSeeOther { |
| + t.Fatalf("confirm = %d", status) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opApplied { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("resent an applied request: writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +func TestOrphanedSendingEscalates(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.CrashBeforeSend = true |
| + if _, _, err := o.send(t, op); !errors.Is(err, billingtest.ErrCrash) { |
| + t.Fatalf("err = %v", err) |
| + } |
| + o.restart(t) |
| + o.fake.AdvanceProvider(resendLifetime + time.Hour) |
| + o.pass(billingNow) |
| + if row := o.op(t, "op_1"); row.State != opUnresolved { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if got := o.openProblems(t); !slices.Equal(got, []string{problemOperationUnresolved}) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| + if o.fake.Writes() != 0 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| +} |
| + |
| +// ---- provider time ---------------------------------------------------------- |
| + |
| +func TestHeaderlessReadCostsOneProbe(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + o.headerlessReads(false) |
| + o.fresh() |
| + if out, err := o.finish(t, "op_1"); err != nil || out.State != opApplied { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 1, "ClockProbe": 1, "Send": 1}) |
| +} |
| + |
| +func TestStaleObservationCostsOneProbe(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.headerlessReads(false) |
| + o.srv.billing.wait = func(context.Context, time.Duration) { o.fake.AdvanceMonotonic(61 * time.Second) } |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.fake.FailBeforeDelivery = 2 |
| + if out, _, err := o.send(t, op); err != nil || out.State != opApplied { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + // 1 + N x (2 + P): two retries, each a read, a probe and a resend. |
| + wantCounts(t, o.counts(), map[string]int{"Send": 3, "Subscription": 2, "ClockProbe": 2}) |
| +} |
| + |
| +func TestFailedProbeSendsNothing(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + o.headerlessReads(false) |
| + o.fake.ProbeErr = errors.New("probe down") |
| + o.fresh() |
| + if out, err := o.finish(t, "op_1"); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 1, "ClockProbe": 1}) |
| +} |
| + |
| +func TestObservationOlderThan60sIsNotUsed(t *testing.T) { |
| + o := newOpsFixture(t, nil) |
| + o.observe() |
| + o.fake.AdvanceMonotonic(30 * time.Second) |
| + got, err := o.srv.providerNow(o.ctx) |
| + if err != nil || !got.Equal(o.providerClock().Add(30*time.Second)) || len(o.counts()) != 0 { |
| + t.Fatalf("within 60 s: %v %v calls %v", got, err, o.counts()) |
| + } |
| + o.fake.AdvanceMonotonic(31 * time.Second) |
| + got, err = o.srv.providerNow(o.ctx) |
| + if err != nil || !got.Equal(o.providerClock()) { |
| + t.Fatalf("past 60 s: %v %v", got, err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1}) |
| + // A failed probe is no provider time at all. |
| + o.fake.AdvanceMonotonic(61 * time.Second) |
| + o.fake.ProbeErr = errors.New("probe down") |
| + if _, err := o.srv.providerNow(o.ctx); !errors.Is(err, billing.ErrNoProviderTime) { |
| + t.Fatalf("failed probe: err = %v", err) |
| + } |
| +} |
| + |
| +func TestRestoreNeedsProviderTime(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 3}) |
| + item := o.packItem(t, "sub_1", "apps") |
| + o.setQuantity("sub_1", item.PriceID, 1) |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNone, opRestore) |
| + o.fresh() |
| + o.fake.ProbeErr = errors.New("probe down") |
| + var refusal billingRefusal |
| + _, _, err := o.send(t, op) |
| + if !errors.As(err, &refusal) || refusal.Key != "change.clock" { |
| + t.Fatalf("err = %v, want the change.clock refusal", err) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1}) |
| + if row, err := o.st.BillingOp("op_1"); err != nil || row != nil { |
| + t.Fatalf("an op was written without provider time: %+v %v", row, err) |
| + } |
| + if _, ok := billingCopy["change.clock"]; !ok { |
| + t.Fatal("change.clock has no copy") |
| + } |
| +} |
| + |
| +// The proration_date half; the expires_at half is Task 9's (Checkout), under |
| +// this same name's scenario there (Ruling R2). |
| +func TestExpiresAtAndProrationDateUseProviderTime(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.fake.SetConsoleClock(o.providerClock().Add(3 * time.Hour)) |
| + o.observe() |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + var body struct { |
| + ProrationDate int64 `json:"proration_date"` |
| + } |
| + if err := json.Unmarshal(op.Prepared.Body, &body); err != nil { |
| + t.Fatal(err) |
| + } |
| + if body.ProrationDate != o.providerClock().Unix() { |
| + t.Fatalf("proration_date = %d, want provider time %d", body.ProrationDate, o.providerClock().Unix()) |
| + } |
| + if body.ProrationDate == o.fake.ConsoleNow().Unix() { |
| + t.Fatal("proration_date followed the console's wall clock") |
| + } |
| +} |
| + |
| +func TestFirstSendUnderSkewThenLateRecoveryRefused(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.fake.SetConsoleClock(o.providerClock().Add(3 * time.Hour)) |
| + consoleNow := o.fake.ConsoleNow() |
| + o.observe() |
| + op := o.renewalOp(t, "op_1", "sub_1", false) |
| + o.fake.FailBeforeDelivery = 1 |
| + o.fake.BeforeSubscription = func(string) error { return errors.New("read failed") } // the retry's read fails: stop, unresolved |
| + h, release := o.hold() |
| + out, _, err := o.srv.sendOpLocked(h, o.ctx, op, consoleNow) |
| + release() |
| + if err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + o.fake.BeforeSubscription = nil |
| + if row := o.op(t, "op_1"); !row.FirstSentAt.Equal(o.providerClock()) || row.FirstSentAt.Equal(consoleNow) { |
| + t.Fatalf("FirstSentAt = %v, want the provider's %v", row.FirstSentAt, o.providerClock()) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("writes = %d", o.fake.Writes()) |
| + } |
| + o.fake.SetConsoleClock(o.providerClock()) // the wall clock is corrected |
| + o.restart(t) |
| + o.fake.AdvanceProvider(24*time.Hour + 30*time.Minute) |
| + if status, _ := o.confirm(t); status != http.StatusSeeOther { |
| + t.Fatalf("confirm = %d", status) |
| + } |
| + if o.fake.Writes() != 1 { |
| + t.Fatalf("resent past the lifetime: writes = %d", o.fake.Writes()) |
| + } |
| + o.pass(o.fake.ConsoleNow()) |
| + if got := o.openProblems(t); !slices.Equal(got, []string{problemOperationUnresolved}) { |
| + t.Fatalf("problems = %v", got) |
| + } |
| +} |
| + |
| +func TestFirstSendUnderSkewRecoveryInsideWindow(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.fake.SetConsoleClock(o.providerClock().Add(3 * time.Hour)) |
| + o.observe() |
| + op := o.renewalOp(t, "op_1", "sub_1", false) |
| + o.fake.FailBeforeDelivery = 1 |
| + o.fake.BeforeSubscription = func(string) error { return errors.New("read failed") } |
| + h, release := o.hold() |
| + out, _, err := o.srv.sendOpLocked(h, o.ctx, op, o.fake.ConsoleNow()) |
| + release() |
| + if err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + o.fake.BeforeSubscription = nil |
| + o.fake.SetConsoleClock(o.providerClock().Add(-5 * 24 * time.Hour)) // and now far behind: irrelevant both ways |
| + o.restart(t) |
| + o.fake.AdvanceProvider(21 * time.Hour) |
| + if status, _ := o.confirm(t); status != http.StatusSeeOther { |
| + t.Fatalf("confirm = %d", status) |
| + } |
| + if o.fake.Writes() != 2 { |
| + t.Fatalf("writes = %d, want the resend", o.fake.Writes()) |
| + } |
| + if row := o.op(t, "op_1"); row.State != opApplied || !o.sub("sub_1").CancelAtPeriodEnd { |
| + t.Fatalf("row = %+v sub cancel %v", row, o.sub("sub_1").CancelAtPeriodEnd) |
| + } |
| +} |
| + |
| +// TestQuietCustomerRecoveryUsesProbe is written in Task 9 (customer create). |
| +// TestHeaderlessTimeoutRecoveredThroughProbe is written in Task 9 (customer create). |
| + |
| +// ---- passes ------------------------------------------------------------------ |
| + |
| +func TestPassesNeverWrite(t *testing.T) { |
| + if found := passSourceWrites(t); len(found) != 0 { |
| + t.Fatalf("billingpass.go writes to the provider: %v", found) |
| + } |
| + o := newOpsFixture(t, map[string]int64{"apps": 3}) |
| + item := o.packItem(t, "sub_1", "apps") |
| + o.setQuantity("sub_1", item.PriceID, 1) |
| + if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil { |
| + t.Fatal(err) |
| + } |
| + o.observe() |
| + restore := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNone, opRestore) |
| + o.fake.ApplyAfterRenewal(restore.Prepared.Key) |
| + if out, _, err := o.send(t, restore); err != nil || out.State != opUnresolved { |
| + t.Fatalf("outcome = %+v %v", out, err) |
| + } |
| + before := o.fake.Writes() |
| + if err := o.fake.Renew("sub_1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := 0; i < 3; i++ { |
| + o.pass(billingNow.Add(time.Duration(i) * time.Hour)) |
| + } |
| + if o.fake.Writes() != before { |
| + t.Fatalf("the pass wrote: %d, was %d", o.fake.Writes(), before) |
| + } |
| +} |
| + |
| +func TestReadinessBackoff(t *testing.T) { |
| + want := map[int]time.Duration{0: time.Second, 1: time.Second, 2: 2 * time.Second, 3: 4 * time.Second, 4: 8 * time.Second, |
| + 5: 16 * time.Second, 6: 30 * time.Minute, 7: 30 * time.Minute, 100: 30 * time.Minute} |
| + for failures, d := range want { |
| + if got := billingCheckDelay(failures); got != d { |
| + t.Errorf("billingCheckDelay(%d) = %v, want %v", failures, got, d) |
| + } |
| + } |
| +} |
| + |
| +// ---- the Confirm now door ------------------------------------------------------- |
| + |
| +func TestBillingConfirmDoor(t *testing.T) { |
| + o := newOpsFixture(t, map[string]int64{"apps": 1}) |
| + o.signInOwner(t) |
| + // Billing off: 404. |
| + off := newConsoleFixture(t) |
| + c := signInPaul(t, off) |
| + if status, _, _ := postForm(t, c, off.u("/billing/confirm"), url.Values{"csrf": {sessionToken(t, off, c)}}); status != http.StatusNotFound { |
| + t.Fatalf("billing off: %d, want 404", status) |
| + } |
| + // A member, not an owner: 404. |
| + if err := o.st.AddMember(o.acct.ID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + kim := newBrowser(t) |
| + o.setUser("kim@keymail.dev") |
| + signUp(t, o.consoleFixture, kim, "code-kim-confirm") |
| + if status, _, _ := postForm(t, kim, o.ts.URL+"/a/"+o.acct.Sqid+"/billing/confirm", url.Values{"csrf": {sessionToken(t, o.consoleFixture, kim)}}); status != http.StatusNotFound { |
| + t.Fatalf("member: %d, want 404", status) |
| + } |
| + // The owner without CSRF: 403. |
| + if status, _, _ := postForm(t, o.owner, o.ts.URL+"/a/"+o.acct.Sqid+"/billing/confirm", url.Values{}); status != http.StatusForbidden { |
| + t.Fatalf("no csrf: %d, want 403", status) |
| + } |
| + // The owner, nothing outstanding: a refresh, then back to the page. |
| + o.reset() |
| + status, loc, _ := postForm(t, o.owner, o.ts.URL+"/a/"+o.acct.Sqid+"/billing/confirm", url.Values{"csrf": {o.csrf}}) |
| + if status != http.StatusSeeOther || loc != "/a/"+o.acct.Sqid+"/billing" { |
| + t.Fatalf("owner: %d %q", status, loc) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 1}) |
| + // With an unresolved op: F + S, and the flash says it is done. |
| + op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack) |
| + o.unresolved(t, op) |
| + o.reset() |
| + status, loc, _ = postForm(t, o.owner, o.ts.URL+"/a/"+o.acct.Sqid+"/billing/confirm", url.Values{"csrf": {o.csrf}}) |
| + if status != http.StatusSeeOther || loc != "/a/"+o.acct.Sqid+"/billing" { |
| + t.Fatalf("owner with an op: %d %q", status, loc) |
| + } |
| + wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1}) |
| + if row := o.op(t, "op_1"); row.State != opApplied { |
| + t.Fatalf("row = %+v", row) |
| + } |
| + if !reflect.DeepEqual(o.sent()[0], op.Prepared) { |
| + t.Fatalf("sent %+v, want the stored bytes", o.sent()[0]) |
| + } |
| +} |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| new file mode 100644 |
| index 000000000..134c23d64 |
| --- /dev/null |
| +++ b/internal/console/billingpage_copy.go |
| @@ -0,0 +1,19 @@ |
| +package console |
| + |
| +// billingCopy is the billing page's copy (plans 6b): notices, buttons and |
| +// the flashes the billing doors leave. Tests compare against this map, never |
| +// literal text. These are the plan's drafts, verbatim; the Luna pass |
| +// replaces them. House rules: no em dashes, plain words. |
| +// |
| +// The page itself (Task 8) and the change doors (Task 10) add their keys |
| +// here. The change.* keys below are the plan's drafts for Task 10, declared |
| +// here because Confirm now and the refusals of this task use them. |
| +var billingCopy = map[string]string{ |
| + "change.done": "Done. Your new limits apply now.", |
| + "change.pending": "Your card didn't go through, so nothing changed. Pay from Payment and invoices to finish.", |
| + "change.declined": "Your card was declined, so nothing changed.", |
| + "change.uncertain": "We couldn't confirm that change yet. Use Confirm now. Nothing more will be charged.", |
| + "change.failed": "We couldn't make that change. Try again in a minute.", |
| + "change.retry": "Your plan just renewed. Try again in a minute.", |
| + "change.clock": "We can't make that change right now. Try again in a few minutes.", |
| +} |
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go| index ba6c0347e..452e57eaa 100644 |
| --- a/internal/console/billingpass.go |
| +++ b/internal/console/billingpass.go |
| @@ -14,10 +14,25 @@ const ( |
| // billingSyncInterval is how often every live subscription is re-read: |
| // the net under a lost webhook. |
| billingSyncInterval = time.Hour |
| - // billingCheckRetry is how often a failed readiness check is retried. |
| - billingCheckRetry = time.Minute |
| + // billingCheckLong is the readiness retry once the short backoff is |
| + // spent (plans 6b): a failing provider is asked again every half hour. |
| + billingCheckLong = 30 * time.Minute |
| ) |
| +// billingCheckDelay is the wait before the next readiness attempt after |
| +// failures consecutive failed ones: 1, 2, 4, 8 and 16 s, then every |
| +// billingCheckLong. Readiness is 34 requests an attempt, so it does not |
| +// hammer a failing provider. |
| +func billingCheckDelay(failures int) time.Duration { |
| + if failures < 1 { |
| + failures = 1 |
| + } |
| + if failures > 5 { |
| + return billingCheckLong |
| + } |
| + return time.Second << (failures - 1) |
| +} |
| + |
| // billingDiscoveryWindow is how long after binding a customer the pass |
| // asks the provider for its subscriptions, when none is recorded: longer |
| // than the provider's three days of webhook retries. |
| @@ -43,15 +58,16 @@ func (s *Server) billingReadyCheck(ctx context.Context) error { |
| } |
| // StartBillingSyncPass is the billing worker (plans 6a). With billing off |
| -// it returns at once. Otherwise it retries the readiness check every |
| -// billingCheckRetry until it passes, logging a failure only when its text |
| -// changes, then syncs every live subscription now and every |
| +// it returns at once. Otherwise it retries the readiness check, backing off |
| +// per billingCheckDelay, until it passes, logging a failure only when its |
| +// text changes, then syncs every live subscription now and every |
| // billingSyncInterval. |
| func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| if s.billing == nil { |
| return |
| } |
| last := "" |
| + failures := 0 |
| for { |
| err := s.billingReadyCheck(ctx) |
| if err == nil { |
| @@ -60,6 +76,7 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| } |
| break |
| } |
| + failures++ |
| if err.Error() != last { |
| last = err.Error() |
| log.Printf("console: billing not ready: %v", err) |
| @@ -67,7 +84,7 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| select { |
| case <-ctx.Done(): |
| return |
| - case <-time.After(billingCheckRetry): |
| + case <-time.After(billingCheckDelay(failures)): |
| } |
| } |
| t := time.NewTicker(billingSyncInterval) |
| @@ -83,11 +100,18 @@ func (s *Server) StartBillingSyncPass(ctx context.Context) { |
| } |
| // billingSyncPass re-reads every live subscription, serially, paging by |
| -// account id. One account's error never stops the others. |
| +// account id, then observes outstanding operations and open restore |
| +// obligations (plans 6b) and runs discovery. One account's error never |
| +// stops the others. The round shares one provider-time recorder: an |
| +// observation at most observationMaxAge old serves every decision in the |
| +// round, and a decision reached after it expires probes again. The pass |
| +// never writes to the provider (Invariant 5). |
| func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| if s.billing == nil || !s.billing.ready.Load() { |
| return |
| } |
| + ctx = s.billingClock(ctx) |
| + synced := map[string]bool{} |
| var after int64 |
| for ctx.Err() == nil { |
| page, err := s.store.LiveBillingAccounts(after, billingSyncBatch) |
| @@ -99,15 +123,113 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) { |
| after = b.AccountID |
| if err := s.syncSubscription(ctx, b.Subscription, now); err != nil { |
| log.Printf("console: billing sync pass: account %d: %v", b.AccountID, err) |
| + } else { |
| + synced[b.Subscription] = true |
| } |
| } |
| if len(page) < billingSyncBatch { |
| break |
| } |
| } |
| + s.billingOpsPass(ctx, now, synced) |
| + s.billingRestorePass(ctx, now, synced) |
| s.billingDiscoveryPass(ctx, now) |
| } |
| +// billingOpsPass observes every outstanding operation (Call 17, Invariant |
| +// 8): its subscription is synced under the hold, unless this round already |
| +// did, which adopts an orphaned sending row and settles on positive |
| +// evidence; then an operation still sending or unresolved that |
| +// recoveryEligible says can never become eligible again (indeterminate, or |
| +// past its window by the round's provider time) opens operation_unresolved. |
| +// A pending operation never escalates. With no provider time nothing is |
| +// escalated this round. Reads and problems only: 0 writes. |
| +func (s *Server) billingOpsPass(ctx context.Context, now time.Time, synced map[string]bool) { |
| + after := "" |
| + for ctx.Err() == nil { |
| + page, err := s.store.OutstandingBillingOps(after, billingSyncBatch) |
| + if err != nil { |
| + log.Printf("console: billing ops pass: %v", err) |
| + return |
| + } |
| + for _, op := range page { |
| + after = op.ID |
| + s.observeOp(ctx, op, now, synced) |
| + } |
| + if len(page) < billingSyncBatch { |
| + return |
| + } |
| + } |
| +} |
| + |
| +func (s *Server) observeOp(ctx context.Context, op billingOp, now time.Time, synced map[string]bool) { |
| + acct, err := s.store.AccountByID(op.AccountID) |
| + if err != nil || acct == nil { |
| + log.Printf("console: billing ops pass: operation %s: account %d: %v", op.ID, op.AccountID, err) |
| + return |
| + } |
| + h, release := s.holdBilling(acct.Sqid) |
| + defer release() |
| + if !synced[op.Subscription] { |
| + if err := s.syncSubscriptionLocked(h, ctx, acct, op.Subscription, now); err != nil { |
| + log.Printf("console: billing ops pass: operation %s: %v", op.ID, err) |
| + return |
| + } |
| + synced[op.Subscription] = true |
| + } |
| + cur, err := s.store.BillingOp(op.ID) |
| + if err != nil || cur == nil { |
| + log.Printf("console: billing ops pass: operation %s: %v", op.ID, err) |
| + return |
| + } |
| + if cur.State != opSending && cur.State != opUnresolved { |
| + return // settled by the read, or pending, which follows the provider's own lifecycle |
| + } |
| + pnow, err := s.providerNow(ctx) |
| + if err != nil { |
| + log.Printf("console: billing ops pass: operation %s: no provider time; not escalated this round", cur.ID) |
| + return |
| + } |
| + ok, reason := recoveryEligible(s.resendStateOf(cur, nil, now), pnow) |
| + if ok || !permanentlyIneligible(reason) { |
| + return |
| + } |
| + detail := fmt.Sprintf("operation %s (%s) has no definite outcome and cannot be resent (%s); check the request log in the dashboard", cur.ID, cur.Kind, reason) |
| + if err := s.openBillingProblem(acct.ID, acct.Sqid, cur.Subscription, problemOperationUnresolved, detail, now); err != nil { |
| + log.Printf("console: billing ops pass: operation %s: %v", cur.ID, err) |
| + } |
| +} |
| + |
| +// billingRestorePass syncs, under the hold, every subscription with an open |
| +// restore obligation this round has not already synced (Risk R1): the sync |
| +// runs restoreCheckLocked, so an obligation whose renewal was saved before a |
| +// crash is still checked. Reads and problems only: 0 writes. |
| +func (s *Server) billingRestorePass(ctx context.Context, now time.Time, synced map[string]bool) { |
| + open, err := s.store.OpenRestoreChecksAll(billingSyncBatch) |
| + if err != nil { |
| + log.Printf("console: billing restore pass: %v", err) |
| + return |
| + } |
| + for _, c := range open { |
| + if ctx.Err() != nil || synced[c.Subscription] { |
| + continue |
| + } |
| + acct, err := s.store.AccountByID(c.AccountID) |
| + if err != nil || acct == nil { |
| + log.Printf("console: billing restore pass: obligation %s: account %d: %v", c.OpID, c.AccountID, err) |
| + continue |
| + } |
| + h, release := s.holdBilling(acct.Sqid) |
| + err = s.syncSubscriptionLocked(h, ctx, acct, c.Subscription, now) |
| + release() |
| + if err != nil { |
| + log.Printf("console: billing restore pass: obligation %s: %v", c.OpID, err) |
| + continue |
| + } |
| + synced[c.Subscription] = true |
| + } |
| +} |
| + |
| // billingDiscoveryPass asks the provider for the live subscriptions of |
| // each customer bound within billingDiscoveryWindow that has none |
| // recorded, or whose last discovery left a candidate unsynced, and syncs |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index 179427c9e..ee606451d 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -63,8 +63,29 @@ const ( |
| problemNotBillingOwned = "not_billing_owned" |
| problemSubscriptionMissing = "subscription_missing" |
| problemDiscoveryFailing = "discovery_failing" |
| + |
| + // Plans 6b. operation_unresolved: a prepared request with no definite |
| + // outcome that can never be resent (Call 17). restore_after_renewal: a |
| + // restore first applied after the renewal that should have billed it |
| + // (Risk R1). restore_check_stalled: that verification still open seven |
| + // provider-time days after the renewal. |
| + problemOperationUnresolved = "operation_unresolved" |
| + problemRestoreAfterRenewal = "restore_after_renewal" |
| + problemRestoreCheckStalled = "restore_check_stalled" |
| ) |
| +// problemClosableWhileLive is a reason an operator closes while the |
| +// subscription is live: these problems are about a live subscription, and |
| +// closing them records what the operator did in the Dashboard. 6a's reasons |
| +// are closed only once the subscription has ended there. |
| +func problemClosableWhileLive(reason string) bool { |
| + switch reason { |
| + case problemOperationUnresolved, problemRestoreAfterRenewal, problemRestoreCheckStalled: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| func (s *Store) migrateBillingAccounts() error { |
| _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_accounts ( |
| account_id INTEGER PRIMARY KEY, |
| @@ -173,6 +194,40 @@ CREATE TABLE IF NOT EXISTS billing_restore_checks ( |
| created_at INTEGER NOT NULL, |
| checked_at INTEGER NOT NULL DEFAULT 0 |
| );`) |
| + if err != nil { |
| + return err |
| + } |
| + return s.migrateBillingOperations() |
| +} |
| + |
| +// migrateBillingOperations adds plans 6b's operations table (one prepared |
| +// request per row) and the stall mark on restore checks. The partial unique |
| +// index is Invariant 7's "one outstanding operation per subscription": its |
| +// state list is pinned to opOutstanding by TestOpOutstandingMatchesIndex. |
| +func (s *Store) migrateBillingOperations() error { |
| + if _, err := s.db.Exec(`ALTER TABLE billing_restore_checks ADD COLUMN stalled_at INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") { |
| + return err |
| + } |
| + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_operations ( |
| + id TEXT PRIMARY KEY, |
| + account_id INTEGER NOT NULL, |
| + subscription TEXT NOT NULL, |
| + kind TEXT NOT NULL, |
| + period_end INTEGER NOT NULL, |
| + target TEXT NOT NULL, |
| + prepared BLOB NOT NULL, |
| + invite_token TEXT NOT NULL DEFAULT '', |
| + authorised_by TEXT NOT NULL DEFAULT '', |
| + state TEXT NOT NULL, |
| + indeterminate INTEGER NOT NULL DEFAULT 0, |
| + first_sent_at INTEGER NOT NULL DEFAULT 0, |
| + last_sent_at INTEGER NOT NULL DEFAULT 0, |
| + settled_at INTEGER NOT NULL DEFAULT 0, |
| + applied_period_end INTEGER NOT NULL DEFAULT 0, |
| + created_at INTEGER NOT NULL |
| +); |
| +CREATE UNIQUE INDEX IF NOT EXISTS billing_operations_outstanding ON billing_operations(subscription) WHERE state IN ('sending', 'unresolved', 'pending'); |
| +CREATE INDEX IF NOT EXISTS billing_operations_invite ON billing_operations(invite_token) WHERE invite_token != '';`) |
| return err |
| } |
| @@ -417,7 +472,14 @@ func scanBillingProblem(sc interface{ Scan(...any) error }) (*billingProblem, er |
| // OpenBillingProblem opens a problem unless one is already open for the |
| // same account, subscription and reason, and reports whether it opened one. |
| func (s *Store) OpenBillingProblem(accountID int64, subscription, reason, detail string, now time.Time) (bool, error) { |
| - res, err := s.db.Exec(`INSERT INTO billing_problems (account_id, subscription, reason, detail, opened_at) |
| + return openBillingProblemTx(s.db, accountID, subscription, reason, detail, now) |
| +} |
| + |
| +// openBillingProblemTx is OpenBillingProblem's statement on a store handle or |
| +// a transaction, so a problem opens in the same transaction as the state it |
| +// reports (a flagged restore check, plans 6b). |
| +func openBillingProblemTx(e sqlExecer, accountID int64, subscription, reason, detail string, now time.Time) (bool, error) { |
| + res, err := e.Exec(`INSERT INTO billing_problems (account_id, subscription, reason, detail, opened_at) |
| VALUES (?, ?, ?, ?, ?) ON CONFLICT(account_id, subscription, reason) WHERE closed_at = 0 DO NOTHING`, |
| accountID, subscription, reason, detail, now.Unix()) |
| if err != nil { |
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go| index e06754ce4..0534d2ee5 100644 |
| --- a/internal/console/billingsync.go |
| +++ b/internal/console/billingsync.go |
| @@ -206,8 +206,20 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no |
| log.Printf("console: billing: subscription %s belongs to deleted account %d; nothing changed", subscriptionID, bound.AccountID) |
| return nil |
| } |
| + h, release := s.holdBilling(acct.Sqid) |
| + defer release() |
| + return s.syncSubscriptionLocked(h, ctx, acct, subscriptionID, now) |
| +} |
| - defer s.billing.locks.lock(acct.Sqid)() |
| +// syncSubscriptionLocked is the sync proper, under the account's billing |
| +// hold: the deciding read, the decision and its commit, then what the read |
| +// proves about the subscription's outstanding operation (settleOpsLocked) |
| +// and its open restore obligations (restoreCheckLocked). ctx should carry a |
| +// provider-time recorder (billingClock) so those decisions have provider |
| +// time without a probe. |
| +func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) error { |
| + cfg := s.billing.cfg |
| + ctx = s.billingClock(ctx) |
| sub, err := cfg.Provider.Subscription(ctx, subscriptionID) |
| if errors.Is(err, billing.ErrNotFound) { |
| return s.subscriptionMissing(subscriptionID, now) |
| @@ -242,7 +254,78 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no |
| prev.State, prev.ProviderStatus = old.State, old.ProviderStatus |
| } |
| } |
| - return s.applyBillingRead(ctx, acct, prev, sub, now) |
| + if err := s.applyBillingRead(ctx, acct, prev, sub, now); err != nil { |
| + return err |
| + } |
| + if err := s.settleOpsLocked(h, acct, sub, now); err != nil { |
| + return err |
| + } |
| + return s.restoreCheckLocked(h, ctx, acct, sub, now) |
| +} |
| + |
| +// refreshLocked is the plain sync of the account's recorded subscription |
| +// under the hold (Invariant 4): one read, applied, with the operation |
| +// settlement and restore checks every read gets. It returns the billing row |
| +// as it then stands and the read; the read is nil when the account records |
| +// no subscription, or the provider has none (a subscription_missing problem |
| +// opens, as in any sync). It makes no period requirement. |
| +func (s *Server) refreshLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, error) { |
| + prev, err := s.store.BillingAccount(acct.ID) |
| + if err != nil || prev == nil || prev.Subscription == "" { |
| + return prev, nil, err |
| + } |
| + cfg := s.billing.cfg |
| + sub, err := cfg.Provider.Subscription(ctx, prev.Subscription) |
| + if errors.Is(err, billing.ErrNotFound) { |
| + return prev, nil, s.subscriptionMissing(prev.Subscription, now) |
| + } |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("billing: reading subscription %s: %w", prev.Subscription, err) |
| + } |
| + if prev.Customer != sub.Customer { |
| + return nil, nil, fmt.Errorf("billing: subscription %s belongs to customer %s, not the account's %s", sub.ID, sub.Customer, prev.Customer) |
| + } |
| + if err := s.applyBillingRead(ctx, acct, prev, sub, now); err != nil { |
| + return nil, nil, err |
| + } |
| + if err := s.settleOpsLocked(h, acct, sub, now); err != nil { |
| + return nil, nil, err |
| + } |
| + if err := s.restoreCheckLocked(h, ctx, acct, sub, now); err != nil { |
| + return nil, nil, err |
| + } |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + return b, sub, nil |
| +} |
| + |
| +// The allowance refusals: what a quantity change or a join needs is a live, |
| +// paid, recognised subscription whose paid period the row agrees with. |
| +var ( |
| + errAllowanceEnded = billingRefusal{Key: "change.failed"} |
| + errAllowanceMismatch = billingRefusal{Key: "change.retry"} |
| +) |
| + |
| +// allowanceLocked is refreshLocked plus what a quantity change or a join on |
| +// a paid subscription needs (Invariant 4): the read live and paid, recognised |
| +// against the subscription's book, and the row's paid period equal to the |
| +// read's (a renewal the console had not seen is applied by the refresh |
| +// first, so it passes). Otherwise a billingRefusal. |
| +func (s *Server) allowanceLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (*billingAccount, *billing.Subscription, billing.Purchase, error) { |
| + b, sub, err := s.refreshLocked(h, ctx, acct, now) |
| + if err != nil { |
| + return nil, nil, billing.Purchase{}, err |
| + } |
| + if sub == nil || !sub.Live || sub.State != billing.StatePaid { |
| + return nil, nil, billing.Purchase{}, errAllowanceEnded |
| + } |
| + purchase, unrecognised := billing.Recognise(sub, s.billing.cfg.Prices, s.cfg.PlanCatalog) |
| + if unrecognised != nil || b == nil || b.Subscription != sub.ID || !b.PaidPeriodEnd.Equal(sub.PeriodEnd) { |
| + return nil, nil, billing.Purchase{}, errAllowanceMismatch |
| + } |
| + return b, sub, purchase, nil |
| } |
| // applyBillingRead decides on one fresh read and commits the billing row |
| @@ -305,8 +388,9 @@ func (s *Server) subscriptionMissing(subscriptionID string, now time.Time) error |
| // ended and drops the account to the default plan, through the same |
| // decision and commit as any ended subscription. A subscription the |
| // account has since replaced, or that a sync has since found ended, is |
| -// left alone. The caller holds the account's billing lock. |
| -func (s *Server) endMissingSubscriptionLocked(ctx context.Context, acct *Account, subscriptionID string, now time.Time) error { |
| +// left alone. The caller holds the account's billing hold. |
| +func (s *Server) endMissingSubscriptionLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) error { |
| + _ = h |
| prev, err := s.store.BillingAccount(acct.ID) |
| if err != nil || prev == nil || prev.Subscription != subscriptionID || !liveState(prev.State) { |
| return err |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index d7c478f5b..8d96f803b 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1299,6 +1299,10 @@ var claimFixtures = map[string]claimFixture{ |
| // The billing webhook re-reads a subscription and writes the account's |
| // plan row and billing state (plans 6a). |
| "route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"), |
| + // Plans 6b: an owner's Confirm now finishes an outstanding billing |
| + // operation under the account's billing hold and refreshes the |
| + // subscription. |
| + "route POST /a/{sqid}/billing/confirm": claimNonApp("finishes the account's outstanding billing operation from a fresh provider read and refreshes its subscription, writing billing state, the plan row and billing problems; names no app"), |
| // ---- POST: CLI, account and deployment level ---- |
| "route POST /accounts/new": claimNonApp("creates an account and its owner membership"), |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 7f4d28fee..95e62dc4a 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -691,6 +691,14 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return claimBillingPlanIs(t, cx, "personal") |
| }, |
| }, |
| + "route POST /a/{sqid}/billing/confirm": { |
| + setup: claimBillingWorld, |
| + do: claimFormReply("/a/bab/billing/confirm"), |
| + status: http.StatusSeeOther, loc: "/a/bab/billing", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + return claimBillingPlanIs(t, cx, "personal") |
| + }, |
| + }, |
| "route POST /api/cli/billing/problems/{id}/close": { |
| setup: claimBillingProblemWorld, |
| do: func(t *testing.T, cx *claimCase) claimReply { |
diff --git a/internal/console/server.go b/internal/console/server.go| index 72603c238..1f3a7b16b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1562,6 +1562,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // Plans 4d: owners choose what stays after a lapse (planlapse_keep.go). |
| s.registerRoute("GET /a/{sqid}/plan/keep", s.handlePlanKeep) |
| s.registerRoute("POST /a/{sqid}/plan/keep", s.handlePlanKeepSave) |
| + // Plans 6b: an owner's Confirm now finishes a billing operation left |
| + // without a definite outcome (billingops.go). 404 with billing off. |
| + s.registerRoute("POST /a/{sqid}/billing/confirm", s.handleBillingConfirm) |
| // Go 1.22's mux prefers this literal over apps/{app} below — exactly why |
| // "new" must be a reserved app name (claimApp): an app so named could |
| // never be viewed. |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 24b1858f3..94bb3cec2 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -245,6 +245,7 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "billing_house": {NonApp: "house accounts an operator marked, keyed by account; names no app"}, |
| "billing_retirements": {NonApp: "accounts whose deletion is in progress, keyed by account; names no app"}, |
| "billing_restore_checks": {NonApp: "an account's late-restore verification obligations; names no app"}, |
| + "billing_operations": {NonApp: "an account's billing operations, each one prepared provider request and its outcome, keyed by subscription; names no app"}, |
| } |
| // claimSQLReservedName is the TEMP permit table. A main-schema table by that |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index b2d26da7e..d227eb6bb 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -150,6 +150,7 @@ route POST /a/{sqid}/apps/{app}/restart |
| route POST /a/{sqid}/apps/{app}/rollback |
| route POST /a/{sqid}/apps/{app}/store/destroy |
| route POST /a/{sqid}/apps/{app}/swap |
| +route POST /a/{sqid}/billing/confirm |
| route POST /a/{sqid}/delete |
| route POST /a/{sqid}/errors/level |
| route POST /a/{sqid}/fleets/{fleet}/detach |