carlos / platform Public

console: a retirement gate that finishes outstanding work before judging every live subscription (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6c53c37c8983a6aa924c01ccee8face21de57c21 parent bb8d200
6 files changed, +822 −20
  • internal/console/billingpage_copy.go +7 −0
  • internal/console/billingretire.go +242 −0
  • internal/console/billingretire_test.go +502 −0
  • internal/console/billingseats.go +7 −1
  • internal/console/billingsync.go +18 −10
  • internal/console/ownership.go +46 −9

CI failed — run details

diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index 930bd3df4..42d88b84b 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -54,6 +54,13 @@ var billingCopy = map[string]string{
"checkout.expired": "That payment page has expired. Start again.",
"billing.retiring": "This account is being deleted.",
+ // Account deletion's retirement gate (Task 13).
+ "delete.renewing": "This account renews on %s. Stop renewal first, then you can delete it.",
+ "delete.collecting": "A payment for this account is still being collected. Settle it in Payment and invoices first.",
+ "delete.pending": "A change is still being confirmed or paid for. Finish it first.",
+ "delete.checkout": "A payment for this account is finishing. Try again in a few minutes.",
+ "delete.unverified": "We couldn't check every subscription for this account. Try again later, or ask an operator.",
+
// The page (Task 8).
"page.title": "Billing",
"notice.not_ready": "Billing isn't available right now. Try again in a few minutes.",
diff --git a/internal/console/billingretire.go b/internal/console/billingretire.go
new file mode 100644
index 000000000..a8af7b6e2
--- /dev/null
+++ b/internal/console/billingretire.go
@@ -0,0 +1,242 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "time"
+)
+
+// The retirement gate (plans 6b, Task 13): what account deletion asks of
+// billing before the account goes.
+//
+// An account is deleted only when nothing at the provider can still charge
+// it or change under it: no operation outstanding, no Checkout that is not
+// history, and every live subscription set to end at its period end with
+// nothing being collected. The account is marked retiring
+// (BeginBillingRetirement) under the billing hold before the gate runs, and
+// every purchase, change, renewal, join, invite and seat reduction refuses
+// while it is, so nothing new can start between the gate and the deletion.
+
+// The gate's refusals. delete.renewing carries the period end
+// (retireRenewingRefusal).
+var (
+ errDeletePending = billingRefusal{Key: "delete.pending"}
+ errDeleteCheckout = billingRefusal{Key: "delete.checkout"}
+ errDeleteUnverified = billingRefusal{Key: "delete.unverified"}
+ errDeleteCollecting = billingRefusal{Key: "delete.collecting"}
+)
+
+// retireRenewingRefusal is delete.renewing: a live subscription renews at
+// PeriodEnd.
+type retireRenewingRefusal struct{ PeriodEnd time.Time }
+
+func (r retireRenewingRefusal) Error() string { return "billing: refused: delete.renewing" }
+
+// retireRefusalText is the settings page's flash for an error the gate
+// returns: a refusal's copy, else delete.unverified (the caller logs).
+func retireRefusalText(err error) string {
+ var renewing retireRenewingRefusal
+ if errors.As(err, &renewing) {
+ return fmt.Sprintf(billingCopy["delete.renewing"], billingDate(renewing.PeriodEnd))
+ }
+ var ref billingRefusal
+ if errors.As(err, &ref) {
+ if text, ok := billingCopy[ref.Key]; ok {
+ return text
+ }
+ }
+ return billingCopy["delete.unverified"]
+}
+
+// OutstandingOpsForAccount is every operation of the account still
+// sending, unresolved or pending, on any subscription it records.
+func (s *Store) OutstandingOpsForAccount(accountID int64) ([]billingOp, error) {
+ return s.billingOpsWhere(`account_id = ? AND state IN (?, ?, ?) ORDER BY id`, accountID, opSending, opUnresolved, opPending)
+}
+
+// retireGateLocked decides, under the hold, whether the account may be
+// deleted. The order is load-bearing: the only provider writes are steps 1
+// and 2, and step 3 always runs after them, so what is judged is what those
+// writes left.
+//
+// 1. Outstanding work is finished: every operation left sending or
+// unresolved gets finishOpLocked (a read, and at most one resend of its
+// stored bytes), a pending one a sync of its subscription. Any still
+// outstanding refuses (delete.pending), so an account is never deleted
+// with an operation nobody could close.
+// 2. A Checkout that is not history is resolved: a creating one has its
+// create finished, an open one is read and then expired
+// (replaceIntentLocked). Still not history refuses (delete.checkout).
+// A buyer who paid first leaves a completed intent, whose subscription
+// step 3 judges.
+// 3. Every live subscription of the customer, from an exhaustive list
+// (delete.unverified when it cannot be had), is synced, then must be set
+// to end at its period end (delete.renewing) with nothing being
+// collected and no change waiting for payment (delete.collecting).
+func (s *Server) retireGateLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error {
+ // 1. Outstanding work.
+ ops, err := s.store.OutstandingOpsForAccount(acct.ID)
+ if err != nil {
+ return err
+ }
+ for i := range ops {
+ op := &ops[i]
+ if op.State == opPending {
+ err = s.syncSubscriptionLocked(h, ctx, acct, op.Subscription, now)
+ } else {
+ _, err = s.finishOpLocked(h, ctx, acct, op, now)
+ }
+ if err != nil {
+ log.Printf("console: billing retire %s: finishing operation %s: %v", acct.Sqid, op.ID, err)
+ }
+ }
+ if left, err := s.store.OutstandingOpsForAccount(acct.ID); err != nil {
+ return err
+ } else if len(left) > 0 {
+ return errDeletePending
+ }
+
+ // 2. A Checkout that is not history.
+ ci, err := s.store.CheckoutIntent(acct.ID)
+ if err != nil {
+ return err
+ }
+ if ci != nil && !intentTerminal(ci) {
+ if ci.State == intentOpen {
+ // One session read first: it may already be over, and its Date
+ // is the expiry's provider time.
+ err = s.observeIntentLocked(h, ctx, acct, ci, now)
+ }
+ if err == nil && !intentTerminal(ci) {
+ err = s.replaceIntentLocked(h, ctx, acct, ci, now)
+ }
+ if err != nil {
+ log.Printf("console: billing retire %s: resolving intent %s: %v", acct.Sqid, ci.ID, err)
+ }
+ if !intentTerminal(ci) {
+ return errDeleteCheckout
+ }
+ }
+
+ // 3. Every live subscription, judged last.
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return err
+ }
+ if b == nil || b.Customer == "" {
+ return nil // no customer: nothing at the provider can renew
+ }
+ ids, err := s.billing.cfg.Provider.LiveSubscriptions(ctx, b.Customer)
+ if err != nil {
+ log.Printf("console: billing retire %s: listing subscriptions: %v", acct.Sqid, err)
+ return errDeleteUnverified
+ }
+ for _, id := range ids {
+ sub, err := s.syncSubscriptionReadLocked(h, ctx, acct, id, now)
+ if err != nil || sub == nil {
+ log.Printf("console: billing retire %s: syncing %s: %v", acct.Sqid, id, err)
+ return errDeleteUnverified
+ }
+ if !sub.Live {
+ continue
+ }
+ if !sub.CancelAtPeriodEnd {
+ return retireRenewingRefusal{PeriodEnd: sub.PeriodEnd}
+ }
+ if sub.Collecting || sub.PendingUpdate {
+ return errDeleteCollecting
+ }
+ }
+ return nil
+}
+
+// retireForDeletion is account deletion's billing step, after the owner,
+// CSRF and name checks; it stands in for the step-up gate. On true the
+// caller holds the account's billing hold, the account is retiring and the
+// gate has passed, and it must call release after DeleteAccount. On false
+// it has written the response.
+//
+// With a fresh sign-in proof, one hold covers the retirement mark, the gate
+// and the deletion. The step-up's replay arrives this way too, and finds the
+// mark its first run set. Without one, the gate runs first under the mark
+// (so a refusal never costs a sign-in), the hold is released, and the
+// request is stashed for the step-up; the account stays retiring until the
+// replay, which runs the gate again, or until the mark goes stale.
+func (s *Server) retireForDeletion(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account) (release func(), ok bool) {
+ settings := "/a/" + acct.Sqid + "/settings"
+ refuse := func(err error) {
+ var renewing retireRenewingRefusal
+ var ref billingRefusal
+ if !errors.As(err, &renewing) && !errors.As(err, &ref) {
+ log.Printf("console: billing retire %s: %v", acct.Sqid, err)
+ }
+ s.setFlash(w, "err", retireRefusalText(err))
+ http.Redirect(w, r, settings, http.StatusSeeOther)
+ }
+ ctx := s.billingClock(r.Context())
+ fresh := s.store.FreshStepUp(raw, addr, time.Now(), StepUpWindow)
+ now := time.Now()
+ h, release := s.holdBilling(acct.Sqid)
+ if fresh {
+ if err := s.retireLocked(h, ctx, acct, addr, now); err != nil {
+ release()
+ refuse(err)
+ return nil, false
+ }
+ return release, true
+ }
+ if err := s.store.BeginBillingRetirement(acct.ID, addr, now); err != nil {
+ release()
+ refuse(err)
+ return nil, false
+ }
+ if err := s.retireGateLocked(h, ctx, acct, now); err != nil {
+ s.endRetirement(acct)
+ release()
+ refuse(err)
+ return nil, false
+ }
+ release()
+ if !s.requireFreshAuth(w, r, addr, raw) {
+ return nil, false
+ }
+ // A proof that became fresh meanwhile: the replay's path, now.
+ h, release = s.holdBilling(acct.Sqid)
+ if err := s.retireLocked(h, ctx, acct, addr, time.Now()); err != nil {
+ release()
+ refuse(err)
+ return nil, false
+ }
+ return release, true
+}
+
+// retireLocked is the gate with a fresh sign-in proof: the account is
+// marked retiring if it is not already (the replay finds the mark its first
+// run set), then the gate runs. A refusal clears the mark.
+func (s *Server) retireLocked(h billingHold, ctx context.Context, acct *Account, addr string, now time.Time) error {
+ retiring, err := s.store.BillingRetiring(acct.ID, now)
+ if err != nil {
+ return err
+ }
+ if !retiring {
+ if err := s.store.BeginBillingRetirement(acct.ID, addr, now); err != nil {
+ return err
+ }
+ }
+ if err := s.retireGateLocked(h, ctx, acct, now); err != nil {
+ s.endRetirement(acct)
+ return err
+ }
+ return nil
+}
+
+// endRetirement clears the account's retirement mark after a refused or
+// failed deletion, so the account can be changed again at once.
+func (s *Server) endRetirement(acct *Account) {
+ if err := s.store.EndBillingRetirement(acct.ID); err != nil {
+ log.Printf("console: billing retire %s: clearing the mark: %v", acct.Sqid, err)
+ }
+}
diff --git a/internal/console/billingretire_test.go b/internal/console/billingretire_test.go
new file mode 100644
index 000000000..ea9076c18
--- /dev/null
+++ b/internal/console/billingretire_test.go
@@ -0,0 +1,502 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+// ---- fixture -----------------------------------------------------------------
+
+// newDeleteFixture is an ops fixture whose account can be deleted: its
+// manifest is in the bucket, it holds no app, renewal is on or stopped as
+// asked (and synced), and the owner is signed in with no fresh sign-in
+// proof, counters reset.
+func newDeleteFixture(t *testing.T, packs map[string]int64, renewing bool) *opsFixture {
+ t.Helper()
+ o := newOpsFixture(t, packs)
+ o.deletable(t)
+ if !renewing {
+ o.setRenewal(t, "sub_1", false)
+ }
+ o.signInOwner(t)
+ if err := o.st.ClearStepUp(o.csrf); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ return o
+}
+
+// deletable writes the account's manifest to the bucket, which deletion
+// tombstones.
+func (o *opsFixture) deletable(t *testing.T) {
+ t.Helper()
+ body, err := json.Marshal(domains.AccountManifest{ID: o.acct.ID, Sqid: o.acct.Sqid, Name: o.acct.Name, CreatedAt: time.Unix(1_700_000_000, 0).UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := o.rel.Put(context.Background(), AccountManifestKey(o.acct.Sqid), body, ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// setRenewal sets renewal at the provider (renew false: cancel at period
+// end) and syncs it.
+func (o *opsFixture) setRenewal(t *testing.T, subID string, renew bool) {
+ t.Helper()
+ o.fake.Lock()
+ o.fake.Subs[subID].CancelAtPeriodEnd = !renew
+ o.fake.Unlock()
+ if err := o.srv.syncSubscription(context.Background(), subID, billingNow); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// editSub changes the provider's subscription in place, without a sync.
+func (o *opsFixture) editSub(subID string, edit func(s *billing.Subscription)) {
+ o.fake.Lock()
+ edit(o.fake.Subs[subID])
+ o.fake.Unlock()
+}
+
+func (o *opsFixture) settingsPath() string { return "/a/" + o.acct.Sqid + "/settings" }
+
+// deleteAccount is the owner's Delete account, through ServeHTTP.
+func (o *opsFixture) deleteAccount(t *testing.T) billingReply {
+ t.Helper()
+ return o.request(t, http.MethodPost, "/a/"+o.acct.Sqid+"/delete", url.Values{"confirm": {o.acct.Name}})
+}
+
+// deleteStashed is the owner's Delete account with no fresh sign-in proof,
+// through the owner's browser so the step-up cookie lands in its jar: the
+// gate runs, and on a pass the request is stashed for the step-up. It
+// answers the Keymail redirect.
+func (o *opsFixture) deleteStashed(t *testing.T) string {
+ t.Helper()
+ status, loc, body := postForm(t, o.owner, o.ts.URL+"/a/"+o.acct.Sqid+"/delete",
+ url.Values{"csrf": {o.csrf}, "confirm": {o.acct.Name}})
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, o.fk.srv.URL) {
+ t.Fatalf("delete without a fresh proof = %d %q, want a redirect into Keymail\n%s", status, loc, body)
+ }
+ return loc
+}
+
+// jarFlash is the flash the owner's browser holds.
+func (o *opsFixture) jarFlash(t *testing.T) (kind, msg string) {
+ t.Helper()
+ u, _ := url.Parse(o.ts.URL)
+ for _, ck := range o.owner.Jar.Cookies(u) {
+ if ck.Name == flashCookie && ck.Value != "" {
+ v, _ := url.QueryUnescape(ck.Value)
+ kind, msg, _ = strings.Cut(v, "|")
+ }
+ }
+ return kind, msg
+}
+
+func (o *opsFixture) retiring(t *testing.T) bool {
+ t.Helper()
+ r, err := o.st.BillingRetiring(o.acct.ID, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+// outstandingOps counts the account's operations still sending, unresolved
+// or pending.
+func (o *opsFixture) outstandingOps(t *testing.T) int {
+ t.Helper()
+ var n int
+ if err := o.st.db.QueryRow(`SELECT COUNT(*) FROM billing_operations WHERE account_id = ? AND state IN (?, ?, ?)`,
+ o.acct.ID, opSending, opUnresolved, opPending).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+// wantDeleteRefused is the settings page with the refusal's text, the
+// account still there and no longer retiring.
+func (o *opsFixture) wantDeleteRefused(t *testing.T, r billingReply, text string) {
+ t.Helper()
+ if text == "" {
+ t.Fatal("the refusal's copy is missing from the map")
+ }
+ if r.Status != http.StatusSeeOther || r.Loc != o.settingsPath() || r.Flash != "err" || r.FlashMsg != text {
+ t.Fatalf("delete = %d %q flash %s:%q, want the refusal %q", r.Status, r.Loc, r.Flash, r.FlashMsg, text)
+ }
+ o.wantKept(t)
+}
+
+func (o *opsFixture) wantKept(t *testing.T) {
+ t.Helper()
+ if a, _ := o.st.AccountBySqid(o.acct.Sqid); a == nil {
+ t.Fatal("the account was deleted")
+ }
+ if o.retiring(t) {
+ t.Fatal("a refused deletion left the account retiring")
+ }
+}
+
+// wantDeleted is the account gone, never with an operation outstanding
+// (an unresolved operation on a deleted account cannot be closed).
+func (o *opsFixture) wantDeleted(t *testing.T, status int, flash string) {
+ t.Helper()
+ if status != http.StatusSeeOther || !strings.HasPrefix(flash, "Deleted") {
+ t.Fatalf("delete = %d flash %q, want deleted", status, flash)
+ }
+ if a, _ := o.st.AccountBySqid(o.acct.Sqid); a != nil {
+ t.Fatal("the account survived its deletion")
+ }
+ if n := o.outstandingOps(t); n != 0 {
+ t.Fatalf("deleted with %d operations outstanding", n)
+ }
+ if m := readManifest(t, o.rel, o.acct.Sqid); !m.Deleted() {
+ t.Fatal("the manifest was not tombstoned")
+ }
+}
+
+func renewingText(periodEnd time.Time) string {
+ return fmt.Sprintf(billingCopy["delete.renewing"], billingDate(periodEnd))
+}
+
+// ---- the gate, with a fresh sign-in proof ------------------------------------
+
+// Review Focus 1: renewal stopped, then an owner's resume-renewal request
+// that never reached the provider, then deletion with a fresh proof. The
+// gate finishes the operation first (renewal resumes), then judges: renewing.
+func TestDeleteFinishesOpsBeforeChecksWithFreshProof(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ o.unresolved(t, o.renewalOp(t, "op_resume", "sub_1", true))
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ o.wantDeleteRefused(t, r, renewingText(o.sub("sub_1").PeriodEnd))
+ // F (the read, then the stored bytes) + L(1) + S.
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1, "LiveSubscriptions": 1})
+ if op := o.op(t, "op_resume"); op.State != opApplied {
+ t.Fatalf("op = %+v, want applied", op)
+ }
+ if o.sub("sub_1").CancelAtPeriodEnd {
+ t.Fatal("the resume was not delivered")
+ }
+}
+
+func TestDeleteRefusedWhileRenewing(t *testing.T) {
+ o := newDeleteFixture(t, nil, true)
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), renewingText(o.sub("sub_1").PeriodEnd))
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ if o.fake.Writes() != 0 {
+ t.Fatalf("writes = %d", o.fake.Writes())
+ }
+}
+
+func TestDeleteAfterCompletedPurchaseAndStop(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.deletable(t)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ if _, err := o.fake.CompleteCheckout(ci.Session); err != nil {
+ t.Fatal(err)
+ }
+ if r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil); r.Flash != "ok" {
+ t.Fatalf("done = %+v", r)
+ }
+ if r := o.renewal(t, "stop"); r.Flash != "ok" {
+ t.Fatalf("stop = %+v", r)
+ }
+ o.stepUp(t)
+ o.reset()
+ r := o.deleteAccount(t)
+ // The intent is history; L(1) + S for the one live subscription.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ if o.fake.Writes() != 0 {
+ t.Fatalf("writes = %d", o.fake.Writes())
+ }
+ o.wantDeleted(t, r.Status, r.FlashMsg)
+}
+
+func TestDeleteRefusedWhileCollecting(t *testing.T) {
+ t.Run("collecting", func(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ o.editSub("sub_1", func(s *billing.Subscription) { s.Collecting = true })
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), billingCopy["delete.collecting"])
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ })
+ t.Run("a pending update", func(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ expires := o.providerClock().Add(23 * time.Hour)
+ o.editSub("sub_1", func(s *billing.Subscription) { s.PendingUpdate, s.PendingExpires = true, expires })
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), billingCopy["delete.collecting"])
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ })
+ t.Run("a pending operation", func(t *testing.T) {
+ o := newDeleteFixture(t, map[string]int64{"apps": 1}, false)
+ o.observe()
+ o.fake.FailPayment = 1
+ if out, _, err := o.send(t, o.packOp(t, "op_raise", "sub_1", "apps", 2, billing.ProrateNow, opPack)); err != nil || out.State != opPending {
+ t.Fatalf("send = %+v %v, want pending", out, err)
+ }
+ o.reset()
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), billingCopy["delete.pending"])
+ // Step 1's read settles nothing (still pending); nothing after it runs.
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ })
+}
+
+// An owner stopped renewal; the request reached the provider and its answer
+// was lost. The gate's read proves it applied, so nothing is resent, and the
+// account is deleted with no operation outstanding.
+func TestDeleteFinishesUnresolvedOp(t *testing.T) {
+ o := newDeleteFixture(t, nil, true)
+ o.unresolved(t, o.renewalOp(t, "op_stop", "sub_1", false))
+ o.editSub("sub_1", func(s *billing.Subscription) { s.CancelAtPeriodEnd = true })
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "LiveSubscriptions": 1})
+ if op := o.op(t, "op_stop"); op.State != opApplied {
+ t.Fatalf("op = %+v, want applied", op)
+ }
+ o.wantDeleted(t, r.Status, r.FlashMsg)
+}
+
+// An unresolved operation that may not be resent (indeterminate) and whose
+// target the read does not show stays outstanding, and deletion is refused:
+// an account is never deleted with an unresolved operation.
+func TestDeleteRefusedWithIndeterminateOp(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ o.unresolved(t, o.renewalOp(t, "op_resume", "sub_1", true))
+ if err := o.st.PutBillingOpState("op_resume", opUnresolved, true, billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), billingCopy["delete.pending"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if op := o.op(t, "op_resume"); op.State != opUnresolved {
+ t.Fatalf("op = %+v", op)
+ }
+}
+
+func TestDeleteSeesLiveSubscriptionOnPageTwo(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.deletable(t)
+ for i := 0; i < 150; i++ {
+ o.put(o.personalSub(fmt.Sprintf("sub_a%03d", i), "canceled", nil))
+ }
+ o.put(o.personalSub("sub_z", "active", nil))
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), renewingText(o.sub("sub_z").PeriodEnd))
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 2, "Subscription": 1})
+ if o.fake.Writes() != 0 {
+ t.Fatalf("writes = %d", o.fake.Writes())
+ }
+}
+
+func TestDeleteRefusesIncompleteList(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.deletable(t)
+ o.fake.PageSize = 1
+ for i := 0; i < 11; i++ {
+ o.put(o.personalSub(fmt.Sprintf("sub_a%03d", i), "canceled", nil))
+ }
+ o.stepUp(t)
+ o.wantDeleteRefused(t, o.deleteAccount(t), billingCopy["delete.unverified"])
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": billing.MaxListPages})
+}
+
+func TestDeleteExpiresOpenCheckoutThenJudges(t *testing.T) {
+ t.Run("completed before the expiry", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.deletable(t)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ o.reset()
+ // The buyer pays just before the expiry arrives.
+ o.fake.Lock()
+ o.fake.BeforeSend = func(p billing.Prepared) error {
+ if p.Kind == billing.PreparedExpire {
+ if _, err := o.fake.CompleteCheckout(old.Session); err != nil {
+ t.Error(err)
+ }
+ }
+ return nil
+ }
+ o.fake.Unlock()
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ ci := o.intent(t)
+ if ci.ID != old.ID || ci.State != intentCompleted {
+ t.Fatalf("intent = %+v", ci)
+ }
+ b, _ := o.st.BillingAccount(o.acct.ID)
+ o.wantDeleteRefused(t, r, renewingText(o.sub(b.Subscription).PeriodEnd))
+ // Step 2: the session read, the refused expiry, the read that
+ // decides, then S; step 3: L(1) + S for the completed purchase.
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 2, "Send": 1, "Subscription": 2, "LiveSubscriptions": 1})
+ })
+ t.Run("expired", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.deletable(t)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ o.reset()
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ // The session read, the expiry, then L(1) with nothing live.
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Send": 1, "LiveSubscriptions": 1})
+ if ci := o.intent(t); ci.ID != old.ID || ci.State != intentExpired {
+ t.Fatalf("intent = %+v", ci)
+ }
+ if o.session(old.Session).State != billing.CheckoutExpired {
+ t.Fatal("the session is still open")
+ }
+ o.wantDeleted(t, r.Status, r.FlashMsg)
+ })
+}
+
+func TestDeleteFinishesCreatingIntent(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.deletable(t)
+ ci := o.unresolvedCreate(t)
+ o.stepUp(t)
+ r := o.deleteAccount(t)
+ // The create's F (its session list, then the stored bytes), then the
+ // expiry of the session it made, then L(1) with nothing live.
+ wantCounts(t, o.counts(), map[string]int{"CustomerCheckouts": 1, "Send": 2, "LiveSubscriptions": 1})
+ sent := o.sent()
+ if len(sent) != 2 || sent[0].Key != ci.Prepared.Key || sent[1].Kind != billing.PreparedExpire {
+ t.Fatalf("sent = %+v, want the stored create then its expiry", sent)
+ }
+ if got := o.intent(t); got.ID != ci.ID || got.State != intentExpired {
+ t.Fatalf("intent = %+v", got)
+ }
+ o.wantDeleted(t, r.Status, r.FlashMsg)
+}
+
+// ---- the gate around the sign-in step -----------------------------------------
+
+// The first run of the gate passes and the account is retiring while the
+// owner signs in again; a resume of renewal then is refused with no request,
+// and the replayed deletion runs the gate again and deletes.
+func TestResumeDuringRetirementRefused(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ loc := o.deleteStashed(t)
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ if !o.retiring(t) {
+ t.Fatal("the account is not retiring while the deletion waits for the sign-in")
+ }
+ if a, _ := o.st.AccountBySqid(o.acct.Sqid); a == nil {
+ t.Fatal("deleted before the sign-in")
+ }
+ o.reset()
+ o.wantFlash(t, o.renewal(t, "resume"), "err", billingCopy["billing.retiring"])
+ wantCounts(t, o.counts(), map[string]int{})
+ if !o.sub("sub_1").CancelAtPeriodEnd {
+ t.Fatal("renewal resumed while retiring")
+ }
+ status, _, body := completeStepUp(t, o.consoleFixture, o.owner, loc)
+ _, msg := o.jarFlash(t)
+ if status != http.StatusSeeOther {
+ t.Fatalf("replay = %d\n%s", status, body)
+ }
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ o.wantDeleted(t, status, msg)
+}
+
+// The replay after the sign-in runs the gate again: a payment that started
+// collecting meanwhile refuses it, and the account stops retiring.
+func TestDeleteGateRerunsAfterStepUp(t *testing.T) {
+ o := newDeleteFixture(t, nil, false)
+ loc := o.deleteStashed(t)
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ o.editSub("sub_1", func(s *billing.Subscription) { s.Collecting = true })
+ o.reset()
+ status, rloc, body := completeStepUp(t, o.consoleFixture, o.owner, loc)
+ if status != http.StatusSeeOther || rloc != o.settingsPath() {
+ t.Fatalf("replay = %d %q\n%s", status, rloc, body)
+ }
+ if kind, msg := o.jarFlash(t); kind != "err" || msg != billingCopy["delete.collecting"] || msg == "" {
+ t.Fatalf("flash = %s:%q, want delete.collecting", kind, msg)
+ }
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ o.wantKept(t)
+}
+
+// A refusal on the first run never asks for the sign-in: the gate runs
+// before the step-up, and the account does not stay retiring.
+func TestDeleteRefusedBeforeStepUp(t *testing.T) {
+ o := newDeleteFixture(t, nil, true)
+ o.wantDeleteRefused(t, o.deleteAccount(t), renewingText(o.sub("sub_1").PeriodEnd))
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Subscription": 1})
+ var stashed int
+ o.st.db.QueryRow(`SELECT COUNT(*) FROM pending_actions`).Scan(&stashed)
+ if stashed != 0 {
+ t.Fatalf("%d pending actions parked for a refused deletion", stashed)
+ }
+}
+
+// A retirement mark an hour old is stale (a deletion that crashed or was
+// never confirmed): it is cleared and the account can be changed again.
+func TestStaleRetirementClears(t *testing.T) {
+ t.Run("a fresh mark refuses", func(t *testing.T) {
+ o := newDeleteFixture(t, nil, true)
+ if err := o.st.BeginBillingRetirement(o.acct.ID, o.ownerAddr(), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.wantFlash(t, o.renewal(t, "stop"), "err", billingCopy["billing.retiring"])
+ wantCounts(t, o.counts(), map[string]int{})
+ })
+ t.Run("a stale mark clears", func(t *testing.T) {
+ o := newDeleteFixture(t, nil, true)
+ if err := o.st.BeginBillingRetirement(o.acct.ID, o.ownerAddr(), time.Now().Add(-retirementTTL-time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ r := o.renewal(t, "stop")
+ if r.Flash != "ok" {
+ t.Fatalf("stop under a stale mark = %+v", r)
+ }
+ var n int
+ if err := o.st.db.QueryRow(`SELECT COUNT(*) FROM billing_retirements WHERE account_id = ?`, o.acct.ID).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("stale mark not cleared: %d %v", n, err)
+ }
+ // And the deletion it never finished can run again.
+ o.stepUp(t)
+ o.reset()
+ r = o.deleteAccount(t)
+ o.wantDeleted(t, r.Status, r.FlashMsg)
+ })
+}
+
+// Every seat path refuses while retiring, after taking the hold and before
+// any provider request: a join, Match seats, a removal's reduction and an
+// invite that needs a new paid seat.
+func TestRetiringRefusesSeatPaths(t *testing.T) {
+ o := newSeatsFixture(t, 10, 10)
+ in := o.invitee(t, "joiner@example.com")
+ tok := o.authorisedInvite(t, in.addr)
+ if err := o.st.BeginBillingRetirement(o.acct.ID, o.ownerAddr(), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ wantAdmit(t, o.accept(in, tok), "billing.retiring")
+ o.wantFlash(t, o.request(t, http.MethodPost, o.billingBase()+"/seats", nil), "err", billingCopy["billing.retiring"])
+ r := o.request(t, http.MethodPost, o.teamPath("/invite"), url.Values{"address": {"new@example.com"}})
+ if r.Status != http.StatusSeeOther || r.Flash != "err" || r.FlashMsg != billingCopy["billing.retiring"] {
+ t.Fatalf("invite = %d %q flash %s:%q, want billing.retiring", r.Status, r.Loc, r.Flash, r.FlashMsg)
+ }
+ if inv, _ := o.st.PendingInvites(o.acct.ID); len(inv) != 1 {
+ t.Fatalf("invites = %+v, want only the first", inv)
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+}
diff --git a/internal/console/billingseats.go b/internal/console/billingseats.go
index 9d17861ba..085c6f26b 100644
--- a/internal/console/billingseats.go
+++ b/internal/console/billingseats.go
@@ -570,13 +570,19 @@ type seatQuote struct {
}
// inviteSeatLocked is the billing step of an invite on a billing team (Calls
-// 6 and 11), under the member lock and the hold: the allowance read; with
+// 6 and 11), under the member lock and the hold: refused while retiring;
+// the allowance read; with
// the members, the pending invites and this one billed above the plan
// item's quantity and the period's paid seats, the invite needs a new paid
// seat. Unconfirmed, that is a quote; confirmed (after a fresh sign-in
// proof), the seat authorisation to record: the subscription's plan, book,
// currency and per-seat price now. No seat needed is neither.
func (s *Server) inviteSeatLocked(h billingHold, ctx context.Context, acct *Account, pending int, to, by string, confirmed bool, now time.Time) (*seatQuote, *seatAuthorisation, error) {
+ if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
+ return nil, nil, err
+ } else if retiring {
+ return nil, nil, errBillingRetiring
+ }
b, sub, purchase, err := s.allowanceLocked(h, ctx, acct, now)
if err != nil {
return nil, nil, err
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go
index 5354bf694..0bbbf007b 100644
--- a/internal/console/billingsync.go
+++ b/internal/console/billingsync.go
@@ -221,32 +221,40 @@ func (s *Server) syncSubscription(ctx context.Context, subscriptionID string, no
// 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 {
+ _, err := s.syncSubscriptionReadLocked(h, ctx, acct, subscriptionID, now)
+ return err
+}
+
+// syncSubscriptionReadLocked is syncSubscriptionLocked answering the
+// deciding read too: nil when the provider has no such subscription. The
+// retirement gate judges what it shows.
+func (s *Server) syncSubscriptionReadLocked(h billingHold, ctx context.Context, acct *Account, subscriptionID string, now time.Time) (*billing.Subscription, error) {
cfg := s.billing.cfg
ctx = s.billingClock(ctx)
sub, err := cfg.Provider.Subscription(ctx, subscriptionID)
if errors.Is(err, billing.ErrNotFound) {
if err := s.restoreStallsForMissingLocked(h, ctx, subscriptionID, now); err != nil {
- return err
+ return nil, err
}
- return s.subscriptionMissing(subscriptionID, now)
+ return nil, s.subscriptionMissing(subscriptionID, now)
}
if err != nil {
- return fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err)
+ return nil, fmt.Errorf("billing: reading subscription %s: %w", subscriptionID, err)
}
// The provider has the subscription: a missing-subscription problem
// for it is resolved (Astra round 2 finding 3), so a close racing this
// sync finds it closed rather than ending a live purchase.
if err := s.store.ResolveBillingProblem(acct.ID, sub.ID, problemSubscriptionMissing,
"the provider has the subscription again", now); err != nil {
- return err
+ return nil, err
}
prev, err := s.store.BillingAccount(acct.ID)
if err != nil {
- return err
+ return nil, err
}
if prev == nil || prev.Customer != sub.Customer {
// The customer changed between the two reads: settle it next time.
- return fmt.Errorf("billing: subscription %s changed customer during the sync", subscriptionID)
+ return nil, fmt.Errorf("billing: subscription %s changed customer during the sync", subscriptionID)
}
if prev.Subscription != "" && prev.Subscription != sub.ID && liveState(prev.State) && liveState(sub.State) {
old, err := cfg.Provider.Subscription(ctx, prev.Subscription)
@@ -255,18 +263,18 @@ func (s *Server) syncSubscriptionLocked(h billingHold, ctx context.Context, acct
// The recorded one is unknown to the provider: it is not shown
// to have ended, so this one is still a second subscription.
case err != nil:
- return fmt.Errorf("billing: reading the recorded subscription %s before adopting %s: %w", prev.Subscription, subscriptionID, err)
+ return nil, fmt.Errorf("billing: reading the recorded subscription %s before adopting %s: %w", prev.Subscription, subscriptionID, err)
default:
prev.State, prev.ProviderStatus = old.State, old.ProviderStatus
}
}
if err := s.applyBillingRead(ctx, acct, prev, sub, now); err != nil {
- return err
+ return nil, err
}
if err := s.settleOpsLocked(h, acct, sub, now); err != nil {
- return err
+ return nil, err
}
- return s.restoreCheckLocked(h, ctx, acct, sub, now)
+ return sub, s.restoreCheckLocked(h, ctx, acct, sub, now)
}
// refreshLocked is the plain sync of the account's recorded subscription
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index c475fc27d..a7364a68a 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -156,18 +156,44 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
return
}
+ if s.billing != nil {
+ // Billing's retirement gate (plans 6b) stands in for the step-up
+ // gate: it runs before the sign-in is asked for, so a refusal never
+ // costs one, and again on the replay. On success the billing hold is
+ // held through DeleteAccount, so nothing can start between the gate
+ // and the deletion. The ops-account and app refusals
+ // (deletionRefused) are checked first, so an account that cannot be
+ // deleted is never marked retiring.
+ if s.deletionRefused(w, r, acct) {
+ return
+ }
+ release, ok := s.retireForDeletion(w, r, addr, raw, acct)
+ if !ok {
+ return
+ }
+ defer release()
+ if !s.deleteAccountNow(w, r, addr, acct) {
+ s.endRetirement(acct) // not deleted: the account can be changed again
+ }
+ return
+ }
if !s.requireFreshAuth(w, r, addr, raw) {
return
}
- // Both refusals that DeleteAccount enforces are re-checked HERE, before the
- // bucket is touched. They are cheap, and getting them in the wrong order is
- // expensive: tombstoning an account the store then refuses to delete would
- // leave a live account marked retired, which the next reconcile pass would
- // act on by dropping its registry row.
+ s.deleteAccountNow(w, r, addr, acct)
+}
+
+// deletionRefused re-checks both refusals that DeleteAccount enforces, before
+// the bucket is touched, and answers whether it refused (the response is
+// written). They are cheap, and getting them in the wrong order is
+// expensive: tombstoning an account the store then refuses to delete would
+// leave a live account marked retired, which the next reconcile pass would
+// act on by dropping its registry row.
+func (s *Server) deletionRefused(w http.ResponseWriter, r *http.Request, acct *Account) bool {
if acct.ID == OpsAccountID {
s.setFlash(w, "err", deletionAdvice(fmt.Errorf("console: ops")))
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
- return
+ return true
}
if n, err := s.store.AppCount(acct.ID); err != nil || n > 0 {
if err != nil {
@@ -177,7 +203,17 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
s.setFlash(w, "err", deletionAdvice(fmt.Errorf("console: still holds %d app(s)", n)))
}
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
- return
+ return true
+ }
+ return false
+}
+
+// deleteAccountNow is the deletion itself, after every gate: the refusals
+// again, the bucket's tombstone, then the rows. It answers whether the
+// account was deleted; either way the response is written.
+func (s *Server) deleteAccountNow(w http.ResponseWriter, r *http.Request, addr string, acct *Account) bool {
+ if s.deletionRefused(w, r, acct) {
+ return false
}
// The bucket first, and the deletion is abandoned if it will not take.
//
@@ -200,16 +236,17 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
"was deleted — an account deleted only here would come back on the next restart. "+
"Try again once the bucket is reachable.")
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
- return
+ return false
}
if err := s.store.DeleteAccount(acct.ID, time.Now()); err != nil {
log.Printf("console: delete account: %v", err)
s.setFlash(w, "err", deletionAdvice(err))
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
- return
+ return false
}
s.setFlash(w, "ok", "Deleted “"+acct.Name+"”.")
s.redirectToCurrentAccount(w, r, addr, http.StatusSeeOther)
+ return true
}
// ---- the Trash --------------------------------------------------------------