carlos / platform Public

console: seats on the plan row; every membership change goes through the plan transition under a member lock; member caps checked inside it (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0d8b37fd7213e51417c138b2530fe11ab173d1b4 parent d6cc8a1
26 files changed, +1,110 −116
  • cmd/console/member.go +24 −2
  • cmd/console/member_test.go +59 −0
  • internal/console/accountplans.go +27 −18
  • internal/console/accountplans_test.go +8 −8
  • internal/console/apiaccountplan.go +15 −3
  • internal/console/billinglapse_test.go +1 −1
  • internal/console/billingstore.go +1 −1
  • internal/console/billingsync.go +1 −0
  • internal/console/billingsync_test.go +1 −1
  • internal/console/claim_invariant_probes_read_test.go +1 −1
  • internal/console/ownership.go +8 −1
  • internal/console/plancaps_copy.go +8 −2
  • internal/console/plancaps_doors_test.go +6 −6
  • internal/console/plancaps_test.go +4 −4
  • internal/console/plangrace_view_test.go +1 −1
  • internal/console/plangracepass_test.go +1 −1
  • internal/console/planlapse.go +42 −11
  • internal/console/planlapse_findings_test.go +1 −1
  • internal/console/planlapse_test.go +1 −1
  • internal/console/planlimits.go +12 −3
  • internal/console/planlimits_test.go +9 −9
  • internal/console/planmembers.go +208 −0
  • internal/console/planmembers_test.go +498 −0
  • internal/console/planthrottle_test.go +1 −1
  • internal/console/server.go +105 −24
  • internal/console/store.go +67 −16
diff --git a/cmd/console/member.go b/cmd/console/member.go
index 36615dde1..297c33afa 100644
--- a/cmd/console/member.go
+++ b/cmd/console/member.go
@@ -2,6 +2,7 @@ package main
import (
"context"
+ "database/sql"
"flag"
"fmt"
"log"
@@ -130,6 +131,27 @@ func runMember(args []string) {
}
}
+// memberTransition runs a membership write through the store's membership
+// transition (plans 6b), with the plan catalog when CARLOS_PLAN_CATALOG
+// names one: on a team account whose limits follow its members, the plan
+// revision moves (the console's limits pass publishes it within a minute)
+// and a fall starts the lapse, exactly as the console's own doors do.
+// Without a catalog it is just the write.
+func memberTransition(st *console.Store, acct *console.Account, write func(*sql.Tx) error) error {
+ cat, err := planCatalog()
+ if err != nil {
+ log.Fatalf("CARLOS_PLAN_CATALOG: %v", err)
+ }
+ var old *console.AccountPlanRow
+ if cat != nil {
+ if old, err = st.AccountPlan(acct.ID); err != nil {
+ return err
+ }
+ }
+ _, err = st.MembershipTransition(acct.ID, cat, old, write, time.Now())
+ return err
+}
+
func memberList(st *console.Store, acct *console.Account) {
members, err := st.Members(acct.ID)
if err != nil {
@@ -164,7 +186,7 @@ func memberAdd(st *console.Store, acct *console.Account, address, role string) {
// does the write — the count and the write cannot be separated by a
// concurrent second demotion. Surfaced here verbatim rather than
// re-checked: two copies of a safety rule is one copy too many.
- if err := st.AddMember(acct.ID, address, role, time.Now()); err != nil {
+ if err := memberTransition(st, acct, console.AddMemberWrite(acct.ID, address, role, time.Now())); err != nil {
log.Fatal(err)
}
if current == "" {
@@ -187,7 +209,7 @@ func memberRemove(st *console.Store, acct *console.Account, address string) {
fmt.Printf("%s is not a member of %s (%s) — nothing to do\n", address, acct.Sqid, acct.Name)
return
}
- if err := st.RemoveMember(acct.ID, address); err != nil {
+ if err := memberTransition(st, acct, console.RemoveMemberWrite(acct.ID, address)); err != nil {
log.Fatal(err)
}
fmt.Printf("removed %s (%s) from %s (%s)\n", address, current, acct.Sqid, acct.Name)
diff --git a/cmd/console/member_test.go b/cmd/console/member_test.go
index 31c9f8663..86cfe264d 100644
--- a/cmd/console/member_test.go
+++ b/cmd/console/member_test.go
@@ -1,6 +1,7 @@
package main_test
import (
+ "fmt"
"path/filepath"
"strings"
"testing"
@@ -334,3 +335,61 @@ func roleOf(t *testing.T, dbPath string, accountID int64, address string) string
}
return role
}
+
+// A box-side removal on a live-counted team account goes through the same
+// membership transition as the console's doors: the revision moves (so the
+// console's limits pass republishes) and a fall starts the lapse.
+func TestCLIMembershipTransition(t *testing.T) {
+ bin := buildConsole(t)
+ tmp := t.TempDir()
+ dbPath := filepath.Join(tmp, "console.db")
+ catalog, err := filepath.Abs("../../internal/plans/testdata/example-catalog.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ run := runner(t, bin, "CONSOLE_DB="+dbPath, "CARLOS_PLAN_CATALOG="+catalog)
+
+ st, err := console.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := st.CreateAccount(42, "cdef", "Kass", "solo@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 13; i++ {
+ if err := st.AddMember(42, fmt.Sprintf("m%d@keymail.dev", i), console.RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := st.SetAccountPlan(42, "community", nil, 0, console.PlanSourceOperator, nil, "r", "ops@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ before, err := st.AccountPlan(42)
+ if err != nil || before == nil {
+ t.Fatalf("plan row: %+v, %v", before, err)
+ }
+ st.Close()
+
+ if out, err := run("member", "-remove", "m0@keymail.dev", "cdef"); err != nil {
+ t.Fatalf("member -remove: %v\n%s", err, out)
+ }
+ st, err = console.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer st.Close()
+ after, err := st.AccountPlan(42)
+ if err != nil || after == nil {
+ t.Fatalf("plan row: %+v, %v", after, err)
+ }
+ if after.Revision != before.Revision+1 {
+ t.Fatalf("revision %d -> %d, want +1", before.Revision, after.Revision)
+ }
+ if after.LapseSince.IsZero() {
+ t.Fatal("14 -> 13 members on a live-counted community row did not start a lapse")
+ }
+ if n, err := st.MemberCount(42); err != nil || n != 13 {
+ t.Fatalf("members = %d, %v; want 13", n, err)
+ }
+}
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go
index e86dddc10..62b4db272 100644
--- a/internal/console/accountplans.go
+++ b/internal/console/accountplans.go
@@ -48,11 +48,15 @@ type AccountPlanRow struct {
LapseSince time.Time
// Disabled lists the hosts a lapse turned off, sorted; nil for none.
Disabled []string
+ // Seats is the paid seat count billing wrote (plans 6b): a team plan's
+ // limits follow it while it is above 0. 0 means "count the members
+ // now" (planMembers).
+ Seats int
}
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.lapse_since, p.disabled`
+ p.lapse_since, p.disabled, p.seats`
func scanAccountPlan(sc interface{ Scan(...any) error }) (*AccountPlanRow, error) {
var r AccountPlanRow
@@ -60,7 +64,7 @@ func scanAccountPlan(sc interface{ Scan(...any) error }) (*AccountPlanRow, error
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,
- &lapse, &disabled); err != nil {
+ &lapse, &disabled, &r.Seats); err != nil {
return nil, err
}
if lapse != 0 {
@@ -100,15 +104,16 @@ func (s *Store) AccountPlan(accountID int64) (*AccountPlanRow, error) {
return r, err
}
-// SetAccountPlan writes the account's plan and returns its new revision.
+// SetAccountPlan writes the account's plan and seats and returns its new
+// revision. seats is the paid seat count (0 for "count the members").
// It drops the account's throttle (plans 4c, Astra finding 3): a bigger
// plan's relief must reach the boxes with its limits, and the grace pass
// sets the throttle again within the hour if the new plan is still
// exceeded.
// It validates nothing: callers check the plan against the catalog first.
-func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, source string,
+func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]int, seats int, source string,
sponsored *plans.Limits, reason, by string, now time.Time) (int64, error) {
- args, err := accountPlanUpsertArgs(accountID, plan, packs, source, sponsored, reason, by, now)
+ args, err := accountPlanUpsertArgs(accountID, plan, packs, seats, source, sponsored, reason, by, now)
if err != nil {
return 0, err
}
@@ -125,17 +130,20 @@ func (s *Store) SetAccountPlan(accountID int64, plan string, packs map[string]in
// a deleted account writes nothing, and every change bumps the revision
// and drops the throttle.
const accountPlanUpsertSQL = `INSERT INTO account_plans
- (account_id, plan, packs, source, sponsored, reason, revision, updated_by, updated_at)
- SELECT ?, ?, ?, ?, ?, ?, 1, ?, ? WHERE EXISTS (SELECT 1 FROM accounts WHERE id = ? AND deleted_at = 0)
- ON CONFLICT(account_id) DO UPDATE SET plan = excluded.plan, packs = excluded.packs,
+ (account_id, plan, packs, seats, source, sponsored, reason, revision, updated_by, updated_at)
+ SELECT ?, ?, ?, ?, ?, ?, ?, 1, ?, ? WHERE EXISTS (SELECT 1 FROM accounts WHERE id = ? AND deleted_at = 0)
+ ON CONFLICT(account_id) DO UPDATE SET plan = excluded.plan, packs = excluded.packs, seats = excluded.seats,
source = excluded.source, sponsored = excluded.sponsored, reason = excluded.reason,
updated_by = excluded.updated_by, updated_at = excluded.updated_at, revision = revision + 1,
throttle = ''
RETURNING revision`
// accountPlanUpsertArgs are accountPlanUpsertSQL's arguments.
-func accountPlanUpsertArgs(accountID int64, plan string, packs map[string]int, source string,
+func accountPlanUpsertArgs(accountID int64, plan string, packs map[string]int, seats int, source string,
sponsored *plans.Limits, reason, by string, now time.Time) ([]any, error) {
+ if seats < 0 {
+ return nil, errors.New("console: negative seats")
+ }
pj, err := canonicalPacks(packs)
if err != nil {
return nil, err
@@ -148,7 +156,7 @@ func accountPlanUpsertArgs(accountID int64, plan string, packs map[string]int, s
}
sj = string(b)
}
- return []any{accountID, plan, pj, source, sj, reason, by, now.Unix(), accountID}, nil
+ return []any{accountID, plan, pj, seats, source, sj, reason, by, now.Unix(), accountID}, nil
}
// canonicalPacks is the stored form of a pack map: JSON with sorted keys,
@@ -167,12 +175,12 @@ const planBilling = "billing"
// setBillingPlanTx is billing's guarded plan write (plans 6a), inside the
// caller's transaction (Store.SaveBillingSync): it writes only a missing
// row or one whose source is default or billing, and only when the plan,
-// canonical packs or source would change, so an unchanged subscription
-// never bumps the revision or clears the 4c throttle. An operator or
+// canonical packs, seats (plans 6b) or source would change, so an unchanged
+// subscription never bumps the revision or clears the 4c throttle. An operator or
// sponsored row is never touched (not written, not owned). A deleted
// account is ErrAccountGone. The writer named is always "billing". It
// never commits.
-func setBillingPlanTx(tx *sql.Tx, accountID int64, plan string, packs map[string]int, reason string, now time.Time) (written, owned bool, err error) {
+func setBillingPlanTx(tx *sql.Tx, accountID int64, plan string, packs map[string]int, seats int, reason string, now time.Time) (written, owned bool, err error) {
want, err := canonicalPacks(packs)
if err != nil {
return false, false, err
@@ -185,7 +193,8 @@ func setBillingPlanTx(tx *sql.Tx, accountID int64, plan string, packs map[string
return false, false, ErrAccountGone
}
var curPlan, curPacks, curSource string
- err = tx.QueryRow(`SELECT plan, packs, source FROM account_plans WHERE account_id = ?`, accountID).Scan(&curPlan, &curPacks, &curSource)
+ var curSeats int
+ err = tx.QueryRow(`SELECT plan, packs, source, seats FROM account_plans WHERE account_id = ?`, accountID).Scan(&curPlan, &curPacks, &curSource, &curSeats)
switch {
case errors.Is(err, sql.ErrNoRows):
case err != nil:
@@ -201,11 +210,11 @@ func setBillingPlanTx(tx *sql.Tx, accountID int64, plan string, packs map[string
if err != nil {
return false, true, err
}
- if curPlan == plan && have == want && curSource == PlanSourceBilling {
+ if curPlan == plan && have == want && curSeats == seats && curSource == PlanSourceBilling {
return false, true, nil
}
}
- if err := billingSetPlan(tx, accountID, plan, packs, reason, now); err != nil {
+ if err := billingSetPlan(tx, accountID, plan, packs, seats, reason, now); err != nil {
return false, true, err
}
return true, true, nil
@@ -217,8 +226,8 @@ func setBillingPlanTx(tx *sql.Tx, accountID int64, plan string, packs map[string
// cannot be split by another write. Billing reaches it only through
// Server.applyBillingPlan, Plan 4d's shared plan transition (lapse lock,
// lapse mark, re-converge, publish).
-func billingSetPlan(tx *sql.Tx, accountID int64, plan string, packs map[string]int, reason string, now time.Time) error {
- args, err := accountPlanUpsertArgs(accountID, plan, packs, PlanSourceBilling, nil, reason, planBilling, now)
+func billingSetPlan(tx *sql.Tx, accountID int64, plan string, packs map[string]int, seats int, reason string, now time.Time) error {
+ args, err := accountPlanUpsertArgs(accountID, plan, packs, seats, PlanSourceBilling, nil, reason, planBilling, now)
if err != nil {
return err
}
diff --git a/internal/console/accountplans_test.go b/internal/console/accountplans_test.go
index 6a48b2f92..a3e5bc5d2 100644
--- a/internal/console/accountplans_test.go
+++ b/internal/console/accountplans_test.go
@@ -42,11 +42,11 @@ func TestSetAccountPlanBumpsRevision(t *testing.T) {
st, ids := planStore(t, "aaa")
id := ids["aaa"]
sp := &plans.Limits{RunningThings: 12}
- rev, err := st.SetAccountPlan(id, "personal", map[string]int{"apps": 2}, "sponsored", sp, "existing user", "ops@example.com", planNow)
+ rev, err := st.SetAccountPlan(id, "personal", map[string]int{"apps": 2}, 0, "sponsored", sp, "existing user", "ops@example.com", planNow)
if err != nil || rev != 1 {
t.Fatalf("first set: rev %d, %v", rev, err)
}
- rev, err = st.SetAccountPlan(id, "personal", map[string]int{"apps": 3}, "sponsored", sp, "more apps", "ops@example.com", planNow)
+ rev, err = st.SetAccountPlan(id, "personal", map[string]int{"apps": 3}, 0, "sponsored", sp, "more apps", "ops@example.com", planNow)
if err != nil || rev != 2 {
t.Fatalf("second set: rev %d, %v", rev, err)
}
@@ -64,7 +64,7 @@ func TestSetAccountPlanBumpsRevision(t *testing.T) {
if row.Sponsored == nil || *row.Sponsored != *sp {
t.Fatalf("sponsored %+v", row.Sponsored)
}
- if _, err := st.SetAccountPlan(id, "free", nil, "operator", nil, "back to free", "ops@example.com", planNow); err != nil {
+ if _, err := st.SetAccountPlan(id, "free", nil, 0, "operator", nil, "back to free", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
row, _ = st.AccountPlan(id)
@@ -75,7 +75,7 @@ func TestSetAccountPlanBumpsRevision(t *testing.T) {
func TestEnsureDefaultPlansInsertsOnlyMissing(t *testing.T) {
st, ids := planStore(t, "aaa", "bbb", "ccc")
- if _, err := st.SetAccountPlan(ids["bbb"], "personal", nil, "operator", nil, "paid", "ops@example.com", planNow); err != nil {
+ if _, err := st.SetAccountPlan(ids["bbb"], "personal", nil, 0, "operator", nil, "paid", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
n, err := st.EnsureDefaultPlans("free", planNow)
@@ -149,7 +149,7 @@ func TestMarkPlanPublishedIgnoresAStaleRevision(t *testing.T) {
st, ids := planStore(t, "aaa")
id := ids["aaa"]
for range 2 {
- if _, err := st.SetAccountPlan(id, "free", nil, "operator", nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := st.SetAccountPlan(id, "free", nil, 0, "operator", nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
}
@@ -173,13 +173,13 @@ func TestSetAccountPlanRefusesADeletedAccount(t *testing.T) {
if _, err := st.db.Exec(`UPDATE accounts SET deleted_at = ? WHERE id = ?`, planNow.Unix(), ids["gone"]); err != nil {
t.Fatal(err)
}
- if _, err := st.SetAccountPlan(ids["gone"], "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); !errors.Is(err, ErrAccountGone) {
+ if _, err := st.SetAccountPlan(ids["gone"], "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); !errors.Is(err, ErrAccountGone) {
t.Fatalf("err %v, want ErrAccountGone", err)
}
if row, _ := st.AccountPlan(ids["gone"]); row != nil {
t.Fatalf("wrote %+v", row)
}
- if _, err := st.SetAccountPlan(999999, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); !errors.Is(err, ErrAccountGone) {
+ if _, err := st.SetAccountPlan(999999, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); !errors.Is(err, ErrAccountGone) {
t.Fatalf("unknown account: err %v, want ErrAccountGone", err)
}
}
@@ -241,7 +241,7 @@ func TestSetBillingPlanLeavesSponsoredAndOperatorRows(t *testing.T) {
if source == PlanSourceSponsored {
sponsored = &plans.Limits{RunningThings: 50}
}
- if _, err := st.SetAccountPlan(ids["bab"], "free", nil, source, sponsored, "by hand", "op@example.com", planNow); err != nil {
+ if _, err := st.SetAccountPlan(ids["bab"], "free", nil, 0, source, sponsored, "by hand", "op@example.com", planNow); err != nil {
t.Fatal(err)
}
before, _ := st.AccountPlan(ids["bab"])
diff --git a/internal/console/apiaccountplan.go b/internal/console/apiaccountplan.go
index 6d74db486..d7d0dd575 100644
--- a/internal/console/apiaccountplan.go
+++ b/internal/console/apiaccountplan.go
@@ -110,7 +110,15 @@ func (s *Server) handleAPIAccountPlanSet(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusBadRequest, msg)
return
}
- if _, err := s.cfg.PlanCatalog.Effective(req.Plan, req.Packs, req.Sponsored, 1); err != nil {
+ // Validated at the live member count: the door writes seats 0, so a
+ // team plan's limits follow the members.
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ log.Printf("console: api account plan %s: member count: %v", acct.Sqid, err)
+ jsonError(w, http.StatusInternalServerError, planCopySaveFailed)
+ return
+ }
+ if _, err := s.cfg.PlanCatalog.Effective(req.Plan, req.Packs, req.Sponsored, members); err != nil {
jsonError(w, http.StatusBadRequest, err.Error())
return
}
@@ -118,7 +126,7 @@ func (s *Server) handleAPIAccountPlanSet(w http.ResponseWriter, r *http.Request)
if req.Sponsored != nil {
source = PlanSourceSponsored
}
- if err := s.applyAccountPlan(r.Context(), acct, req.Plan, req.Packs, source, req.Sponsored, reason, addr, time.Now()); err != nil {
+ if err := s.applyAccountPlan(r.Context(), acct, req.Plan, req.Packs, 0, source, req.Sponsored, reason, addr, time.Now()); err != nil {
if errors.Is(err, ErrAccountGone) {
http.NotFound(w, r)
return
@@ -179,7 +187,11 @@ func (s *Server) accountPlanReplyFor(acct *Account) (accountPlanReply, error) {
reply.PublishedRevision = 0
}
}
- if l, err := cat.Effective(reply.Plan, reply.Packs, reply.Sponsored, 1); err != nil {
+ members, err := s.planMembers(row, acct.ID)
+ if err != nil {
+ return accountPlanReply{}, err
+ }
+ if l, err := cat.Effective(reply.Plan, reply.Packs, reply.Sponsored, members); err != nil {
reply.LimitsError = err.Error()
} else {
reply.Limits = &l
diff --git a/internal/console/billinglapse_test.go b/internal/console/billinglapse_test.go
index db45d8703..b6a681a2e 100644
--- a/internal/console/billinglapse_test.go
+++ b/internal/console/billinglapse_test.go
@@ -135,7 +135,7 @@ func TestBillingSyncGracePassAndOperatorDoNotDeadlock(t *testing.T) {
if i%2 == 1 {
plan = "free"
}
- if err := bf.srv.applyAccountPlan(context.Background(), bf.acct, plan, nil, PlanSourceOperator, nil, "race", "ops@example.com", now); err != nil {
+ if err := bf.srv.applyAccountPlan(context.Background(), bf.acct, plan, nil, 0, PlanSourceOperator, nil, "race", "ops@example.com", now); err != nil {
t.Errorf("applyAccountPlan: %v", err)
}
}
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index b7778cd9d..bb776de20 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -343,7 +343,7 @@ func (s *Store) SaveBillingSync(next *billingAccount, accountID int64, plan *pla
}
}
if plan != nil {
- written, owned, err = setBillingPlanTx(tx, accountID, plan.Plan, plan.Packs, plan.Reason, now)
+ written, owned, err = setBillingPlanTx(tx, accountID, plan.Plan, plan.Packs, plan.Seats, plan.Reason, now)
if errors.Is(err, ErrAccountGone) {
return false, false, nil
}
diff --git a/internal/console/billingsync.go b/internal/console/billingsync.go
index bdd7e30c8..11d76ce7c 100644
--- a/internal/console/billingsync.go
+++ b/internal/console/billingsync.go
@@ -31,6 +31,7 @@ type billingInput struct {
type planChange struct {
Plan string
Packs map[string]int
+ Seats int // the paid seat count (plans 6b); 0 counts the members
Reason string
}
diff --git a/internal/console/billingsync_test.go b/internal/console/billingsync_test.go
index e9c535f13..a5810edc1 100644
--- a/internal/console/billingsync_test.go
+++ b/internal/console/billingsync_test.go
@@ -319,7 +319,7 @@ func TestSyncUnchangedKeepsThrottle(t *testing.T) {
func TestPaidSubscriptionOnSponsoredAccountOpensProblem(t *testing.T) {
bf := newBillingFixture(t)
- if _, err := bf.st.SetAccountPlan(bf.acct.ID, "free", nil, PlanSourceSponsored, &plans.Limits{RunningThings: 40}, "friend", "op@example.com", billingNow); err != nil {
+ if _, err := bf.st.SetAccountPlan(bf.acct.ID, "free", nil, 0, PlanSourceSponsored, &plans.Limits{RunningThings: 40}, "friend", "op@example.com", billingNow); err != nil {
t.Fatal(err)
}
before, _ := bf.st.AccountPlan(bf.acct.ID)
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index ea7d1efe0..4d05a078e 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -49,7 +49,7 @@ func claimWorldFleet(t *testing.T, cx *claimCase) { t.Helper(); cx.fleet(t) }
func claimWorldLapse(t *testing.T, cx *claimCase) {
t.Helper()
cx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
- if _, err := cx.st.SetAccountPlan(OpsAccountID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil {
+ if _, err := cx.st.SetAccountPlan(OpsAccountID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil {
t.Fatal(err)
}
if err := cx.st.MarkLapse(OpsAccountID, time.Now()); err != nil {
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 3a75c603c..7fb9ad5c4 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -47,7 +47,14 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
return
}
target := strings.TrimSpace(r.FormValue("address"))
- if err := s.store.RemoveMember(acct.ID, target); err != nil {
+ // Under the member lock and through the membership transition (plans
+ // 6b): a team account's limits follow the removal at once.
+ unlock := s.lockMembers(acct.Sqid)
+ err := s.membershipTransition(r.Context(), acct, time.Now(), func(tx *sql.Tx) error {
+ return removeMemberTx(tx, acct.ID, target)
+ })
+ unlock()
+ if err != nil {
log.Printf("console: remove member: %v", err)
s.setFlash(w, "err", removalAdvice(err, target))
} else {
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go
index 50a643147..92a31958f 100644
--- a/internal/console/plancaps_copy.go
+++ b/internal/console/plancaps_copy.go
@@ -8,17 +8,23 @@ package console
var capCopy = map[string]string{
"browser.cap.running_things": "This account is running %d apps and instances, the most its plan allows. Delete one to make room, or move to a plan that allows more.",
"browser.cap.restore": "Restoring %s would take this account past the %d apps and instances its plan allows. Delete one first, or move to a plan that allows more.",
- "browser.cap.free_account": "You already own a free account, and each person can own one. Use that account, or ask an operator for another.",
+ "browser.cap.free_account": "You already own a free account, and each person can own one. Upgrade that account to create another, or ask an operator.",
"browser.cap.custom_domain": "Custom domains need a paid plan. On this plan the app keeps its platform address.",
"cli.cap.running_things": "this account is running %d apps and instances, the most its plan allows. delete one to make room, or move to a plan that allows more",
"cli.cap.restore": "restoring %s would take this account past the %d apps and instances its plan allows. delete one first, or move to a plan that allows more",
"cli.cap.sidecars": "%s already has %d workers, the most its plan allows. remove one first, or move to a plan that allows more",
- "cli.cap.free_account": "you already own a free account, and each person can own one. use that account, or ask an operator for another",
+ "cli.cap.free_account": "you already own a free account, and each person can own one. upgrade that account to create another, or ask an operator",
"cli.cap.fleets": "this account's plan does not include its own boxes (fleets). move to a plan that does to add one",
"cli.cap.custom_domain": "custom domains need a paid plan. on this plan the app keeps its platform address",
"cli.cap.daemon": "this release declares the daemon capability, which keeps an app running all the time. on shared boxes apps sleep when idle, so place the app on your own boxes (a fleet) to run it, or ship it without daemon",
"cli.cap.always_on": "on shared boxes apps sleep when idle, so sidecars cannot be set to stay awake. place the app on your own boxes (a fleet) to keep them running, or remove hibernate: false",
"cli.cap.schedule": "on shared boxes this plan runs schedules at most every %d minutes. choose a longer interval, place the app on your own boxes (a fleet), or move to a plan that allows more",
+ // Plans 6b: the member cap and the free-account refusal above. DRAFTS
+ // for the Luna pass.
+ "browser.cap.members": "This plan has room for %d members. Move to a team plan to add more.",
+ "browser.cap.members_join": "This account is full on its plan. Ask an owner to move it to a team plan.",
+ "cli.cap.members": "this plan has room for %d members. move to a team plan to add more",
+ "cli.cap.members_join": "this account is full on its plan. ask an owner to move it to a team plan",
}
// planCheckFailedCopy is the approved answer when an account's plan could
diff --git a/internal/console/plancaps_doors_test.go b/internal/console/plancaps_doors_test.go
index b8238cd82..b94632859 100644
--- a/internal/console/plancaps_doors_test.go
+++ b/internal/console/plancaps_doors_test.go
@@ -42,7 +42,7 @@ func atRunningCap(t *testing.T, fx *consoleFixture, capN int) *Account {
}
capsApp(t, fx, acct, fmt.Sprintf("filler%02d", i))
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceSponsored, &plans.Limits{RunningThings: capN}, "test", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceSponsored, &plans.Limits{RunningThings: capN}, "test", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
return acct
@@ -54,7 +54,7 @@ func raiseRunningCap(t *testing.T, fx *consoleFixture, acct *Account, by int) {
if err != nil {
t.Fatal(err)
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceSponsored, &plans.Limits{RunningThings: n + by}, "test", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceSponsored, &plans.Limits{RunningThings: n + by}, "test", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
}
@@ -168,7 +168,7 @@ func sponsorCustomDomains(t *testing.T, fx *consoleFixture, acct *Account) {
}
sp := *row.Sponsored
sp.CustomDomains = true
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceSponsored, &sp, "test", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceSponsored, &sp, "test", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
}
@@ -272,7 +272,7 @@ func TestNewAccountAllowedWhenTheOtherIsPaid(t *testing.T) {
fx := newConsoleFixture(t)
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
ops, _ := fx.st.AccountBySqid(fx.sqid)
- if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
token := cliToken(t, fx, "paul@keymail.dev", "code-cap-acct-paid")
@@ -354,7 +354,7 @@ func TestFreeAccountCapIsExactUnderConcurrentCreates(t *testing.T) {
fx := newConsoleFixture(t)
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
ops, _ := fx.st.AccountBySqid(fx.sqid)
- if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
token := cliToken(t, fx, "paul@keymail.dev", "code-cap-acct-race")
@@ -518,7 +518,7 @@ func TestScheduleMinimumOnAPaidPlan(t *testing.T) {
fx, token := scheduleFixture(t, "code-cap-schedule-paid")
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
ops, _ := fx.st.AccountBySqid(fx.sqid)
- if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(ops.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
if status := setSchedule(t, fx, token, `{"name":"minutely","every":"1m","path":"/jobs/x"}`); status != http.StatusOK {
diff --git a/internal/console/plancaps_test.go b/internal/console/plancaps_test.go
index 57f123012..cdd311d48 100644
--- a/internal/console/plancaps_test.go
+++ b/internal/console/plancaps_test.go
@@ -111,7 +111,7 @@ func TestRunningThingsCapUsesEffectiveLimits(t *testing.T) {
fx := newConsoleFixture(t)
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
acct := planAccount(t, fx, 501)
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceSponsored, &plans.Limits{RunningThings: 300}, "existing account", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceSponsored, &plans.Limits{RunningThings: 300}, "existing account", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
for i := range 4 {
@@ -134,7 +134,7 @@ func TestSidecarCap(t *testing.T) {
if err := fx.srv.checkSidecars(context.Background(), acct, "shop"); !isCap(err) {
t.Fatalf("free, one sidecar: %v, want a plan cap", err)
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
for _, n := range []string{"w2", "w3", "w4"} {
@@ -157,7 +157,7 @@ func TestNewFreeAccountCap(t *testing.T) {
if err := fx.srv.checkNewFreeAccount(owner); !isCap(err) {
t.Fatalf("owner of one free account: %v, want a plan cap", err)
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
if err := fx.srv.checkNewFreeAccount(owner); err != nil {
@@ -180,7 +180,7 @@ func TestFleetsAndCustomDomainsFollowThePlan(t *testing.T) {
if !isCap(fx.srv.checkFleets(acct)) || !isCap(fx.srv.checkCustomDomains(acct)) {
t.Fatal("free plan allowed fleets or custom domains")
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
if fx.srv.checkFleets(acct) != nil || fx.srv.checkCustomDomains(acct) != nil {
diff --git a/internal/console/plangrace_view_test.go b/internal/console/plangrace_view_test.go
index 640ff89d0..e0a928082 100644
--- a/internal/console/plangrace_view_test.go
+++ b/internal/console/plangrace_view_test.go
@@ -141,7 +141,7 @@ func lapsedOps(t *testing.T, fx *consoleFixture) (*Account, capState) {
t.Helper()
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
acct, _ := fx.st.AccountBySqid(fx.sqid)
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", time.Now()); err != nil {
t.Fatal(err)
}
if err := fx.st.MarkLapse(acct.ID, time.Now().Add(-time.Hour)); err != nil {
diff --git a/internal/console/plangracepass_test.go b/internal/console/plangracepass_test.go
index aa6955169..a7134d583 100644
--- a/internal/console/plangracepass_test.go
+++ b/internal/console/plangracepass_test.go
@@ -122,7 +122,7 @@ func TestGracePassSkipsUnreadableMeasurements(t *testing.T) {
if err := fx.st.PutCapState(over); err != nil {
t.Fatal(err)
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, "operator", nil, "test", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, 0, "operator", nil, "test", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
fx.srv.planGracePass(context.Background(), planNow) // no storage sweep exists: storage is unknown
diff --git a/internal/console/planlapse.go b/internal/console/planlapse.go
index d17ea9710..320326314 100644
--- a/internal/console/planlapse.go
+++ b/internal/console/planlapse.go
@@ -25,18 +25,21 @@ func planRowSponsored(row *AccountPlanRow) bool {
// 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 {
+// price starts nothing. Team plans are compared at their member counts
+// (plans 6b): the old row's seats, or the live count when it has none, and
+// seats, or the live count, for the new assignment; a count that cannot be
+// read starts nothing.
+func (s *Server) lapseStarted(accountID int64, old *AccountPlanRow, plan string, packs map[string]int, seats int, sponsored *plans.Limits) bool {
cat := s.cfg.PlanCatalog
if cat == nil || sponsored != nil {
return false
}
- oldPlan, oldPacks := cat.DefaultPlan, map[string]int(nil)
+ oldPlan, oldPacks, oldSeats := cat.DefaultPlan, map[string]int(nil), 0
if old != nil {
if planRowSponsored(old) {
return false
}
- oldPlan, oldPacks = old.Plan, old.Packs
+ oldPlan, oldPacks, oldSeats = old.Plan, old.Packs, old.Seats
}
p, ok := cat.Plans[oldPlan]
if !ok {
@@ -51,11 +54,34 @@ func (s *Server) lapseStarted(old *AccountPlanRow, plan string, packs map[string
if !paid {
return false
}
- was, err := cat.Effective(oldPlan, oldPacks, nil, 1)
+ live := -1
+ members := func(seats int) (int, bool) {
+ if seats > 0 {
+ return seats, true
+ }
+ if live < 0 {
+ n, err := s.store.MemberCount(accountID)
+ if err != nil {
+ log.Printf("console: plan lapse: member count for account %d: %v", accountID, err)
+ return 0, false
+ }
+ live = n
+ }
+ return live, true
+ }
+ wasMembers, ok := members(oldSeats)
+ if !ok {
+ return false
+ }
+ nextMembers, ok := members(seats)
+ if !ok {
+ return false
+ }
+ was, err := cat.Effective(oldPlan, oldPacks, nil, wasMembers)
if err != nil {
return false
}
- next, err := cat.Effective(plan, packs, nil, 1)
+ next, err := cat.Effective(plan, packs, nil, nextMembers)
if err != nil {
return false
}
@@ -71,13 +97,18 @@ func (s *Server) lapseStarted(old *AccountPlanRow, plan string, packs map[string
// 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 {
+// seats is the paid seat count (plans 6b); the operator door passes 0, so
+// a team plan's limits follow the member count.
+func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan string, packs map[string]int, seats int,
+ source string, sponsored *plans.Limits, reason, by string, now time.Time) error {
return s.transitionAccountPlan(ctx, acct, now, func(old *AccountPlanRow) (bool, error) {
- if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, source, sponsored, reason, by, now); err != nil {
+ // The fall is judged before the write, while the old row is the
+ // one the store holds.
+ fell := s.lapseStarted(acct.ID, old, plan, packs, seats, sponsored)
+ if _, err := s.store.SetAccountPlan(acct.ID, plan, packs, seats, source, sponsored, reason, by, now); err != nil {
return false, err
}
- if s.lapseStarted(old, plan, packs, sponsored) {
+ if fell {
if err := s.store.MarkLapse(acct.ID, now); err != nil {
return true, err
}
@@ -105,7 +136,7 @@ func (s *Server) applyAccountPlan(ctx context.Context, acct *Account, plan strin
// then the store transaction. Nothing takes them the other way round.
func (s *Server) applyBillingPlan(ctx context.Context, acct *Account, next *billingAccount, plan *planChange, now time.Time) (written, owned bool, err error) {
err = s.transitionAccountPlan(ctx, acct, now, func(old *AccountPlanRow) (bool, error) {
- lapse := plan != nil && s.lapseStarted(old, plan.Plan, plan.Packs, nil)
+ lapse := plan != nil && s.lapseStarted(acct.ID, old, plan.Plan, plan.Packs, plan.Seats, nil)
written, owned, err = s.store.SaveBillingSync(next, acct.ID, plan, lapse, lapseCaps, now)
return written, err
})
diff --git a/internal/console/planlapse_findings_test.go b/internal/console/planlapse_findings_test.go
index f7ba22176..32bd83aad 100644
--- a/internal/console/planlapse_findings_test.go
+++ b/internal/console/planlapse_findings_test.go
@@ -28,7 +28,7 @@ func TestStaleGracePassCannotUndoAnUpgrade(t *testing.T) {
fx.srv.lapseBeforeConverge = func() {
once.Do(func() {
go func() {
- done <- fx.srv.applyAccountPlan(context.Background(), acct, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow.Add(week+time.Minute))
+ done <- fx.srv.applyAccountPlan(context.Background(), acct, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow.Add(week+time.Minute))
}()
select {
case err := <-done:
diff --git a/internal/console/planlapse_test.go b/internal/console/planlapse_test.go
index 1c80eed3b..41d405b5a 100644
--- a/internal/console/planlapse_test.go
+++ b/internal/console/planlapse_test.go
@@ -44,7 +44,7 @@ func applyPlan(t *testing.T, fx *consoleFixture, acct *Account, plan string, pac
if sponsored != nil {
source = PlanSourceSponsored
}
- if err := fx.srv.applyAccountPlan(context.Background(), acct, plan, packs, source, sponsored, "r", "ops@example.com", now); err != nil {
+ if err := fx.srv.applyAccountPlan(context.Background(), acct, plan, packs, 0, source, sponsored, "r", "ops@example.com", now); err != nil {
t.Fatalf("applyAccountPlan %s: %v", plan, err)
}
}
diff --git a/internal/console/planlimits.go b/internal/console/planlimits.go
index b508314ca..f17ebcdd0 100644
--- a/internal/console/planlimits.go
+++ b/internal/console/planlimits.go
@@ -80,7 +80,11 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n
if cat == nil {
return errors.New("no plan catalog")
}
- limits, err := cat.Effective(row.Plan, row.Packs, row.Sponsored, 1)
+ members, err := s.planMembers(&row, row.AccountID)
+ if err != nil {
+ return err
+ }
+ limits, err := cat.Effective(row.Plan, row.Packs, row.Sponsored, members)
if err != nil {
return err
}
@@ -116,7 +120,8 @@ func (s *Server) publishAccountLimits(ctx context.Context, row AccountPlanRow, n
}
// EffectiveLimits is acct's limits under the configured catalog, or nil
-// when plans are off. An account with no row is on the default plan.
+// when plans are off. An account with no row is on the default plan. A
+// team plan is limited at planMembers' count.
func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) {
cat := s.cfg.PlanCatalog
if cat == nil {
@@ -131,7 +136,11 @@ func (s *Server) EffectiveLimits(acct *Account) (*plans.Limits, error) {
if row != nil {
plan, packs, sponsored = row.Plan, row.Packs, row.Sponsored
}
- l, err := cat.Effective(plan, packs, sponsored, 1)
+ members, err := s.planMembers(row, acct.ID)
+ if err != nil {
+ return nil, err
+ }
+ l, err := cat.Effective(plan, packs, sponsored, members)
if err != nil {
return nil, err
}
diff --git a/internal/console/planlimits_test.go b/internal/console/planlimits_test.go
index 6a4ab7a99..a481f203c 100644
--- a/internal/console/planlimits_test.go
+++ b/internal/console/planlimits_test.go
@@ -121,10 +121,10 @@ func TestPlanLimitsPassSkipsAnOrphanedAssignment(t *testing.T) {
other := planAccount(t, fx, 502)
fx.srv.planLimitsPass(context.Background(), planNow)
_, before := readLimits(t, fx, orphan.Sqid)
- if _, err := fx.st.SetAccountPlan(orphan.ID, "gold", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(orphan.ID, "gold", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
- if _, err := fx.st.SetAccountPlan(other.ID, "personal", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(other.ID, "personal", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
fx.srv.planLimitsPass(context.Background(), planNow)
@@ -149,7 +149,7 @@ func TestPublishNeverOverwritesANewerRecord(t *testing.T) {
t.Fatal(err)
}
for range 3 {
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
}
@@ -210,7 +210,7 @@ func TestEffectiveLimits(t *testing.T) {
if err != nil || l == nil || l.RunningThings != 3 {
t.Fatalf("default: %+v, %v", l, err)
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "personal", map[string]int{"apps": 1}, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", map[string]int{"apps": 1}, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
l, err = fx.srv.EffectiveLimits(acct)
@@ -230,7 +230,7 @@ func TestPlanLimitsPassOrphansDoNotStarveLaterAccounts(t *testing.T) {
b := planAccount(t, fx, 502)
c := planAccount(t, fx, 503)
for _, acct := range []*Account{a, b} {
- if _, err := fx.st.SetAccountPlan(acct.ID, "gold", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "gold", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
}
@@ -243,7 +243,7 @@ func TestPlanLimitsPassOrphansDoNotStarveLaterAccounts(t *testing.T) {
func TestSetAccountThrottleBumpsRevisionOnChange(t *testing.T) {
fx := newConsoleFixture(t)
acct := planAccount(t, fx, 501)
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
before, _ := fx.st.AccountPlan(acct.ID)
@@ -291,13 +291,13 @@ func TestPublishCarriesThrottle(t *testing.T) {
func TestPlanChangeClearsTheThrottle(t *testing.T) {
fx := newConsoleFixture(t)
acct := planAccount(t, fx, 501)
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
if _, err := fx.st.SetAccountThrottle(acct.ID, &plans.Throttle{Bandwidth: true, Until: planNow.Add(time.Hour)}, planNow); err != nil {
t.Fatal(err)
}
- if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, PlanSourceOperator, nil, "upgrade", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "personal", nil, 0, PlanSourceOperator, nil, "upgrade", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
if row, _ := fx.st.AccountPlan(acct.ID); row.Throttle != nil {
@@ -311,7 +311,7 @@ func TestSetAccountDisabledBumpsRevisionOnChange(t *testing.T) {
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 {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
before, _ := fx.st.AccountPlan(acct.ID)
diff --git a/internal/console/planmembers.go b/internal/console/planmembers.go
new file mode 100644
index 000000000..0211e6aec
--- /dev/null
+++ b/internal/console/planmembers.go
@@ -0,0 +1,208 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// Seats and membership (plans 6b). A team plan's pooled limits follow its
+// member count: the paid seats billing wrote on the plan row, or, while
+// that is 0, the members counted now. So every membership change goes
+// through the plan transition (membershipTransition), under the account's
+// member lock, and invites and joins are admitted inside that lock against
+// the plan's max_members (checkMemberCap).
+//
+// Lock order: member, then billing, then lapse, then the store.
+
+// sqlQueryRower is a store handle or a transaction, for reads.
+type sqlQueryRower interface {
+ QueryRow(query string, args ...any) *sql.Row
+}
+
+// MemberCount is who the account is billed and limited for: its owners
+// and members. Pending invites and service credentials never count.
+func (s *Store) MemberCount(accountID int64) (int, error) {
+ return memberCountOn(s.db, accountID)
+}
+
+func memberCountOn(q sqlQueryRower, accountID int64) (int, error) {
+ var n int
+ err := q.QueryRow(`SELECT COUNT(*) FROM memberships WHERE account_id = ? AND role IN (?, ?)`,
+ accountID, RoleOwner, RoleMember).Scan(&n)
+ return n, err
+}
+
+// planMembers is the member count a plan row is limited at: its seats
+// when billing wrote some, else the members counted now. A nil row (the
+// default plan) counts the members.
+func (s *Server) planMembers(row *AccountPlanRow, accountID int64) (int, error) {
+ if row != nil && row.Seats > 0 {
+ return row.Seats, nil
+ }
+ return s.store.MemberCount(accountID)
+}
+
+// lockMembers takes the account's member lock and returns its release.
+// Every invite, join, revoke and removal runs under it, so a count and the
+// write it admits cannot be split by another membership change.
+//
+// LOCK ORDER: member, then billing (holdBilling), then lapse
+// (lapseLock), then the store. Never the other way round.
+func (s *Server) lockMembers(sqid string) func() {
+ lockEvent("member", sqid, lockWaiting)
+ unlock := s.memberLocks.lock(sqid)
+ lockEvent("member", sqid, lockHeld)
+ return func() {
+ lockEvent("member", sqid, lockReleased)
+ unlock()
+ }
+}
+
+// liveTeam is row's team block when row is a live-counted team row (a
+// team plan with no seats written), else nil.
+func liveTeam(cat *plans.Catalog, row *AccountPlanRow) *plans.Team {
+ if cat == nil || row == nil || row.Seats > 0 {
+ return nil
+ }
+ p, ok := cat.Plans[row.Plan]
+ if !ok {
+ return nil
+ }
+ return p.Team
+}
+
+// membershipFell reports whether a membership change from before to after
+// members is a fall that starts a lapse (plans 4d): the row is a
+// live-counted team row, paid (a paid plan or any pack) and not
+// sponsored, and a limit the lapse lifecycle governs fell.
+func membershipFell(cat *plans.Catalog, row *AccountPlanRow, before, after int) bool {
+ if liveTeam(cat, row) == nil || planRowSponsored(row) {
+ return false
+ }
+ paid := cat.Plans[row.Plan].Paid
+ for _, q := range row.Packs {
+ if q > 0 {
+ paid = true
+ }
+ }
+ if !paid {
+ return false
+ }
+ was, err := cat.Effective(row.Plan, row.Packs, nil, before)
+ if err != nil {
+ return false
+ }
+ next, err := cat.Effective(row.Plan, row.Packs, nil, after)
+ if err != nil {
+ return false
+ }
+ return plans.LimitsFell(was, next)
+}
+
+// MembershipTransition runs write, a membership change, in one
+// transaction with what it does to the plan row old (the caller's read):
+// it counts the members before and after, and on a live-counted team row
+// whose billed count changed it bumps the revision, so the limits record
+// is republished; on a fall (membershipFell) it also marks the lapse and
+// clears the lapse caps' grace clocks, as a plan change does. changed
+// reports the bump. With no catalog it is just write, committed. A write
+// error rolls everything back and comes back unchanged.
+func (s *Store) MembershipTransition(accountID int64, cat *plans.Catalog, old *AccountPlanRow,
+ write func(tx *sql.Tx) error, now time.Time) (changed bool, err error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, err
+ }
+ defer tx.Rollback()
+ team := liveTeam(cat, old)
+ var before int
+ if team != nil {
+ if before, err = memberCountOn(tx, accountID); err != nil {
+ return false, err
+ }
+ }
+ if err := write(tx); err != nil {
+ return false, err
+ }
+ if team != nil {
+ after, err := memberCountOn(tx, accountID)
+ if err != nil {
+ return false, err
+ }
+ if team.Billed(before) != team.Billed(after) {
+ if _, err := tx.Exec(`UPDATE account_plans SET revision = revision + 1, updated_at = ? WHERE account_id = ?`,
+ now.Unix(), accountID); err != nil {
+ return false, err
+ }
+ changed = true
+ if membershipFell(cat, old, before, after) {
+ if _, err := tx.Exec(markLapseSQL, now.Unix(), accountID); err != nil {
+ return false, err
+ }
+ for _, c := range lapseCaps {
+ if _, err := tx.Exec(deleteCapStateSQL, accountID, string(c)); err != nil {
+ return false, err
+ }
+ }
+ }
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return false, err
+ }
+ return changed, nil
+}
+
+// membershipTransition is every membership change in the console: write
+// inside Store.MembershipTransition, wrapped in the plan transition
+// (transitionAccountPlan), so a change that moves a team's limits
+// re-converges the account and publishes its record at once (the limits
+// pass retries a failed publication). Callers hold the account's member
+// lock. Without a catalog it is just the membership write.
+func (s *Server) membershipTransition(ctx context.Context, acct *Account, now time.Time, write func(tx *sql.Tx) error) error {
+ cat := s.cfg.PlanCatalog
+ if cat == nil {
+ _, err := s.store.MembershipTransition(acct.ID, nil, nil, write, now)
+ return err
+ }
+ return s.transitionAccountPlan(ctx, acct, now, func(old *AccountPlanRow) (bool, error) {
+ return s.store.MembershipTransition(acct.ID, cat, old, write, now)
+ })
+}
+
+// checkMemberCap refuses adding more people to an account whose plan caps
+// its members (max_members, Call 14) when they would pass the cap. Team
+// plans, sponsored rows, plans with no cap and consoles with no catalog
+// pass. Callers hold the account's member lock.
+func (s *Server) checkMemberCap(acct *Account, adding int) error {
+ cat := s.cfg.PlanCatalog
+ if cat == nil {
+ return nil
+ }
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ return err
+ }
+ plan := cat.DefaultPlan
+ if row != nil {
+ if planRowSponsored(row) {
+ return nil
+ }
+ plan = row.Plan
+ }
+ p, ok := cat.Plans[plan]
+ if !ok || p.Team != nil || p.MaxMembers <= 0 {
+ return nil
+ }
+ n, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ return err
+ }
+ if n+adding > p.MaxMembers {
+ return &planCapError{capMessage("cli.cap.members", p.MaxMembers), capMessage("browser.cap.members", p.MaxMembers)}
+ }
+ return nil
+}
diff --git a/internal/console/planmembers_test.go b/internal/console/planmembers_test.go
new file mode 100644
index 000000000..2127ff9bd
--- /dev/null
+++ b/internal/console/planmembers_test.go
@@ -0,0 +1,498 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "net/http"
+ "net/url"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// addMembers gives the account n more members, m0@example.com onwards
+// after skip.
+func addMembers(t *testing.T, fx *consoleFixture, accountID int64, skip, n int) {
+ t.Helper()
+ for i := skip; i < skip+n; i++ {
+ if err := fx.st.AddMember(accountID, fmt.Sprintf("m%d@example.com", i), RoleMember, planNow); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func memberCount(t *testing.T, fx *consoleFixture, accountID int64) int {
+ t.Helper()
+ n, err := fx.st.MemberCount(accountID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+// fillMembers adds members until the account has n.
+func fillMembers(t *testing.T, fx *consoleFixture, accountID int64, n int) {
+ t.Helper()
+ have := memberCount(t, fx, accountID)
+ if have > n {
+ t.Fatalf("account %d already has %d members, want %d", accountID, have, n)
+ }
+ addMembers(t, fx, accountID, 100, n-have)
+}
+
+func planRow(t *testing.T, fx *consoleFixture, accountID int64) *AccountPlanRow {
+ t.Helper()
+ row, err := fx.st.AccountPlan(accountID)
+ if err != nil || row == nil {
+ t.Fatalf("plan row: %+v, %v", row, err)
+ }
+ return row
+}
+
+func runningLimit(t *testing.T, fx *consoleFixture, acct *Account) int {
+ t.Helper()
+ l, err := fx.srv.EffectiveLimits(acct)
+ if err != nil || l == nil {
+ t.Fatalf("EffectiveLimits: %+v, %v", l, err)
+ }
+ return l.RunningThings
+}
+
+// removeMembers is a membership transition removing each address.
+func removeMembers(t *testing.T, fx *consoleFixture, acct *Account, now time.Time, addrs ...string) {
+ t.Helper()
+ err := fx.srv.membershipTransition(context.Background(), acct, now, func(tx *sql.Tx) error {
+ for _, a := range addrs {
+ if err := removeMemberTx(tx, acct.ID, a); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("membershipTransition: %v", err)
+ }
+}
+
+func addMembersTransition(t *testing.T, fx *consoleFixture, acct *Account, now time.Time, addrs ...string) {
+ t.Helper()
+ err := fx.srv.membershipTransition(context.Background(), acct, now, func(tx *sql.Tx) error {
+ for _, a := range addrs {
+ if err := addMemberTx(tx, acct.ID, a, RoleMember, now); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("membershipTransition: %v", err)
+ }
+}
+
+func TestTeamLimitsFollowMembers(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ fillMembers(t, fx, acct.ID, 12)
+ applyPlan(t, fx, acct, "community", nil, nil, planNow)
+ if row := planRow(t, fx, acct.ID); row.Seats != 0 {
+ t.Fatalf("operator row seats = %d, want 0", row.Seats)
+ }
+ if got := runningLimit(t, fx, acct); got != 60 {
+ t.Fatalf("12 members: running things %d, want 60", got)
+ }
+ removeMembers(t, fx, acct, planNow.Add(time.Minute), "m100@example.com", "m101@example.com")
+ if got := runningLimit(t, fx, acct); got != 50 {
+ t.Fatalf("10 members: running things %d, want 50", got)
+ }
+ // The minimum: fewer than 10 members is still limited at 10.
+ removeMembers(t, fx, acct, planNow.Add(2*time.Minute), "m102@example.com")
+ if got := runningLimit(t, fx, acct); got != 50 {
+ t.Fatalf("9 members: running things %d, want 50 (minimum 10)", got)
+ }
+}
+
+func TestSeatsPinTeamLimits(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ fillMembers(t, fx, acct.ID, 3)
+ if err := fx.srv.applyAccountPlan(context.Background(), acct, "community", nil, 14, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if row := planRow(t, fx, acct.ID); row.Seats != 14 {
+ t.Fatalf("seats = %d, want 14", row.Seats)
+ }
+ if got := runningLimit(t, fx, acct); got != 70 {
+ t.Fatalf("seats 14 with 3 members: running things %d, want 70", got)
+ }
+ // A pinned row does not follow the count.
+ rev := planRow(t, fx, acct.ID).Revision
+ addMembersTransition(t, fx, acct, planNow.Add(time.Minute), "x@example.com")
+ if row := planRow(t, fx, acct.ID); row.Revision != rev {
+ t.Fatalf("a pinned row's revision moved on a join: %d -> %d", rev, row.Revision)
+ }
+ if got := runningLimit(t, fx, acct); got != 70 {
+ t.Fatalf("seats 14 with 4 members: running things %d, want 70", got)
+ }
+}
+
+// A join on a live-counted community account, through the accept door.
+func TestMembershipRiseReconvergesAndPublishes(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.setUser("sam@keymail.dev")
+ sam := newBrowser(t)
+ signUp(t, fx, sam, "code-sam")
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := opsAccount(t, fx)
+ fillMembers(t, fx, acct.ID, 10)
+ applyPlan(t, fx, acct, "community", nil, nil, planNow)
+ before := planRow(t, fx, acct.ID)
+ tok, err := fx.st.CreateInvite(acct.ID, "sam@keymail.dev", "paul@keymail.dev", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ st, _, _ := postForm(t, sam, fx.ts.URL+"/invite/"+tok, url.Values{"csrf": {sessionToken(t, fx, sam)}})
+ if st != http.StatusSeeOther {
+ t.Fatalf("accept = %d, want 303", st)
+ }
+ if n := memberCount(t, fx, acct.ID); n != 11 {
+ t.Fatalf("members = %d, want 11", n)
+ }
+ after := planRow(t, fx, acct.ID)
+ if after.Revision != before.Revision+1 {
+ t.Fatalf("revision %d -> %d, want +1", before.Revision, after.Revision)
+ }
+ if after.PublishedRevision != after.Revision {
+ t.Fatalf("published_revision %d, want %d", after.PublishedRevision, after.Revision)
+ }
+ rec, _ := readLimits(t, fx, acct.Sqid)
+ if rec == nil || rec.Revision != after.Revision || rec.Limits.RunningThings != 55 {
+ t.Fatalf("record = %+v, want revision %d with 55 running things", rec, after.Revision)
+ }
+ // The grace pass ran on the new limits.
+ states, err := fx.st.CapStates(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ran := false
+ for _, s := range states {
+ if s.Cap == capRunningThings && s.Limit == 55 {
+ ran = true
+ }
+ }
+ if !ran {
+ t.Fatalf("no running-things state at the new limit: %+v", states)
+ }
+}
+
+func TestMembershipFallStartsLapse(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ fillMembers(t, fx, acct.ID, 14)
+ applyPlan(t, fx, acct, "community", nil, nil, planNow.Add(-time.Hour))
+ // More running things than 11 members cover (55), so the lapse
+ // outlives the call's own re-converge.
+ for i := 0; i < 60; i++ {
+ lapseApp_(t, fx, acct, fmt.Sprintf("app%02d", i), at(-200+i))
+ }
+ old := planNow.Add(-30 * 24 * time.Hour)
+ if err := fx.st.PutCapState(capState{AccountID: acct.ID, Cap: capRunningThings, Level: levelOver, Used: 99, Limit: 70,
+ FirstOver: old, GraceEnds: old.Add(week), UpdatedAt: old}); err != nil {
+ t.Fatal(err)
+ }
+ removeMembers(t, fx, acct, planNow, "m100@example.com", "m101@example.com", "m102@example.com")
+ if got := lapseSince(t, fx, acct); !got.Equal(planNow) {
+ t.Fatalf("14 -> 11: lapse_since = %v, want %v", got, planNow)
+ }
+ states, err := fx.st.CapStates(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, s := range states {
+ if s.Cap == capRunningThings && s.FirstOver.Equal(old) {
+ t.Fatalf("the running-things grace clock kept its old start: %+v", s)
+ }
+ }
+}
+
+func TestMembershipNoLimitChangeWritesNothing(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ fillMembers(t, fx, acct.ID, 4)
+ applyPlan(t, fx, acct, "community", nil, nil, planNow)
+ before := planRow(t, fx, acct.ID)
+ recBefore, etag := readLimits(t, fx, acct.Sqid)
+ addMembersTransition(t, fx, acct, planNow.Add(time.Minute), "fifth@example.com")
+ if n := memberCount(t, fx, acct.ID); n != 5 {
+ t.Fatalf("members = %d, want 5", n)
+ }
+ after := planRow(t, fx, acct.ID)
+ if after.Revision != before.Revision || !after.UpdatedAt.Equal(before.UpdatedAt) {
+ t.Fatalf("4 -> 5 (billed 10 both) bumped the row: %+v -> %+v", before, after)
+ }
+ recAfter, etag2 := readLimits(t, fx, acct.Sqid)
+ if etag2 != etag || recAfter.Revision != recBefore.Revision {
+ t.Fatalf("4 -> 5 republished: %+v (%s) -> %+v (%s)", recBefore, etag, recAfter, etag2)
+ }
+}
+
+func TestMembershipPublishFailureRetried(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := planAccount(t, fx, 501)
+ fillMembers(t, fx, acct.ID, 10)
+ applyPlan(t, fx, acct, "community", nil, nil, planNow)
+ fp := &planFailingPuts{Store: fx.rel}
+ fx.srv.cfg.Releases = fp
+ fp.n.Store(1000)
+ addMembersTransition(t, fx, acct, planNow.Add(time.Minute), "eleventh@example.com")
+ row := planRow(t, fx, acct.ID)
+ if row.PublishedRevision >= row.Revision {
+ t.Fatalf("published_revision %d not behind revision %d after a failed publish", row.PublishedRevision, row.Revision)
+ }
+ fp.n.Store(0)
+ fx.srv.planLimitsPass(context.Background(), planNow.Add(2*time.Minute))
+ row = planRow(t, fx, acct.ID)
+ if row.PublishedRevision != row.Revision {
+ t.Fatalf("the limits pass left published_revision %d, revision %d", row.PublishedRevision, row.Revision)
+ }
+ if rec, _ := readLimits(t, fx, acct.Sqid); rec == nil || rec.Limits.RunningThings != 55 {
+ t.Fatalf("record after the pass = %+v, want 55 running things", rec)
+ }
+}
+
+// memberLockWaits counts waiters on the member lock for sqid.
+func memberLockWaits(t *testing.T, sqid string) *atomic.Int32 {
+ t.Helper()
+ var n atomic.Int32
+ h := func(kind, key, event string) {
+ if kind == "member" && key == sqid && event == lockWaiting {
+ n.Add(1)
+ }
+ }
+ lifetimeLockHook.Store(&h)
+ t.Cleanup(func() { lifetimeLockHook.Store(nil) })
+ return &n
+}
+
+func waitMemberWaiters(t *testing.T, n *atomic.Int32, want int32, what string) {
+ t.Helper()
+ deadline := time.Now().Add(15 * time.Second)
+ for n.Load() < want {
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for %s", what)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+func TestConcurrentInvitesRespectCap(t *testing.T) {
+ fx := newConsoleFixture(t)
+ owner := newBrowser(t)
+ signUp(t, fx, owner, "code-owner")
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := opsAccount(t, fx)
+ fillMembers(t, fx, acct.ID, 2)
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow)
+ inviteAttempts(fx)
+ csrf := sessionToken(t, fx, owner)
+ waits := memberLockWaits(t, acct.Sqid)
+ // Hold the lock so both invites queue on it, then let them race.
+ unlock := fx.srv.lockMembers(acct.Sqid)
+ var wg sync.WaitGroup
+ for _, to := range []string{"kim@keymail.dev", "lee@keymail.dev"} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ postForm(t, owner, fx.u("/invite"), url.Values{"csrf": {csrf}, "address": {to}})
+ }()
+ }
+ waitMemberWaiters(t, waits, 3, "both invites to queue on the member lock")
+ unlock()
+ wg.Wait()
+ pending, err := fx.st.PendingInvites(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(pending) != 1 {
+ t.Fatalf("pending invites = %+v, want exactly one", pending)
+ }
+}
+
+// acceptInvitees signs up each address and gives it a pending invite to
+// the ops account made directly in the store (before the cap applied).
+func acceptInvitees(t *testing.T, fx *consoleFixture, addrs ...string) (browsers []*http.Client, tokens []string) {
+ t.Helper()
+ for i, a := range addrs {
+ fx.setUser(a)
+ b := newBrowser(t)
+ signUp(t, fx, b, fmt.Sprintf("code-invitee-%d", i))
+ tok, err := fx.st.CreateInvite(OpsAccountID, a, "paul@keymail.dev", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ browsers, tokens = append(browsers, b), append(tokens, tok)
+ }
+ return browsers, tokens
+}
+
+func TestConcurrentAcceptsRespectCap(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browsers, tokens := acceptInvitees(t, fx, "kim@keymail.dev", "lee@keymail.dev")
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := opsAccount(t, fx)
+ fillMembers(t, fx, acct.ID, 2)
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow)
+ waits := memberLockWaits(t, acct.Sqid)
+ unlock := fx.srv.lockMembers(acct.Sqid)
+ codes := make([]int, 2)
+ var wg sync.WaitGroup
+ for i := range browsers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ codes[i], _, _ = postForm(t, browsers[i], fx.ts.URL+"/invite/"+tokens[i], url.Values{"csrf": {sessionToken(t, fx, browsers[i])}})
+ }()
+ }
+ waitMemberWaiters(t, waits, 3, "both accepts to queue on the member lock")
+ unlock()
+ wg.Wait()
+ if n := memberCount(t, fx, acct.ID); n != 3 {
+ t.Fatalf("members = %d, want 3", n)
+ }
+ joined, refused := 0, -1
+ for i, c := range codes {
+ switch c {
+ case http.StatusSeeOther:
+ joined++
+ case http.StatusConflict:
+ refused = i
+ default:
+ t.Fatalf("accept %d = %d", i, c)
+ }
+ }
+ if joined != 1 || refused < 0 {
+ t.Fatalf("codes = %v, want one 303 and one 409", codes)
+ }
+ pending, err := fx.st.PendingInvites(acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(pending) != 1 || pending[0].Token != tokens[refused] {
+ t.Fatalf("pending = %+v, want the refused invite still pending", pending)
+ }
+}
+
+func TestAcceptRechecksInsideLock(t *testing.T) {
+ fx := newConsoleFixture(t)
+ browsers, tokens := acceptInvitees(t, fx, "kim@keymail.dev")
+ acct := opsAccount(t, fx)
+ waits := memberLockWaits(t, acct.Sqid)
+ unlock := fx.srv.lockMembers(acct.Sqid)
+ code := make(chan int, 1)
+ go func() {
+ c, _, _ := postForm(t, browsers[0], fx.ts.URL+"/invite/"+tokens[0], url.Values{"csrf": {sessionToken(t, fx, browsers[0])}})
+ code <- c
+ }()
+ waitMemberWaiters(t, waits, 2, "the accept to queue on the member lock")
+ // The revoke lands while the accept waits.
+ if err := fx.st.RevokeInvite(tokens[0]); err != nil {
+ t.Fatal(err)
+ }
+ unlock()
+ select {
+ case c := <-code:
+ if c != http.StatusGone {
+ t.Fatalf("accept after revoke = %d, want 410", c)
+ }
+ case <-time.After(15 * time.Second):
+ t.Fatal("accept never answered")
+ }
+ if role, _ := fx.st.Role(acct.ID, "kim@keymail.dev"); role != "" {
+ t.Fatalf("a revoked invite joined (role %q)", role)
+ }
+}
+
+func TestMemberCapAtInvite(t *testing.T) {
+ fx := newConsoleFixture(t)
+ owner := newBrowser(t)
+ signUp(t, fx, owner, "code-owner")
+ fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
+ acct := opsAccount(t, fx)
+ fillMembers(t, fx, acct.ID, 2)
+ if _, err := fx.st.CreateInvite(acct.ID, "waiting@keymail.dev", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ inviteAttempts(fx)
+ csrf := sessionToken(t, fx, owner)
+ invite := func(to string) (string, string) {
+ postForm(t, owner, fx.u("/invite"), url.Values{"csrf": {csrf}, "address": {to}})
+ return inviteFlashAfter(t, owner, fx.ts.URL)
+ }
+ applyPlan(t, fx, acct, "personal", nil, nil, planNow)
+ if kind, msg := invite("kim@keymail.dev"); kind != "err" || msg != capMessage("browser.cap.members", 3) {
+ t.Fatalf("personal, 2 members + 1 pending: flash %q %q, want err %q", kind, msg, capMessage("browser.cap.members", 3))
+ }
+ if pending, _ := fx.st.PendingInvites(acct.ID); len(pending) != 1 {
+ t.Fatalf("a refused invite was created: %+v", pending)
+ }
+ applyPlan(t, fx, acct, "community", nil, nil, planNow.Add(time.Minute))
+ if kind, msg := invite("lee@keymail.dev"); kind != "ok" {
+ t.Fatalf("community: flash %q %q, want ok", kind, msg)
+ }
+ applyPlan(t, fx, acct, "personal", nil, &plans.Limits{RunningThings: 30}, planNow.Add(2*time.Minute))
+ if kind, msg := invite("max@keymail.dev"); kind != "ok" {
+ t.Fatalf("sponsored: flash %q %q, want ok", kind, msg)
+ }
+}
+
+func TestMemberCountExcludesInvitesAndServices(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ addMembers(t, fx, acct.ID, 0, 1)
+ if _, err := fx.st.CreateInvite(acct.ID, "invited@example.com", "owner@example.com", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.NewServicePrincipal(acct.ID, "svc", "", svcrole.Publish, "owner@example.com", planNow); err != nil {
+ t.Fatal(err)
+ }
+ if n := memberCount(t, fx, acct.ID); n != 2 {
+ t.Fatalf("MemberCount = %d, want 2", n)
+ }
+}
+
+// Billing's guarded plan write compares seats too: a changed seat count is
+// a write (and a revision), an unchanged one is not.
+func TestSaveBillingSyncComparesSeats(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ save := func(seats int, now time.Time) bool {
+ t.Helper()
+ written, _, err := fx.st.SaveBillingSync(nil, acct.ID, &planChange{Plan: "community", Seats: seats, Reason: "subscription sub_1 active"}, false, nil, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return written
+ }
+ if !save(10, planNow) {
+ t.Fatal("first billing write not written")
+ }
+ rev := planRow(t, fx, acct.ID).Revision
+ if save(10, planNow.Add(time.Minute)) {
+ t.Fatal("unchanged seats written")
+ }
+ if !save(11, planNow.Add(2*time.Minute)) {
+ t.Fatal("changed seats not written")
+ }
+ if row := planRow(t, fx, acct.ID); row.Seats != 11 || row.Revision != rev+1 {
+ t.Fatalf("row after a seat change = seats %d revision %d, want 11 and %d", row.Seats, row.Revision, rev+1)
+ }
+}
diff --git a/internal/console/planthrottle_test.go b/internal/console/planthrottle_test.go
index bac62f425..2251029e3 100644
--- a/internal/console/planthrottle_test.go
+++ b/internal/console/planthrottle_test.go
@@ -46,7 +46,7 @@ func throttleFixture(t *testing.T) (*consoleFixture, *Account) {
fx := newConsoleFixture(t)
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
acct, _ := fx.st.AccountBySqid(fx.sqid)
- if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
+ if _, err := fx.st.SetAccountPlan(acct.ID, "free", nil, 0, PlanSourceOperator, nil, "r", "ops@example.com", planNow); err != nil {
t.Fatal(err)
}
return fx, acct
diff --git a/internal/console/server.go b/internal/console/server.go
index fbba22be2..72603c238 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -10,6 +10,7 @@ import (
"crypto/ed25519"
"crypto/subtle"
"crypto/x509"
+ "database/sql"
"embed"
"encoding/json"
"errors"
@@ -1205,6 +1206,9 @@ type Server struct {
// (applocks.go). Zero values are ready.
appLocks keyedLocks
acctLocks keyedLocks
+ // memberLocks is the per-account member lock (planmembers.go,
+ // lockMembers), keyed by sqid. The zero value is ready.
+ memberLocks keyedLocks
// hostLocks is withHostname's refcounted mutex per hostname
// (lifetimes.go), and lifetimeLogged the last time each hourly lifetime
// log line was written, pruned past two hours. Zero values are ready.
@@ -2675,48 +2679,74 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request) {
back("err", copyText("team.bad_address"))
return
}
+ tok, ok := s.createInviteLocked(acct, addr, to, back)
+ if !ok {
+ return
+ }
+ link := s.cfg.Origin + "/invite/" + url.PathEscape(tok)
+ subject, body := inviteMessage(addr, acct.Name, to, link, s.consoleName())
+ ctx, cancel := context.WithTimeout(r.Context(), s.inviteTimeout)
+ defer cancel()
+ switch ch, err := s.deliver(ctx, to, subject, body, s.inviteKeymailShare); {
+ case err != nil:
+ log.Printf("console: invite to %s not delivered: %v", to, err)
+ back("err", inviteFlashFailed(to, link))
+ case ch == deliveredKeymail:
+ back("ok", inviteFlashKeymail(to))
+ default:
+ back("ok", inviteFlashEmail(to))
+ }
+}
+
+// createInviteLocked admits and creates one invite under the account's
+// member lock (plans 6b): the membership check, the pending count, the
+// member cap (the pending invites plus this one) and the row, so two
+// invites at once cannot both fit under the cap. Delivery happens after,
+// outside the lock. A refusal is answered through back.
+func (s *Server) createInviteLocked(acct *Account, addr, to string, back func(kind, msg string)) (string, bool) {
+ defer s.lockMembers(acct.Sqid)()
if role, err := s.store.Role(acct.ID, to); err != nil {
back("err", "Could not check that address. Please try again.")
- return
+ return "", false
} else if role != "" {
back("err", to+" is already a member of this account.")
- return
+ return "", false
}
// Volume limits (each invite is a send as the platform): first the
// account's waiting invites, then its last hour. Both refuse before a row
// exists or any delivery is tried.
- if n, err := s.store.CountPendingInvites(acct.ID, time.Now()); err != nil {
+ n, err := s.store.CountPendingInvites(acct.ID, time.Now())
+ if err != nil {
log.Printf("console: count pending invites: %v", err)
back("err", "Could not create the invitation. Please try again.")
- return
- } else if n >= maxPendingInvites {
+ return "", false
+ }
+ if n >= maxPendingInvites {
back("err", inviteFlashTooManyPending())
- return
+ return "", false
+ }
+ if err := s.checkMemberCap(acct, n+1); err != nil {
+ var planCap *planCapError
+ if errors.As(err, &planCap) {
+ back("err", planCap.Browser())
+ return "", false
+ }
+ log.Printf("console: invite: member cap: %v", err)
+ back("err", "Could not create the invitation. Please try again.")
+ return "", false
}
if !s.inviteRate.take(acct.ID) {
back("err", inviteFlashTooManyPerHour())
- return
+ return "", false
}
tok, err := s.store.CreateInvite(acct.ID, to, addr, time.Now())
if err != nil {
s.inviteRate.giveBack(acct.ID)
log.Printf("console: create invite: %v", err)
back("err", "Could not create the invitation. Please try again.")
- return
- }
- link := s.cfg.Origin + "/invite/" + url.PathEscape(tok)
- subject, body := inviteMessage(addr, acct.Name, to, link, s.consoleName())
- ctx, cancel := context.WithTimeout(r.Context(), s.inviteTimeout)
- defer cancel()
- switch ch, err := s.deliver(ctx, to, subject, body, s.inviteKeymailShare); {
- case err != nil:
- log.Printf("console: invite to %s not delivered: %v", to, err)
- back("err", inviteFlashFailed(to, link))
- case ch == deliveredKeymail:
- back("ok", inviteFlashKeymail(to))
- default:
- back("ok", inviteFlashEmail(to))
+ return "", false
}
+ return tok, true
}
// inviteMessage is the subject and body for an invitation, whichever channel
@@ -2809,6 +2839,10 @@ func (s *Server) handleRevokeInvite(w http.ResponseWriter, r *http.Request) {
return
}
tok := r.FormValue("token")
+ // Under the member lock (plans 6b), so a revoke and an accept of the
+ // same invite are one after the other: the accept re-checks the invite
+ // inside the lock.
+ defer s.lockMembers(acct.Sqid)()
// Scoped to THIS account: an owner of one account must not be able to
// revoke another account's invite by pasting its token.
pending, err := s.store.PendingInvites(acct.ID)
@@ -2904,17 +2938,22 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
+ token := r.PathValue("token")
now := time.Now()
- accountID, err := s.store.AcceptInvite(r.PathValue("token"), addr, now)
+ inv, err := s.store.PendingInviteFor(token, addr, now)
if err != nil {
s.invitationGone(w, r)
return
}
- a, err := s.store.AccountByID(accountID)
+ a, err := s.store.AccountByID(inv.AccountID)
if err != nil || a == nil {
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Joined, but could not open the account. Try the front page.")
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitation. Try again.")
+ return
+ }
+ if !s.acceptInviteLocked(w, r, a, token, addr, now) {
return
}
+ accountID := a.ID
if err := s.store.SetLastAccount(addr, accountID); err != nil {
log.Printf("console: set last account: %v", err)
}
@@ -2922,6 +2961,48 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+url.PathEscape(a.Sqid)+"/", http.StatusSeeOther)
}
+// acceptInviteLocked joins addr to a under the account's member lock
+// (plans 6b): inside it the invite is checked again (a revoke may have
+// landed while this waited), and a person not yet a member must fit under
+// the plan's member cap. The join goes through the membership transition,
+// so a team account's limits follow at once. A refusal leaves the invite
+// pending and is answered here.
+func (s *Server) acceptInviteLocked(w http.ResponseWriter, r *http.Request, a *Account, token, addr string, now time.Time) bool {
+ defer s.lockMembers(a.Sqid)()
+ inv, err := s.store.PendingInviteFor(token, addr, now)
+ if err != nil || inv.AccountID != a.ID {
+ s.invitationGone(w, r)
+ return false
+ }
+ role, err := s.store.Role(a.ID, addr)
+ if err != nil {
+ log.Printf("console: accept invite: role: %v", err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitation. Try again.")
+ return false
+ }
+ if role == "" {
+ if err := s.checkMemberCap(a, 1); err != nil {
+ if isPlanCap(err) {
+ s.renderMessage(w, r, http.StatusConflict, "Refused", capMessage("browser.cap.members_join"))
+ return false
+ }
+ log.Printf("console: accept invite: member cap: %v", err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read the invitation. Try again.")
+ return false
+ }
+ }
+ err = s.membershipTransition(r.Context(), a, now, func(tx *sql.Tx) error {
+ _, err := acceptInviteTx(tx, token, addr, now)
+ return err
+ })
+ if err != nil {
+ log.Printf("console: accept invite: %v", err)
+ s.invitationGone(w, r)
+ return false
+ }
+ return true
+}
+
// handleContinue is the front page's one form (spec 4): it finds the door
// from the address alone. A Keymail address goes to Keymail's sign-in; any
// other gets an emailed link and code. Every email-bound outcome renders the
diff --git a/internal/console/store.go b/internal/console/store.go
index 0ec22d727..e8693c6f9 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -617,10 +617,25 @@ func (s *Store) migrate() error {
if err := s.migratePlanLapse(); err != nil {
return err
}
+ // Plans 6b's seat count on the plan row (planmembers.go).
+ if err := s.migratePlanSeats(); err != nil {
+ return err
+ }
// Plans 6a's billing state (billingstore.go), for the same reason.
return s.migrateBilling()
}
+// migratePlanSeats adds account_plans.seats (plans 6b): the paid seat count
+// billing wrote, 0 for "count the members now". Guarded like the ALTER
+// list above: a second start finds the column and carries on.
+func (s *Store) migratePlanSeats() error {
+ _, err := s.db.Exec(`ALTER TABLE account_plans ADD COLUMN seats INTEGER NOT NULL DEFAULT 0;`)
+ if err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
+ return nil
+}
+
// mailCountsBackfillVersion is the user_version this migration stamps. The
// next migration that needs a one-shot marker takes 2 and reads this
// constant rather than the literal.
@@ -1353,26 +1368,33 @@ ORDER BY CASE role WHEN 'owner' THEN 0 ELSE 1 END, address`, accountID)
// the same reason removing them is: it leaves an account nobody can
// administer. Transfer ownership first.
func (s *Store) AddMember(accountID int64, address, role string, now time.Time) error {
- if role != RoleOwner && role != RoleMember {
- return fmt.Errorf("console: invalid role %q", role)
- }
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
+ if err := addMemberTx(tx, accountID, address, role, now); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// addMemberTx is AddMember inside the caller's transaction (a
+// MembershipTransition write). It never commits.
+func addMemberTx(tx *sql.Tx, accountID int64, address, role string, now time.Time) error {
+ if role != RoleOwner && role != RoleMember {
+ return fmt.Errorf("console: invalid role %q", role)
+ }
if role != RoleOwner {
if err := lastOwnerGuard(tx, accountID, address); err != nil {
return err
}
}
- if _, err := tx.Exec(`INSERT INTO memberships (account_id, address, role, added_at)
+ _, err := tx.Exec(`INSERT INTO memberships (account_id, address, role, added_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(account_id, address) DO UPDATE SET role = excluded.role`,
- accountID, address, role, now.Unix()); err != nil {
- return err
- }
- return tx.Commit()
+ accountID, address, role, now.Unix())
+ return err
}
// RemoveMember drops a membership, refusing to remove the last owner.
@@ -1382,14 +1404,33 @@ func (s *Store) RemoveMember(accountID int64, address string) error {
return err
}
defer tx.Rollback()
- if err := lastOwnerGuard(tx, accountID, address); err != nil {
+ if err := removeMemberTx(tx, accountID, address); err != nil {
return err
}
- if _, err := tx.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`,
- accountID, address); err != nil {
+ return tx.Commit()
+}
+
+// removeMemberTx is RemoveMember inside the caller's transaction (a
+// MembershipTransition write). It never commits.
+func removeMemberTx(tx *sql.Tx, accountID int64, address string) error {
+ if err := lastOwnerGuard(tx, accountID, address); err != nil {
return err
}
- return tx.Commit()
+ _, err := tx.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`,
+ accountID, address)
+ return err
+}
+
+// AddMemberWrite is addMemberTx as a MembershipTransition write, for the
+// box-side membership tool (cmd/console).
+func AddMemberWrite(accountID int64, address, role string, now time.Time) func(*sql.Tx) error {
+ return func(tx *sql.Tx) error { return addMemberTx(tx, accountID, address, role, now) }
+}
+
+// RemoveMemberWrite is removeMemberTx as a MembershipTransition write, for
+// the box-side membership tool (cmd/console).
+func RemoveMemberWrite(accountID int64, address string) func(*sql.Tx) error {
+ return func(tx *sql.Tx) error { return removeMemberTx(tx, accountID, address) }
}
// lastOwnerGuard refuses a change that would leave an account with no owner.
@@ -1504,9 +1545,22 @@ func (s *Store) AcceptInvite(token, address string, now time.Time) (int64, error
return 0, err
}
defer tx.Rollback()
+ accountID, err := acceptInviteTx(tx, token, address, now)
+ if err != nil {
+ return 0, err
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ return accountID, nil
+}
+
+// acceptInviteTx is AcceptInvite inside the caller's transaction (a
+// MembershipTransition write), with the same three gates. It never commits.
+func acceptInviteTx(tx *sql.Tx, token, address string, now time.Time) (int64, error) {
var accountID, expires, accepted int64
var want string
- err = tx.QueryRow(`SELECT account_id, address, expires_at, accepted_at FROM invites WHERE token = ?`,
+ err := tx.QueryRow(`SELECT account_id, address, expires_at, accepted_at FROM invites WHERE token = ?`,
token).Scan(&accountID, &want, &expires, &accepted)
if err == sql.ErrNoRows {
return 0, fmt.Errorf("console: no such invite")
@@ -1532,9 +1586,6 @@ VALUES (?, ?, ?, ?) ON CONFLICT(account_id, address) DO NOTHING`,
accountID, address, RoleMember, now.Unix()); err != nil {
return 0, err
}
- if err := tx.Commit(); err != nil {
- return 0, err
- }
return accountID, nil
}