carlos / platform Public

console: turn off what a lapsed account no longer pays for, and back on when it does (plans 4d)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0f9c1156c059a374e1520587dc90a5d7bfa5a3e6 parent bf74cf7
4 files changed, +509 −7
  • internal/console/plancaps_copy.go +6 −0
  • internal/console/plangracepass.go +30 −0
  • internal/console/planlapse.go +156 −3
  • internal/console/planlapse_test.go +317 −4
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go
index 745e220e6..dd5dbe50a 100644
--- a/internal/console/plancaps_copy.go
+++ b/internal/console/plancaps_copy.go
@@ -55,4 +55,10 @@ var planNoticeCopy = map[string]string{
"cli.bandwidth_throttled": "this account's apps are served more slowly until the month ends or the plan grows: it has used %s",
"banner.awake_throttled": "This account's apps are served more slowly and put to sleep after 15 minutes awake until the month ends or the plan grows: %s. Open live connections (WebSockets) are closed.",
"cli.awake_throttled": "this account's apps are served more slowly and put to sleep after 15 minutes awake until the month ends or the plan grows: %s. open live connections are closed",
+ // Plans 4d: what a lapse turned off and back on, for the audit log.
+ "audit.turned_off": "plan: %s turned off because %s",
+ "audit.turned_on": "plan: %s turned back on",
+ "audit.reason.running_things": "the plan covers %d apps and instances",
+ "audit.reason.sidecars": "the plan covers %d workers per app",
+ "audit.reason.custom_domains": "the plan does not include custom domains",
}
diff --git a/internal/console/plangracepass.go b/internal/console/plangracepass.go
index feb8d32e6..c4c81eb45 100644
--- a/internal/console/plangracepass.go
+++ b/internal/console/plangracepass.go
@@ -63,6 +63,10 @@ func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.T
if err != nil || l == nil {
return err
}
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ return err
+ }
prev, err := s.store.CapStates(acct.ID)
if err != nil {
return err
@@ -72,6 +76,22 @@ func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.T
byCap[prev[i].Cap] = &prev[i]
}
measures, errs := s.measureCaps(ctx, acct, l, now)
+ // Plans 4d: an eligible account's leftovers. An inventory that cannot
+ // be read keeps both leftover rows and changes nothing turned off.
+ eligible := lapseEligible(row)
+ var inv *lapseInventory
+ if eligible {
+ var invErr error
+ if inv, invErr = s.lapseInventory(ctx, acct); invErr != nil {
+ for c := range measureLeftovers(&lapseInventory{}, l) {
+ errs[c] = invErr
+ }
+ } else {
+ for c, m := range measureLeftovers(inv, l) {
+ measures[c] = m
+ }
+ }
+ }
var states []capState
for _, c := range capOrder {
m, measured := measures[c]
@@ -117,6 +137,16 @@ func (s *Server) planGraceAccount(ctx context.Context, acct *Account, now time.T
log.Printf("console: plan grace %s: storage clear: %v", acct.Sqid, err)
}
}
+ switch {
+ case eligible && inv != nil:
+ if err := s.convergeLapse(ctx, acct, row, l, byState, inv, now); err != nil {
+ log.Printf("console: plan grace %s: lapse: %v", acct.Sqid, err)
+ }
+ case !eligible:
+ if err := s.clearLapseOff(ctx, acct, now); err != nil {
+ log.Printf("console: plan grace %s: lapse clear: %v", acct.Sqid, err)
+ }
+ }
if s.cfg.MailProvisioner != nil {
if err := s.resumePlanMail(ctx, acct, now); err != nil {
log.Printf("console: plan grace %s: mail resume: %v", acct.Sqid, err)
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go
index 5c30a5ab7..287e22b96 100644
--- a/internal/console/planlapse.go
+++ b/internal/console/planlapse.go
@@ -2,6 +2,7 @@ package console
import (
"context"
+ "fmt"
"log"
"time"
@@ -63,9 +64,11 @@ func (s *Server) lapseStarted(old *AccountPlanRow, plan string, packs map[string
// applyAccountPlan is the one way an account's plan changes. The operator
// door uses it, and billing (Plan 6, Checkout) calls it for every
// subscription change, so a paid account whose limits fall always starts a
-// lapse (plans 4d). It writes the plan, marks the lapse when one starts,
-// and publishes the account's limits record best-effort (the publish pass
-// retries anything this misses). ErrAccountGone comes back unchanged. With
+// lapse (plans 4d). It writes the plan, marks the lapse when one starts
+// (restarting the lapse caps' grace), runs the account's grace pass at once
+// so a raise turns things back on in the same call, and publishes the
+// account's limits record best-effort (the publish pass retries anything
+// this misses). ErrAccountGone comes back unchanged. With
// no catalog it writes exactly what Store.SetAccountPlan writes.
func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, source string,
sponsored *plans.Limits, reason, by string, now time.Time) error {
@@ -80,10 +83,20 @@ func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan strin
if err := s.store.MarkLapse(acct.ID, now); err != nil {
return err
}
+ // Each fall gets its own grace: the lapse caps' clocks start afresh.
+ for _, c := range lapseCaps {
+ if err := s.store.DeleteCapState(acct.ID, c); err != nil {
+ return err
+ }
+ }
}
if s.cfg.Releases == nil || s.cfg.PlanCatalog == nil {
return nil
}
+ // Re-converge now, so paying again turns things back on in this call.
+ if err := s.planGraceAccount(ctx, acct, now); err != nil {
+ log.Printf("console: plan %s: grace: %v", acct.Sqid, err)
+ }
row, err := s.store.AccountPlan(acct.ID)
if err != nil {
log.Printf("console: plan %s: reread: %v", acct.Sqid, err)
@@ -96,3 +109,143 @@ func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan strin
}
return nil
}
+
+// lapseKey identifies a thing, or its item row, within one account.
+func lapseKey(kind, ref string) string { return kind + "\x00" + ref }
+
+// lapseCaps are the caps whose leftovers a lapse turns off.
+var lapseCaps = []capID{capRunningThings, capSidecars, capCustomDomains}
+
+// convergeLapse turns off what an eligible account no longer pays for, and
+// back on what it does (plans 4d). Each kind is decided on its own cap:
+// once that cap is past grace and notice (afterGraceDue) its whole
+// selection is off; before then only things already off stay off, and
+// only while they are still beyond the limits. So a raise turns things
+// back on at once, and a further fall waits for its own grace. It records
+// the result in plan_lapse_items and the account's disabled host list, and
+// ends the lapse when nothing is off and nothing is over.
+func (s *Server) convergeLapse(ctx context.Context, acct *Account, row *AccountPlanRow, l *plans.Limits,
+ states map[capID]capState, inv *lapseInventory, now time.Time) error {
+ items, err := s.store.LapseItems(acct.ID)
+ if err != nil {
+ return err
+ }
+ byKey := map[string]lapseItem{}
+ for _, it := range items {
+ byKey[lapseKey(it.Kind, it.Ref)] = it
+ }
+ // isOff: the item is this incarnation's and is off.
+ isOff := func(x lapseThing) bool {
+ it, ok := byKey[lapseKey(x.Kind, x.Ref)]
+ return ok && !it.DisabledAt.IsZero() && unixOrZero(it.ThingCreated) == unixOrZero(x.CreatedAt)
+ }
+ reasons := map[string]string{}
+ next := func(c capID, selected []lapseThing, reason string) []lapseThing {
+ due := afterGraceDue(states[c], now)
+ var out []lapseThing
+ for _, x := range selected {
+ if due || isOff(x) {
+ out = append(out, x)
+ reasons[lapseKey(x.Kind, x.Ref)] = reason
+ }
+ }
+ return out
+ }
+ var off []lapseThing
+ off = append(off, next(capRunningThings, chooseOff(inv.Things, l.RunningThings),
+ fmt.Sprintf(planNoticeCopy["audit.reason.running_things"], l.RunningThings))...)
+ off = append(off, next(capSidecars, sidecarsOff(inv.Sidecars, l.SidecarsPerApp),
+ fmt.Sprintf(planNoticeCopy["audit.reason.sidecars"], l.SidecarsPerApp))...)
+ if !l.CustomDomains {
+ off = append(off, next(capCustomDomains, inv.Domains, planNoticeCopy["audit.reason.custom_domains"])...)
+ }
+ offKeys := map[string]bool{}
+ for _, x := range off {
+ offKeys[lapseKey(x.Kind, x.Ref)] = true
+ }
+ seen := map[string]bool{}
+ for _, list := range [][]lapseThing{inv.Things, inv.Sidecars, inv.Domains} {
+ for _, x := range list {
+ key := lapseKey(x.Kind, x.Ref)
+ seen[key] = true
+ it, has := byKey[key]
+ current := has && unixOrZero(it.ThingCreated) == unixOrZero(x.CreatedAt)
+ switch {
+ case offKeys[key] && current && !it.DisabledAt.IsZero():
+ // Already off: keeps its DisabledAt.
+ case offKeys[key]:
+ put := lapseItem{AccountID: acct.ID, App: x.App, Kind: x.Kind, Ref: x.Ref, ThingCreated: x.CreatedAt,
+ Keep: current && it.Keep, DisabledAt: now, UpdatedAt: now}
+ if err := s.store.PutLapseItem(ctx, put); err != nil {
+ return err
+ }
+ s.audit(acct, x.App, "plan", "plan.turned_off", fmt.Sprintf(planNoticeCopy["audit.turned_off"], x.Ref, reasons[key]))
+ case current && !it.DisabledAt.IsZero():
+ if err := s.lapseItemOn(ctx, acct, it, now); err != nil {
+ return err
+ }
+ case has && !current:
+ // A row for an earlier thing of the same name.
+ if err := s.store.DeleteLapseItem(ctx, acct.ID, it.App, it.Kind, it.Ref); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ for key, it := range byKey {
+ if !seen[key] {
+ if err := s.store.DeleteLapseItem(ctx, acct.ID, it.App, it.Kind, it.Ref); err != nil {
+ return err
+ }
+ }
+ }
+ if _, err := s.store.SetAccountDisabled(acct.ID, lapseHosts(off, inv), now); err != nil {
+ return err
+ }
+ if len(off) == 0 {
+ for _, c := range lapseCaps {
+ if st, ok := states[c]; ok && st.Level.over() {
+ return nil
+ }
+ }
+ return s.store.ClearLapse(acct.ID)
+ }
+ return nil
+}
+
+// lapseItemOn turns one item back on: a kept item keeps its row with
+// DisabledAt cleared, any other row goes.
+func (s *Server) lapseItemOn(ctx context.Context, acct *Account, it lapseItem, now time.Time) error {
+ var err error
+ if it.Keep {
+ it.DisabledAt, it.UpdatedAt = time.Time{}, now
+ err = s.store.PutLapseItem(ctx, it)
+ } else {
+ err = s.store.DeleteLapseItem(ctx, acct.ID, it.App, it.Kind, it.Ref)
+ }
+ if err != nil {
+ return err
+ }
+ s.audit(acct, it.App, "plan", "plan.turned_on", fmt.Sprintf(planNoticeCopy["audit.turned_on"], it.Ref))
+ return nil
+}
+
+// clearLapseOff turns everything a lapse turned off back on, without an
+// inventory: the account is no longer on the lapse path (sponsored, its
+// lapse cleared, or plans that no longer govern it).
+func (s *Server) clearLapseOff(ctx context.Context, acct *Account, now time.Time) error {
+ items, err := s.store.LapseItems(acct.ID)
+ if err != nil {
+ return err
+ }
+ for _, it := range items {
+ if it.DisabledAt.IsZero() {
+ continue
+ }
+ if err := s.lapseItemOn(ctx, acct, it, now); err != nil {
+ return err
+ }
+ }
+ _, err = s.store.SetAccountDisabled(acct.ID, nil, now)
+ return err
+}
diff --git a/internal/console/planlapse_test.go b/internal/console/planlapse_test.go
index 306f9122b..1c80eed3b 100644
--- a/internal/console/planlapse_test.go
+++ b/internal/console/planlapse_test.go
@@ -2,18 +2,23 @@ package console
import (
"context"
+ "fmt"
"net/http"
"os"
"path/filepath"
+ "reflect"
+ "slices"
"strings"
"testing"
"time"
"github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/provision"
)
// lapseCatalog is the example catalog plus "hobby", a second unpaid plan
-// with a lower running-things cap than free.
+// with a lower running-things cap than free, and "mini", a paid plan with
+// a cap of 2 and a "one" pack adding one running thing.
func lapseCatalog(t *testing.T) *plans.Catalog {
t.Helper()
b, err := os.ReadFile(exampleCatalogPath)
@@ -21,7 +26,10 @@ func lapseCatalog(t *testing.T) *plans.Catalog {
t.Fatal(err)
}
s := strings.Replace(string(b), `"plans": {`, `"plans": {
- "hobby": {"paid": false, "limits": {"running_things": 2, "sidecars_per_app": 1, "idle_seconds": 90, "memory_tier": "small", "min_schedule_seconds": 900}},`, 1)
+ "hobby": {"paid": false, "limits": {"running_things": 2, "sidecars_per_app": 1, "idle_seconds": 90, "memory_tier": "small", "min_schedule_seconds": 900}},
+ "mini": {"paid": true, "limits": {"running_things": 2, "sidecars_per_app": 1, "idle_seconds": 90, "memory_tier": "small", "min_schedule_seconds": 900}, "packs": ["one"]},`, 1)
+ s = strings.Replace(s, `"packs": {`, `"packs": {
+ "one": {"adds": {"running_things": 1}, "max_quantity": 20},`, 1)
c, err := plans.ParseCatalog([]byte(s))
if err != nil {
t.Fatal(err)
@@ -54,6 +62,11 @@ func TestApplyAccountPlanMarksALapse(t *testing.T) {
fx := newConsoleFixture(t)
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
acct := planAccount(t, fx, 501)
+ // More running things than free covers, so the lapse outlives the
+ // call's own re-converge (plans 4d task 5).
+ for i, app := range []string{"a", "b", "c", "d"} {
+ lapseApp_(t, fx, acct, app, at(-100+i))
+ }
applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
if got := lapseSince(t, fx, acct); !got.IsZero() {
t.Fatalf("free -> personal marked a lapse at %v", got)
@@ -62,9 +75,10 @@ func TestApplyAccountPlanMarksALapse(t *testing.T) {
if got := lapseSince(t, fx, acct); !got.Equal(planNow) {
t.Fatalf("personal -> free: lapse_since = %v, want %v", got, planNow)
}
+ // Paying again covers everything: the lapse ends in the same call.
applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(time.Hour))
- if got := lapseSince(t, fx, acct); !got.Equal(planNow) {
- t.Fatalf("free -> personal moved lapse_since to %v", got)
+ if got := lapseSince(t, fx, acct); !got.IsZero() {
+ t.Fatalf("free -> personal left lapse_since at %v", got)
}
}
@@ -72,6 +86,9 @@ func TestApplyAccountPlanPackReductionIsALapse(t *testing.T) {
fx := newConsoleFixture(t)
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
acct := planAccount(t, fx, 501)
+ for i := 0; i < 26; i++ {
+ lapseApp_(t, fx, acct, fmt.Sprintf("app%02d", i), at(-100+i))
+ }
applyPlan(t, fx, acct, "personal", map[string]int{"apps": 2}, nil, planNow.Add(-time.Hour))
applyPlan(t, fx, acct, "personal", nil, nil, planNow)
if got := lapseSince(t, fx, acct); !got.Equal(planNow) {
@@ -171,3 +188,299 @@ func TestApplyAccountPlanWithoutACatalogWritesOnlyThePlan(t *testing.T) {
t.Fatalf("row without a catalog = %+v", row)
}
}
+
+// lapseFixture is an account on personal with five running things (apps
+// shop and blog, instances shop-1, blog-1 and shop-2, oldest first) and
+// owners reachable by a fake mailer. Moving it to free (cap 3) is a lapse.
+func lapseFixture(t *testing.T) (*consoleFixture, *Account, *fakeConsoleMail) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ mailer := &fakeConsoleMail{ready: true}
+ fx.srv.consoleMail = mailer
+ fx.srv.sendFederated = nil
+ acct := planAccount(t, fx, 501)
+ lapseApp_(t, fx, acct, "shop", at(-100))
+ lapseInstanceRec(t, fx, acct, "shop", "shop-1.example.com", at(-99))
+ lapseApp_(t, fx, acct, "blog", at(-98))
+ lapseInstanceRec(t, fx, acct, "blog", "blog-1.example.com", at(-97))
+ lapseInstanceRec(t, fx, acct, "shop", "shop-2.example.com", at(-96))
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
+ return fx, acct, mailer
+}
+
+const week = 7 * 24 * time.Hour
+
+func disabledOf(t *testing.T, fx *consoleFixture, acct *Account) []string {
+ t.Helper()
+ row, err := fx.st.AccountPlan(acct.ID)
+ if err != nil || row == nil {
+ t.Fatalf("plan row: %+v, %v", row, err)
+ }
+ return row.Disabled
+}
+
+func offItems(t *testing.T, fx *consoleFixture, acct *Account) []string {
+ t.Helper()
+ items, err := fx.st.LapseItems(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, it := range items {
+ if !it.DisabledAt.IsZero() {
+ out = append(out, it.Ref)
+ }
+ }
+ slices.Sort(out)
+ return out
+}
+
+func publishedDisabled(t *testing.T, fx *consoleFixture, acct *Account) []string {
+ t.Helper()
+ r, _ := readLimits(t, fx, acct.Sqid)
+ if r == nil {
+ t.Fatal("no limits record")
+ }
+ return r.Disabled
+}
+
+// lapseAndTurnOff moves the fixture to free at planNow (notice goes out by
+// email at once) and runs the pass after grace: the two newest are off.
+func lapseAndTurnOff(t *testing.T, fx *consoleFixture, acct *Account) {
+ t.Helper()
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ fx.srv.planGracePass(context.Background(), planNow.Add(week))
+ if got, want := disabledOf(t, fx, acct), []string{"blog-1.example.com", "shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("after grace: disabled = %v, want %v", got, want)
+ }
+}
+
+func TestLapseGraceTurnsNothingOff(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ fx.srv.planGracePass(context.Background(), planNow.Add(week-time.Minute))
+ if got := disabledOf(t, fx, acct); got != nil {
+ t.Fatalf("in grace: disabled = %v", got)
+ }
+ if got := offItems(t, fx, acct); got != nil {
+ t.Fatalf("in grace: items off = %v", got)
+ }
+}
+
+func TestLapseAfterGraceTurnsTheNewestOff(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ lapseAndTurnOff(t, fx, acct)
+ if got, want := offItems(t, fx, acct), []string{"blog-1.example.com", "shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("items off = %v, want %v", got, want)
+ }
+ fx.srv.planLimitsPass(context.Background(), planNow.Add(week+time.Minute))
+ if got, want := publishedDisabled(t, fx, acct), []string{"blog-1.example.com", "shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("Record.Disabled = %v, want %v", got, want)
+ }
+ evs, err := fx.st.Events(acct.ID, "blog", 20)
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for _, e := range evs {
+ if e.Action == "plan.turned_off" && strings.Contains(e.Detail, "blog-1.example.com") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("no plan.turned_off audit on blog: %+v", evs)
+ }
+}
+
+func TestLapseWaitsForNotice(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ fx.srv.consoleMail = nil // no email: notice only as recorded below
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ st, ok := capRow(t, fx, acct, capRunningThings)
+ if !ok || !st.NoticeAt.IsZero() {
+ t.Fatalf("running_things row %+v (present %v), want no notice yet", st, ok)
+ }
+ if err := fx.st.RecordCapNotice(acct.ID, []capState{st}, planNow.Add(week-71*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(week))
+ if got := disabledOf(t, fx, acct); got != nil {
+ t.Fatalf("notice 71h old: disabled = %v", got)
+ }
+}
+
+func TestApplyAccountPlanTurnsThingsBackOnAtOnce(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ lapseAndTurnOff(t, fx, acct)
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(week+time.Hour))
+ if got := disabledOf(t, fx, acct); got != nil {
+ t.Fatalf("after paying again: disabled = %v", got)
+ }
+ if got := offItems(t, fx, acct); got != nil {
+ t.Fatalf("after paying again: items off = %v", got)
+ }
+ if got := publishedDisabled(t, fx, acct); got != nil {
+ t.Fatalf("record not republished in the same call: Disabled = %v", got)
+ }
+}
+
+func TestFurtherFallWaitsForItsOwnGrace(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ fx.srv.cfg.PlanCatalog = lapseCatalog(t)
+ // personal -> mini + 2 one-packs (cap 4): after grace the newest is off.
+ applyPlan(t, fx, acct, "mini", map[string]int{"one": 2}, nil, planNow)
+ fx.srv.planGracePass(context.Background(), planNow.Add(week))
+ if got, want := disabledOf(t, fx, acct), []string{"shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("after the first grace: disabled = %v, want %v", got, want)
+ }
+ // A pack reduced again (cap 3) is a new fall with its own grace.
+ applyPlan(t, fx, acct, "mini", map[string]int{"one": 1}, nil, planNow.Add(week+time.Hour))
+ if got := lapseSince(t, fx, acct); !got.Equal(planNow.Add(week + time.Hour)) {
+ t.Fatalf("lapse_since = %v, want the new fall", got)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(2*week))
+ if got, want := disabledOf(t, fx, acct), []string{"shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("in the new grace: disabled = %v, want only what was off %v", got, want)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(2*week+time.Hour))
+ if got, want := disabledOf(t, fx, acct), []string{"blog-1.example.com", "shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("after the new grace: disabled = %v, want %v", got, want)
+ }
+}
+
+func TestDeletingAThingBringsAnotherBack(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ lapseAndTurnOff(t, fx, acct)
+ if err := fx.rel.Delete(context.Background(), provision.RecordKey(acct.Sqid, "shop", "shop-1.example.com")); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(week+time.Hour))
+ if got, want := disabledOf(t, fx, acct), []string{"shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("after a delete: disabled = %v, want %v", got, want)
+ }
+ if got, want := offItems(t, fx, acct), []string{"shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("after a delete: items off = %v, want %v", got, want)
+ }
+}
+
+func TestLapseUnchangedWhenInventoryUnreadable(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ lapseAndTurnOff(t, fx, acct)
+ before, _ := fx.st.LapseItems(acct.ID)
+ if _, err := fx.rel.Put(context.Background(), provision.RecordKey(acct.Sqid, "blog", "blog-9.example.com"), []byte(`{not json`), ""); err != nil {
+ t.Fatal(err)
+ }
+ // Even a raise that would turn everything back on changes nothing while
+ // the inventory cannot be read.
+ fx.srv.planGracePass(context.Background(), planNow.Add(week+time.Hour))
+ if got, want := disabledOf(t, fx, acct), []string{"blog-1.example.com", "shop-2.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("unreadable inventory: disabled = %v, want %v", got, want)
+ }
+ if after, _ := fx.st.LapseItems(acct.ID); !reflect.DeepEqual(after, before) {
+ t.Fatalf("items changed: %+v -> %+v", before, after)
+ }
+}
+
+func TestNoLapseWithoutAFall(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ fx.srv.consoleMail = &fakeConsoleMail{ready: true}
+ fx.srv.sendFederated = nil
+ acct := planAccount(t, fx, 501)
+ for i, app := range []string{"a", "b", "c", "d", "e"} {
+ lapseApp_(t, fx, acct, app, at(-100+i))
+ }
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ fx.srv.planGracePass(context.Background(), planNow.Add(week))
+ fx.srv.planGracePass(context.Background(), planNow.Add(2*week))
+ if st, ok := capRow(t, fx, acct, capRunningThings); !ok || !afterGraceDue(st, planNow.Add(2*week)) {
+ t.Fatalf("fixture: running_things %+v not past grace and notice", st)
+ }
+ if got := disabledOf(t, fx, acct); got != nil {
+ t.Fatalf("never paid: disabled = %v", got)
+ }
+ if got := offItems(t, fx, acct); got != nil {
+ t.Fatalf("never paid: items off = %v", got)
+ }
+}
+
+func TestSponsoredAccountsNeverTurnedOff(t *testing.T) {
+ fx, acct, _ := lapseFixture(t)
+ lapseAndTurnOff(t, fx, acct)
+ // The operator sponsors the account at the same figure: not eligible.
+ if _, err := fx.st.db.Exec(`UPDATE account_plans SET source = ? WHERE account_id = ?`, PlanSourceSponsored, acct.ID); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(week+time.Hour))
+ if got := disabledOf(t, fx, acct); got != nil {
+ t.Fatalf("sponsored: disabled = %v", got)
+ }
+ if got := offItems(t, fx, acct); got != nil {
+ t.Fatalf("sponsored: items off = %v", got)
+ }
+ // And the operator door's way: a sponsored assignment turns things on
+ // in the same call.
+ fx2, acct2, _ := lapseFixture(t)
+ lapseAndTurnOff(t, fx2, acct2)
+ applyPlan(t, fx2, acct2, "free", nil, &plans.Limits{RunningThings: 3}, planNow.Add(week+time.Hour))
+ if got := disabledOf(t, fx2, acct2); got != nil {
+ t.Fatalf("sponsored through the door: disabled = %v", got)
+ }
+}
+
+func TestCustomDomainsTurnedOffAfterGrace(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ fx.srv.consoleMail = &fakeConsoleMail{ready: true}
+ fx.srv.sendFederated = nil
+ acct := planAccount(t, fx, 501)
+ lapseApp_(t, fx, acct, "shop", at(-100))
+ lapseInstanceRec(t, fx, acct, "shop", "shop-1.example.com", at(-99))
+ lapseClaim(t, fx, acct, "shop", "shop.example.com", true, at(-98))
+ lapseClaim(t, fx, acct, "shop", "shop."+acct.Sqid+".oncarlos.test", false, at(-97))
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ if got := disabledOf(t, fx, acct); got != nil {
+ t.Fatalf("in grace: disabled = %v", got)
+ }
+ fx.srv.planGracePass(context.Background(), planNow.Add(week))
+ if got, want := disabledOf(t, fx, acct), []string{"*.shop.example.com", "shop.example.com"}; !slices.Equal(got, want) {
+ t.Fatalf("after grace: disabled = %v, want %v", got, want)
+ }
+}
+
+func TestLapseClearsWhenNothingIsLeft(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ lapseApp_(t, fx, acct, "shop", at(-100))
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
+ if err := fx.st.MarkLapse(acct.ID, planNow.Add(-time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planGracePass(context.Background(), planNow)
+ if got := lapseSince(t, fx, acct); !got.IsZero() {
+ t.Fatalf("within its limits: lapse_since = %v, want cleared", got)
+ }
+}
+
+func TestLapseWithoutACatalogUnchanged(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ lapseApp_(t, fx, acct, "shop", at(-100))
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ fx.srv.planGracePass(context.Background(), planNow.Add(week))
+ row, _ := fx.st.AccountPlan(acct.ID)
+ if !row.LapseSince.IsZero() || row.Disabled != nil {
+ t.Fatalf("no catalog: row %+v", row)
+ }
+ if items, _ := fx.st.LapseItems(acct.ID); items != nil {
+ t.Fatalf("no catalog: items %+v", items)
+ }
+ if r, _ := readLimits(t, fx, acct.Sqid); r != nil {
+ t.Fatalf("no catalog: record %+v", r)
+ }
+}