carlos / platform Public

console: a paid account's falling limits start a lapse (plans 4d)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 4beb75e7c7b54cbc0c9253dbf3b6eb4864206d0a parent 87ad2d1
7 files changed, +399 −14
  • internal/console/accountplans.go +70 −4
  • internal/console/apiaccountplan.go +1 −10
  • internal/console/planlapse.go +98 −0
  • internal/console/planlapse_test.go +173 −0
  • internal/console/planlimits.go +1 −0
  • internal/console/planlimits_test.go +51 −0
  • internal/console/store.go +5 −0
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index 5a3980c24..865f090f4 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -4,6 +4,8 @@ import (
"database/sql"
"encoding/json"
"errors"
+ "slices"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/plans"
@@ -41,19 +43,34 @@ type AccountPlanRow struct {
UpdatedAt time.Time
// Throttle is the account's plan throttle (plans 4c); nil for none.
Throttle *plans.Throttle
+ // LapseSince is when the account's limits last fell from a paid
+ // assignment (plans 4d); zero for no lapse.
+ LapseSince time.Time
+ // Disabled lists the hosts a lapse turned off, sorted; nil for none.
+ Disabled []string
}
const accountPlanColumns = `p.account_id, a.sqid, p.plan, p.packs, p.source, p.sponsored, p.reason,
- p.revision, p.published_revision, p.published_catalog, p.updated_by, p.updated_at, p.throttle`
+ p.revision, p.published_revision, p.published_catalog, p.updated_by, p.updated_at, p.throttle,
+ p.lapse_since, p.disabled`
func scanAccountPlan(sc interface{ Scan(...any) error }) (*AccountPlanRow, error) {
var r AccountPlanRow
- var packs, sponsored, throttle string
- var updated int64
+ var packs, sponsored, throttle, disabled string
+ var updated, lapse int64
if err := sc.Scan(&r.AccountID, &r.Sqid, &r.Plan, &packs, &r.Source, &sponsored, &r.Reason,
- &r.Revision, &r.PublishedRevision, &r.PublishedCatalog, &r.UpdatedBy, &updated, &throttle); err != nil {
+ &r.Revision, &r.PublishedRevision, &r.PublishedCatalog, &r.UpdatedBy, &updated, &throttle,
+ &lapse, &disabled); err != nil {
return nil, err
}
+ if lapse != 0 {
+ r.LapseSince = time.Unix(lapse, 0)
+ }
+ if disabled != "" {
+ if err := json.Unmarshal([]byte(disabled), &r.Disabled); err != nil {
+ return nil, err
+ }
+ }
if throttle != "" {
r.Throttle = &plans.Throttle{}
if err := json.Unmarshal([]byte(throttle), r.Throttle); err != nil {
@@ -219,3 +236,52 @@ func (s *Store) SetAccountThrottle(accountID int64, t *plans.Throttle, now time.
n, err := res.RowsAffected()
return n > 0, err
}
+
+// MarkLapse records that the account's limits fell from a paid assignment
+// at now (plans 4d). Each fall moves it.
+func (s *Store) MarkLapse(accountID int64, now time.Time) error {
+ _, err := s.db.Exec(`UPDATE account_plans SET lapse_since = ? WHERE account_id = ?`, now.Unix(), accountID)
+ return err
+}
+
+// ClearLapse ends the account's lapse: nothing is turned off and nothing
+// it runs is beyond its limits any more.
+func (s *Store) ClearLapse(accountID int64) error {
+ _, err := s.db.Exec(`UPDATE account_plans SET lapse_since = 0 WHERE account_id = ? AND lapse_since <> 0`, accountID)
+ return err
+}
+
+// SetAccountDisabled stores the hosts a lapse turned off (lower case,
+// sorted, deduped; none clears it) and bumps the revision so the publish
+// pass carries them to the boxes. An unchanged list writes nothing. An
+// account with no plan row is (false, nil).
+func (s *Store) SetAccountDisabled(accountID int64, hosts []string, now time.Time) (bool, error) {
+ val, err := disabledColumn(hosts)
+ if err != nil {
+ return false, err
+ }
+ res, err := s.db.Exec(`UPDATE account_plans SET disabled = ?, revision = revision + 1, updated_at = ?
+ WHERE account_id = ? AND disabled <> ?`, val, now.Unix(), accountID, val)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ return n > 0, err
+}
+
+// disabledColumn is hosts as the disabled column stores them.
+func disabledColumn(hosts []string) (string, error) {
+ set := make([]string, 0, len(hosts))
+ for _, h := range hosts {
+ if h = strings.ToLower(strings.TrimSpace(h)); h != "" {
+ set = append(set, h)
+ }
+ }
+ slices.Sort(set)
+ set = slices.Compact(set)
+ if len(set) == 0 {
+ return "", nil
+ }
+ b, err := json.Marshal(set)
+ return string(b), err
+}
diff --git a/internal/console/apiaccountplan.go b/internal/console/apiaccountplan.go
index d21fceb2b..d93e16375 100644
--- a/internal/console/apiaccountplan.go
+++ b/internal/console/apiaccountplan.go
@@ -118,8 +118,7 @@ func (s *Server) handleAPIAccountPlanSet(w http.ResponseWriter, r *http.Request)
if req.Sponsored != nil {
source = PlanSourceSponsored
}
- now := time.Now()
- if _, err := s.store.SetAccountPlan(acct.ID, req.Plan, req.Packs, source, req.Sponsored, reason, addr, now); err != nil {
+ if err := s.applyAccountPlan(r.Context(), acct, req.Plan, req.Packs, source, req.Sponsored, reason, addr, time.Now()); err != nil {
if errors.Is(err, ErrAccountGone) {
http.NotFound(w, r)
return
@@ -128,14 +127,6 @@ func (s *Server) handleAPIAccountPlanSet(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusInternalServerError, planCopySaveFailed)
return
}
- if row, err := s.store.AccountPlan(acct.ID); err != nil {
- log.Printf("console: api account plan %s: reread: %v", acct.Sqid, err)
- } else if row != nil && s.cfg.Releases != nil {
- // Best effort: the pass retries anything this misses.
- if err := s.publishAccountLimits(r.Context(), *row, now); err != nil {
- log.Printf("console: api account plan %s: publish: %v", acct.Sqid, err)
- }
- }
reply, err := s.accountPlanReplyFor(acct)
if err != nil {
log.Printf("console: api account plan %s: %v", acct.Sqid, err)
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go
new file mode 100644
index 000000000..5c30a5ab7
--- /dev/null
+++ b/internal/console/planlapse.go
@@ -0,0 +1,98 @@
+package console
+
+import (
+ "context"
+ "log"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// lapseEligible reports whether an account is on the lapse path (plans 4d):
+// its limits fell from a paid assignment and it is not sponsored. Sponsored
+// accounts never are (spec §9.2).
+func lapseEligible(row *AccountPlanRow) bool {
+ return row != nil && !row.LapseSince.IsZero() && !planRowSponsored(row)
+}
+
+func planRowSponsored(row *AccountPlanRow) bool {
+ return row.Sponsored != nil || row.Source == PlanSourceSponsored
+}
+
+// lapseStarted reports whether moving from old to the new assignment starts
+// a lapse: plans are on, the new assignment is not sponsored, the old one
+// was paid (a paid plan or any pack, and not sponsored), and a limit the
+// lapse lifecycle governs fell. An old assignment the catalog can no longer
+// price starts nothing.
+func (s *Server) lapseStarted(old *AccountPlanRow, plan string, packs map[string]int, sponsored *plans.Limits) bool {
+ cat := s.cfg.PlanCatalog
+ if cat == nil || sponsored != nil {
+ return false
+ }
+ oldPlan, oldPacks := cat.DefaultPlan, map[string]int(nil)
+ if old != nil {
+ if planRowSponsored(old) {
+ return false
+ }
+ oldPlan, oldPacks = old.Plan, old.Packs
+ }
+ p, ok := cat.Plans[oldPlan]
+ if !ok {
+ return false
+ }
+ paid := p.Paid
+ for _, q := range oldPacks {
+ if q > 0 {
+ paid = true
+ }
+ }
+ if !paid {
+ return false
+ }
+ was, err := cat.Effective(oldPlan, oldPacks, nil)
+ if err != nil {
+ return false
+ }
+ next, err := cat.Effective(plan, packs, nil)
+ if err != nil {
+ return false
+ }
+ return plans.LimitsFell(was, next)
+}
+
+// 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
+// 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 {
+ old, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ return err
+ }
+ if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, source, sponsored, reason, by, now); err != nil {
+ return err
+ }
+ if s.lapseStarted(old, plan, packs, sponsored) {
+ if err := s.store.MarkLapse(acct.ID, now); err != nil {
+ return err
+ }
+ }
+ if s.cfg.Releases == nil || s.cfg.PlanCatalog == nil {
+ return nil
+ }
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ log.Printf("console: plan %s: reread: %v", acct.Sqid, err)
+ return nil
+ }
+ if row != nil {
+ if err := s.publishAccountLimits(ctx, *row, now); err != nil {
+ log.Printf("console: plan %s: publish: %v", acct.Sqid, err)
+ }
+ }
+ return nil
+}
diff --git a/internal/console/planlapse_test.go b/internal/console/planlapse_test.go
new file mode 100644
index 000000000..306f9122b
--- /dev/null
+++ b/internal/console/planlapse_test.go
@@ -0,0 +1,173 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// lapseCatalog is the example catalog plus "hobby", a second unpaid plan
+// with a lower running-things cap than free.
+func lapseCatalog(t *testing.T) *plans.Catalog {
+ t.Helper()
+ b, err := os.ReadFile(exampleCatalogPath)
+ if err != nil {
+ 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)
+ c, err := plans.ParseCatalog([]byte(s))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+// applyPlan runs applyAccountPlan as an operator would.
+func applyPlan(t *testing.T, fx *consoleFixture, acct *Account, plan string, packs map[string]int, sponsored *plans.Limits, now time.Time) {
+ t.Helper()
+ source := PlanSourceOperator
+ if sponsored != nil {
+ source = PlanSourceSponsored
+ }
+ if err := fx.srv.applyAccountPlan(context.Background(), acct, plan, packs, source, sponsored, "r", "ops@example.com", now); err != nil {
+ t.Fatalf("applyAccountPlan %s: %v", plan, err)
+ }
+}
+
+func lapseSince(t *testing.T, fx *consoleFixture, acct *Account) time.Time {
+ t.Helper()
+ row, err := fx.st.AccountPlan(acct.ID)
+ if err != nil || row == nil {
+ t.Fatalf("plan row: %+v, %v", row, err)
+ }
+ return row.LapseSince
+}
+
+func TestApplyAccountPlanMarksALapse(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ 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)
+ }
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ if got := lapseSince(t, fx, acct); !got.Equal(planNow) {
+ t.Fatalf("personal -> free: lapse_since = %v, want %v", got, planNow)
+ }
+ 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)
+ }
+}
+
+func TestApplyAccountPlanPackReductionIsALapse(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ 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) {
+ t.Fatalf("pack reduction: lapse_since = %v, want %v", got, planNow)
+ }
+}
+
+func TestApplyAccountPlanNeverPaidIsNoLapse(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = lapseCatalog(t)
+ acct := planAccount(t, fx, 501)
+ applyPlan(t, fx, acct, "free", nil, nil, planNow.Add(-2*time.Hour))
+ // An operator row moving to a lower unpaid plan never paid.
+ applyPlan(t, fx, acct, "hobby", nil, nil, planNow.Add(-time.Hour))
+ if got := lapseSince(t, fx, acct); !got.IsZero() {
+ t.Fatalf("free -> hobby marked a lapse at %v", got)
+ }
+ // Nor does a free account given a lower sponsored figure.
+ other := planAccount(t, fx, 502)
+ applyPlan(t, fx, other, "free", nil, &plans.Limits{RunningThings: 1}, planNow)
+ if got := lapseSince(t, fx, other); !got.IsZero() {
+ t.Fatalf("free -> sponsored lower figure marked a lapse at %v", got)
+ }
+}
+
+func TestApplyAccountPlanSponsoredIsNoLapse(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
+ applyPlan(t, fx, acct, "free", nil, &plans.Limits{RunningThings: 3}, planNow)
+ if got := lapseSince(t, fx, acct); !got.IsZero() {
+ t.Fatalf("personal -> sponsored free marked a lapse at %v", got)
+ }
+}
+
+func TestLapseEligible(t *testing.T) {
+ marked := &AccountPlanRow{Plan: "free", Source: PlanSourceOperator, LapseSince: planNow}
+ if !lapseEligible(marked) {
+ t.Fatal("a marked operator row is not eligible")
+ }
+ sponsoredSource := *marked
+ sponsoredSource.Source = PlanSourceSponsored
+ sponsoredLimits := *marked
+ sponsoredLimits.Sponsored = &plans.Limits{RunningThings: 3}
+ unset := *marked
+ unset.LapseSince = time.Time{}
+ for name, row := range map[string]*AccountPlanRow{
+ "nil row": nil, "unset lapse": &unset, "sponsored source": &sponsoredSource, "sponsored limits": &sponsoredLimits,
+ } {
+ if lapseEligible(row) {
+ t.Errorf("%s: eligible", name)
+ }
+ }
+}
+
+// Plan 6 (Checkout) and the operator door must both change a plan through
+// applyAccountPlan, so a fall is never missed.
+func TestOnlyApplyAccountPlanSetsAccountPlans(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") || f == "planlapse.go" {
+ continue
+ }
+ b, err := os.ReadFile(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(b), ".SetAccountPlan(") {
+ t.Errorf("%s calls Store.SetAccountPlan; change plans through applyAccountPlan", f)
+ }
+ }
+}
+
+func TestAccountPlanDoorUnchangedWithoutACatalog(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ token := planOperatorToken(t, fx, "ops@keymail.dev", "code-plan-nocat-lapse")
+ if status, _ := postJSON(t, accountPlanURL(fx, acct.Sqid), map[string]any{"plan": "free", "reason": "r"}, token); status != http.StatusConflict {
+ t.Fatalf("POST with no catalog = %d, want 409", status)
+ }
+ if row, _ := fx.st.AccountPlan(acct.ID); row != nil {
+ t.Fatalf("refused POST wrote %+v", row)
+ }
+}
+
+func TestApplyAccountPlanWithoutACatalogWritesOnlyThePlan(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow.Add(-time.Hour))
+ applyPlan(t, fx, acct, "free", nil, nil, planNow)
+ row, _ := fx.st.AccountPlan(acct.ID)
+ if row == nil || row.Plan != "free" || !row.LapseSince.IsZero() || row.Disabled != nil {
+ t.Fatalf("row without a catalog = %+v", row)
+ }
+}
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go
index dd9456831..d3808f839 100644
--- a/internal/console/planlimits.go
+++ b/internal/console/planlimits.go
@@ -93,6 +93,7 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n
Limits: limits,
IssuedAt: now.UTC().Truncate(time.Second),
Throttle: row.Throttle,
+ Disabled: row.Disabled,
}
for attempt := 0; attempt < 2; attempt++ {
cur, etag, err := plans.GetLimits(ctx, s.cfg.Releases, row.Sqid)
diff --git a/internal/console/planlimits_test.go b/internal/console/planlimits_test.go
index 9b00f0f63..6a4ab7a99 100644
--- a/internal/console/planlimits_test.go
+++ b/internal/console/planlimits_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"os"
+ "reflect"
"strings"
"sync/atomic"
"testing"
@@ -303,3 +304,53 @@ func TestPlanChangeClearsTheThrottle(t *testing.T) {
t.Fatalf("throttle survived a plan change: %+v", row.Throttle)
}
}
+
+func TestSetAccountDisabledBumpsRevisionOnChange(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ if changed, err := fx.st.SetAccountDisabled(acct.ID, []string{"b.example.com"}, planNow); err != nil || changed {
+ t.Fatalf("no row yet = %v, %v, want (false, nil)", changed, err)
+ }
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ t.Fatal(err)
+ }
+ before, _ := fx.st.AccountPlan(acct.ID)
+ if changed, err := fx.st.SetAccountDisabled(acct.ID, []string{"b.example.com", "A.example.com", "b.example.com"}, planNow); err != nil || !changed {
+ t.Fatalf("set = %v, %v", changed, err)
+ }
+ row, _ := fx.st.AccountPlan(acct.ID)
+ if row.Revision != before.Revision+1 || !reflect.DeepEqual(row.Disabled, []string{"a.example.com", "b.example.com"}) {
+ t.Fatalf("row after set = rev %d disabled %v", row.Revision, row.Disabled)
+ }
+ if changed, err := fx.st.SetAccountDisabled(acct.ID, []string{"a.example.com", "b.example.com"}, planNow); err != nil || changed {
+ t.Fatalf("same set again = %v, %v, want unchanged", changed, err)
+ }
+ if again, _ := fx.st.AccountPlan(acct.ID); again.Revision != row.Revision {
+ t.Fatalf("revision moved on an unchanged set: %d -> %d", row.Revision, again.Revision)
+ }
+ if changed, err := fx.st.SetAccountDisabled(acct.ID, nil, planNow); err != nil || !changed {
+ t.Fatalf("clear = %v, %v", changed, err)
+ }
+ var raw string
+ if err := fx.st.db.QueryRow(`SELECT disabled FROM account_plans WHERE account_id = ?`, acct.ID).Scan(&raw); err != nil || raw != "" {
+ t.Fatalf("cleared column = %q, %v, want \"\"", raw, err)
+ }
+ if cleared, _ := fx.st.AccountPlan(acct.ID); cleared.Disabled != nil {
+ t.Fatalf("cleared row = %v", cleared.Disabled)
+ }
+}
+
+func TestPublishCarriesDisabled(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ fx.srv.planLimitsPass(context.Background(), planNow)
+ if _, err := fx.st.SetAccountDisabled(acct.ID, []string{"shop.example.com"}, planNow); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.planLimitsPass(context.Background(), planNow.Add(time.Minute))
+ r, _ := readLimits(t, fx, acct.Sqid)
+ if r == nil || !reflect.DeepEqual(r.Disabled, []string{"shop.example.com"}) {
+ t.Fatalf("published record = %+v", r)
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index 5049a2b4f..4cd11da45 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -424,6 +424,11 @@ func (s *Store) migrate() error {
`ALTER TABLE users ADD COLUMN operator INTEGER NOT NULL DEFAULT 0;`,
// Plans 4c: the account's throttle, JSON, "" for none.
`ALTER TABLE account_plans ADD COLUMN throttle TEXT NOT NULL DEFAULT '';`,
+ // Plans 4d: when the account's limits last fell from a paid
+ // assignment (0 for no lapse), and the hosts a lapse turned off,
+ // JSON, "" for none.
+ `ALTER TABLE account_plans ADD COLUMN lapse_since INTEGER NOT NULL DEFAULT 0;`,
+ `ALTER TABLE account_plans ADD COLUMN disabled TEXT NOT NULL DEFAULT '';`,
// deliveries (tenant-email, ruling 2a): SES already publishes
// Delivery to the event destination and the ingest already
// verifies and parses it — this stops throwing the answer away.