| new file mode 100644 |
| index 000000000..07386f7dd |
| --- /dev/null |
| +++ b/internal/console/hacreatecapacity_test.go |
| @@ -0,0 +1,955 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "html" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/hostops" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const capacityUnknownIE = "Capacity evidence for ie is incomplete. Nothing was created. Try again in 60 seconds." |
| +const capacityPoolIE = "Capacity for pool %s in ie could not be checked. No box confirmed room, and at least one box does not report which pools it serves. Nothing was created. A box serving this pool must report its pool membership before this create can proceed." |
| + |
| +// Use the publisher's golden body, real signed identity and status parsers. |
| +func createCapacityEvidence(t *testing.T, s *Server, evidence string, edit func(map[string]any), regions ...string) *haObserver { |
| + t.Helper() |
| + o, store, _ := haFixture(t) |
| + target := "ie" |
| + if len(regions) > 0 { |
| + target = regions[0] |
| + raw := strings.ReplaceAll(haTestConfig, `"ie"`, fmt.Sprintf("%q", target)) |
| + c, err := parseHACapacityConfig(raw, []string{target, "de"}, "ie") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + o.config = c |
| + } |
| + now := time.Now().UTC() |
| + haPut(t, store, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { |
| + m["generation"] = now.Format(time.RFC3339Nano) |
| + m["serves_shared_pool"] = true |
| + if target != "ie" { |
| + m["placement"] = target |
| + } |
| + if evidence == "zero" { |
| + m["admitted"] = false |
| + } |
| + if evidence == "unknown" { |
| + delete(m, "admitted") |
| + } |
| + if edit != nil { |
| + edit(m) |
| + } |
| + })) |
| + haPut(t, store, "status/boxes/leo.json", []byte(fmt.Sprintf(`{"label":"leo","generated_at":%q,"metrics":{"instance_id":"i-0123456789abcdef0"}}`, now.Format(time.RFC3339Nano)))) |
| + o.current.Store(o.observe(context.Background(), now)) |
| + s.haCapacity.Store(o) |
| + return o |
| +} |
| + |
| +type capacityDoorFixture struct { |
| + fx *consoleFixture |
| + token string |
| + browser *http.Client |
| + csrf string |
| + claims *claimCase |
| +} |
| + |
| +func capacityFixture(t *testing.T, mode string) capacityDoorFixture { |
| + t.Helper() |
| + var clock *lifetimesClock |
| + if mode == "lifetimes" { |
| + clock = useLifetimesClock(t) |
| + } |
| + var f capacityDoorFixture |
| + if mode == "claims" { |
| + cx := newClaimCaseWith(t, func(c *Config) { c.HomeRegion = "ie" }) |
| + f = capacityDoorFixture{cx.consoleFixture, cx.bearer, cx.browser, cx.csrf, cx} |
| + } else { |
| + fx := newConsoleFixture(t) |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + browser := newBrowser(t) |
| + signUp(t, fx, browser, "capacity-"+claimSafeName(t.Name())) |
| + f = capacityDoorFixture{fx: fx, token: cliToken(t, fx, "paul@keymail.dev", "capacity-token"), browser: browser, csrf: sessionToken(t, fx, browser)} |
| + if mode == "lifetimes" { |
| + turnLifetimesOn(t, fx.srv, clock) |
| + } |
| + } |
| + if err := f.fx.st.SetOperator("paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.fx.srv.cfg.HomeRegion = "ie" |
| + f.fx.srv.cfg.HARegions = []string{"ie"} |
| + f.fx.srv.cfg.SeedData = release.NewDirStore(t.TempDir()) |
| + f.fx.srv.cfg.HibernateBucket = "test-data" |
| + root := t.TempDir() |
| + f.fx.srv.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) { |
| + return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil |
| + } |
| + m := titoManifest() |
| + m.Pool = "" |
| + m.Regions = nil |
| + enableInstances(t, f.fx, "titogo", m) |
| + sm := titoSidecarManifest() |
| + sm.Pool = "" |
| + sm.Regions = nil |
| + enableSidecars(t, f.fx, "titogo", sm) |
| + shipVersion(t, f.fx, "titogo", "v1") |
| + seedChannel(t, f.fx, "titogo", "edge", "v1") |
| + return f |
| +} |
| + |
| +func (f capacityDoorFixture) request(t *testing.T, door string) (int, http.Header, string) { |
| + t.Helper() |
| + path, body := "/api/cli/apps/bab/titogo/instances", `{"host":"capacity.go.tito.io","kind":"static"}` |
| + switch door { |
| + case "binary": |
| + body = `{"host":"capacity.go.tito.io"}` |
| + case "address": |
| + body = `{"host":"capacity.go.tito.io","addrs":["127.0.0.1:8080"]}` |
| + case "sidecar": |
| + path, body = "/api/cli/apps/bab/titogo/sidecars", `{"name":"capacity"}` |
| + case "domain", "browser": |
| + path, body = "/api/cli/apps/bab/titogo/domains", `{"host":"capacity.example.com","kind":"static","channel":"edge"}` |
| + } |
| + if door != "browser" { |
| + return rawReq(t, http.MethodPost, f.fx.ts.URL+path, f.token, body) |
| + } |
| + req, err := http.NewRequest(http.MethodPost, f.fx.ts.URL+"/a/bab/apps/titogo/domains/attach", strings.NewReader(url.Values{"csrf": {f.csrf}, "host": {"capacity.example.com"}, "kind": {"static"}, "channel": {"edge"}}.Encode())) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + resp, err := f.browser.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp.StatusCode, resp.Header, html.UnescapeString(string(b)) |
| +} |
| + |
| +func TestHACreateCapacityDoors(t *testing.T) { |
| + for _, mode := range []string{"plain", "lifetimes", "claims"} { |
| + for _, door := range []string{"instance", "binary", "address", "sidecar", "domain", "browser"} { |
| + for _, evidence := range []string{"allow", "zero", "unknown"} { |
| + t.Run(mode+"/"+door+"/"+evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, mode) |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + data := &haCreateStore{Store: f.fx.srv.cfg.SeedData} |
| + f.fx.srv.cfg.Releases, f.fx.srv.cfg.SeedData = control, data |
| + local := capacityLocalWrites(t, f.fx) |
| + mark := 0 |
| + if f.claims != nil { |
| + mark = f.claims.rec.mark() |
| + } |
| + before := bucketState(t, f.fx.rel) |
| + code, hdr, body := f.request(t, door) |
| + if evidence == "allow" { |
| + if code < 200 || code >= 400 { |
| + t.Fatalf("allow: %d %s", code, body) |
| + } |
| + if door == "sidecar" { |
| + rec, err := provision.GetSidecarRecord(context.Background(), f.fx.rel, "bab", "titogo", "capacity") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := json.Marshal(rec) |
| + if strings.Contains(string(b), `"ha":true`) { |
| + t.Fatal("sidecar stamped HA") |
| + } |
| + } |
| + return |
| + } |
| + want := capacityUnknownIE |
| + if evidence == "zero" { |
| + want = noCapacityRefusal("ie") |
| + } |
| + if code != 503 || hdr.Get("Retry-After") != "60" || !strings.Contains(body, want) { |
| + t.Fatalf("%d Retry-After=%q %s; want %q", code, hdr.Get("Retry-After"), body, want) |
| + } |
| + haCreateNoWrites(t, control, data) |
| + if f.claims != nil { |
| + wroteNothing(t, f.claims, mark) |
| + } |
| + local() |
| + if after := bucketState(t, f.fx.rel); !reflect.DeepEqual(before, after) { |
| + t.Fatal("refusal changed bucket") |
| + } |
| + if evidence == "zero" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// SQLite triggers count attempts even if a later statement restores the row. |
| +// Authentication bookkeeping is outside the protected create state. |
| +func capacityLocalWrites(t *testing.T, fx *consoleFixture) func() { |
| + t.Helper() |
| + install := func(db sqlHandle, tables []string) func() int { |
| + if _, err := db.Exec(`CREATE TABLE capacity_write_probe (event TEXT)`); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, table := range tables { |
| + for _, verb := range []string{"INSERT", "UPDATE", "DELETE"} { |
| + q := fmt.Sprintf(`CREATE TRIGGER "capacity_%s_%s" AFTER %s ON "%s" BEGIN INSERT INTO capacity_write_probe VALUES ('%s %s'); END`, table, verb, verb, table, verb, table) |
| + if _, err := db.Exec(q); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + return func() int { |
| + var n int |
| + if err := db.QueryRow(`SELECT COUNT(*) FROM capacity_write_probe`).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| + } |
| + } |
| + localDB := fx.st.rawPool |
| + if fx.st.gate != nil { |
| + var err error |
| + localDB, err = sql.Open("sqlite", fx.st.gate.path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { localDB.Close() }) |
| + } |
| + local := install(localDB, []string{"audit", "apps", "host_allocations", "record_retirements", "record_migrations"}) |
| + reg, err := sql.Open("sqlite", fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + rows, err := reg.Query(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var tables []string |
| + for rows.Next() { |
| + var name string |
| + if err := rows.Scan(&name); err != nil { |
| + t.Fatal(err) |
| + } |
| + tables = append(tables, name) |
| + } |
| + if err := rows.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + registry := install(reg, tables) |
| + return func() { |
| + t.Helper() |
| + if a, b := local(), registry(); a != 0 || b != 0 { |
| + t.Fatalf("local writes: console=%d registry=%d", a, b) |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateCapacityNamedPools(t *testing.T) { |
| + for _, door := range []string{"instance", "sidecar"} { |
| + for _, pool := range []string{"hapair", "cohort1"} { |
| + for _, scenario := range []string{"new", "old", "null", "mixed-positive", "mixed-missing", "absent-membership", "closed-inbound", "malformed"} { |
| + t.Run(door+"/"+pool+"/"+scenario, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "plain") |
| + m := titoManifest() |
| + m.Pool = pool |
| + m.Regions = nil |
| + enableInstances(t, f.fx, "titogo", m) |
| + sm := titoSidecarManifest() |
| + sm.Pool = pool |
| + sm.Regions = nil |
| + enableSidecars(t, f.fx, "titogo", sm) |
| + o := createCapacityEvidence(t, f.fx.srv, "allow", func(m map[string]any) { |
| + switch scenario { |
| + case "old": |
| + delete(m, "named_pools") |
| + case "mixed-missing": |
| + m["named_pools"] = []string{"other"} |
| + case "null": |
| + m["named_pools"] = nil |
| + case "absent-membership": |
| + m["named_pools"] = []string{"other"} |
| + case "closed-inbound": |
| + m["accepts_inbound"] = false |
| + case "malformed": |
| + m["named_pools"] = 17 |
| + } |
| + }) |
| + if strings.HasPrefix(scenario, "mixed-") { |
| + // An otherwise eligible older publisher shares the same trust checks. |
| + c := *o.config |
| + c.FixedBoxes = make(map[string]haFixedBox) |
| + for k, v := range o.config.FixedBoxes { |
| + c.FixedBoxes[k] = v |
| + } |
| + c.FixedBoxes["sophie"] = haFixedBox{RegionCode: "ie", InstanceID: "i-0123456789abcdef1"} |
| + o.config = &c |
| + signer := boxidtest.NewSigner(t) |
| + o.verifier.Certs = signer.Certs() |
| + for _, pair := range []struct{ ref, iid string }{{"leo", "i-0123456789abcdef0"}, {"sophie", "i-0123456789abcdef1"}} { |
| + rec, _ := signer.Record(t, pair.ref, moveTestAccount, "eu-west-1", pair.iid) |
| + b, _ := json.Marshal(rec) |
| + haPut(t, o.store.(*haCapacityStore).Store, boxid.Key(pair.ref), b) |
| + } |
| + now := time.Now().UTC() |
| + haPut(t, o.store, "control/edges/sophie.json", haEdit(t, haGolden(t), func(m map[string]any) { |
| + m["box"] = "sophie" |
| + m["box_id"] = "sophie" |
| + m["generation"] = now.Format(time.RFC3339Nano) |
| + delete(m, "named_pools") |
| + })) |
| + haPut(t, o.store, "status/boxes/sophie.json", []byte(fmt.Sprintf(`{"label":"sophie","generated_at":%q,"metrics":{"instance_id":"i-0123456789abcdef1"}}`, now.Format(time.RFC3339Nano)))) |
| + o.current.Store(o.observe(context.Background(), now)) |
| + } |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + f.fx.srv.cfg.Releases = control |
| + local := capacityLocalWrites(t, f.fx) |
| + code, hdr, body := f.request(t, door) |
| + switch scenario { |
| + case "new", "mixed-positive": |
| + if code != 201 { |
| + t.Fatalf("positive: %d %s", code, body) |
| + } |
| + default: |
| + want := noCapacityRefusal("ie") |
| + if scenario == "old" || scenario == "null" || scenario == "mixed-missing" { |
| + want = fmt.Sprintf(capacityPoolIE, pool) |
| + } |
| + if scenario == "malformed" { |
| + want = capacityUnknownIE |
| + } |
| + if code != 503 || hdr.Get("Retry-After") != "60" || errorText(body) != want { |
| + t.Fatalf("%d %s %s", code, hdr.Get("Retry-After"), body) |
| + } |
| + if n, _ := control.counts(); n != 0 { |
| + t.Fatalf("writes=%d", n) |
| + } |
| + local() |
| + if scenario == "absent-membership" || scenario == "closed-inbound" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + } |
| + pub := &capacityRecorder{} |
| + _ = f.fx.srv.publishCapacity(context.Background(), pub) |
| + for _, v := range pub.got { |
| + if v.Placement == "ie" && v.Eligible == 0 { |
| + t.Fatal("pool evidence produced regional zero") |
| + } |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateCapacityBeforeSeedAndPrivateStorage(t *testing.T) { |
| + for _, lifetimes := range []bool{false, true} { |
| + for _, seeded := range []bool{false, true} { |
| + for _, evidence := range []string{"allow", "zero", "unknown"} { |
| + t.Run(fmt.Sprintf("lifetimes=%v/from=%v/%s", lifetimes, seeded, evidence), func(t *testing.T) { |
| + pages := pagesTo(t) |
| + clock := useLifetimesClock(t) |
| + f := newFromFixture(t, 1) |
| + if lifetimes { |
| + turnLifetimesOn(t, f.fx.srv, clock) |
| + } |
| + f.fx.srv.cfg.HomeRegion = "ie" |
| + f.fx.srv.cfg.HARegions = []string{"ie"} |
| + enableInstances(t, f.fx, "shop", fromManifest(true)) |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + var adapterCalls atomic.Int64 |
| + adapter, err := NewStoreProvisionerBoundary(f.fake, func(context.Context, hostops.MutationTarget) error { adapterCalls.Add(1); return nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.fx.srv.cfg.StoreProvisioner = adapter |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + data := &haCreateStore{Store: f.fx.srv.cfg.SeedData} |
| + f.fx.srv.cfg.Releases, f.fx.srv.cfg.SeedData = control, data |
| + local := capacityLocalWrites(t, f.fx) |
| + before := bucketState(t, f.fx.rel) |
| + body := `{"host":"` + fromHost + `"}` |
| + if seeded { |
| + body = `{"host":"` + fromHost + `","from":{"host":"` + fromSource + `"}}` |
| + } |
| + code, hdr, out := rawReq(t, http.MethodPost, f.url, f.token, body) |
| + f.fx.srv.seedCopies.Wait() |
| + if evidence == "allow" { |
| + want := 201 |
| + if seeded { |
| + want = 202 |
| + } |
| + if code != want { |
| + t.Fatalf("allow=%d %s", code, out) |
| + } |
| + if adapterCalls.Load() == 0 { |
| + t.Fatal("positive control never reached storage adapter") |
| + } |
| + return |
| + } |
| + want := capacityUnknownIE |
| + if evidence == "zero" { |
| + want = noCapacityRefusal("ie") |
| + } |
| + if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != want { |
| + t.Fatalf("%d %v %s", code, hdr, out) |
| + } |
| + haCreateNoWrites(t, control, data) |
| + local() |
| + if adapterCalls.Load() != 0 { |
| + t.Fatal("refusal reached storage adapter") |
| + } |
| + if !reflect.DeepEqual(before, bucketState(t, f.fx.rel)) { |
| + t.Fatal("refusal changed stored state") |
| + } |
| + if evidence == "zero" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateCapacityResidentRootfs(t *testing.T) { |
| + for _, evidence := range []string{"allow", "zero", "unknown"} { |
| + t.Run(evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + fx, token := unplacedRootfsApp(t) |
| + fx.srv.cfg.DeploymentSingleTenant = true |
| + fx.srv.cfg.HomeRegion = "ie" |
| + fx.srv.cfg.HARegions = []string{"ie"} |
| + writeFleetBox(t, fx, "", "box-1", "ie", true, time.Now()) |
| + createCapacityEvidence(t, fx.srv, evidence, nil) |
| + control := &haCreateStore{Store: fx.srv.cfg.Releases} |
| + fx.srv.cfg.Releases = control |
| + local := capacityLocalWrites(t, fx) |
| + code, hdr, out := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "shop"), token, `{"host":"shop.example.com"}`) |
| + if evidence == "allow" { |
| + if code != 201 { |
| + t.Fatalf("%d %s", code, out) |
| + } |
| + rec, _ := storedShop(t, fx, rootfsShopHost) |
| + if rec.Runtime != provision.RuntimeRootfsV1 || rec.HA { |
| + t.Fatalf("record=%+v", rec) |
| + } |
| + return |
| + } |
| + want := capacityUnknownIE |
| + if evidence == "zero" { |
| + want = noCapacityRefusal("ie") |
| + } |
| + if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != want { |
| + t.Fatalf("%d %v %s", code, hdr, out) |
| + } |
| + if n, _ := control.counts(); n != 0 { |
| + t.Fatalf("writes=%d", n) |
| + } |
| + local() |
| + if evidence == "zero" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type createCapacityReads struct { |
| + release.Store |
| + metadata haMetadataLister |
| + reads atomic.Int64 |
| +} |
| + |
| +func (s *createCapacityReads) Get(ctx context.Context, k string) ([]byte, string, error) { |
| + s.reads.Add(1) |
| + return s.Store.Get(ctx, k) |
| +} |
| +func (s *createCapacityReads) ListPage(ctx context.Context, p, a string, n int) ([]string, error) { |
| + s.reads.Add(1) |
| + return s.Store.(release.PageLister).ListPage(ctx, p, a, n) |
| +} |
| +func (s *createCapacityReads) haListStatus(ctx context.Context) ([]haObject, bool, error) { |
| + s.reads.Add(1) |
| + return s.metadata.haListStatus(ctx) |
| +} |
| + |
| +func TestHACreateCapacitySharesObservation(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "plain") |
| + o, st, _ := haFixture(t) |
| + haPut(t, st, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { m["admitted"] = false })) |
| + counted := &createCapacityReads{Store: o.store, metadata: o.store.(haMetadataLister)} |
| + o.store = counted |
| + o.clock = newHATestClock() |
| + f.fx.srv.haCapacity.Store(o) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := o.start(ctx) |
| + defer func() { cancel(); haAwait(t, done) }() |
| + haAwait(t, o.ready) |
| + before := counted.reads.Load() |
| + obs, _ := f.fx.srv.HACapacity() |
| + if before != 5 { |
| + t.Fatalf("observation reads=%d, want 2 LIST + 3 GET", before) |
| + } |
| + transport := hap2S3(t, f.fx) |
| + var wg sync.WaitGroup |
| + for _, door := range []string{"instance", "sidecar", "domain"} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + code, hdr, body := f.request(t, door) |
| + if code != 503 || hdr.Get("Retry-After") != "60" || errorText(body) != noCapacityRefusal("ie") { |
| + t.Errorf("%s: %d %s", door, code, body) |
| + } |
| + }() |
| + } |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + pub := &capacityRecorder{} |
| + if err := f.fx.srv.publishCapacity(context.Background(), pub); err != nil { |
| + t.Error(err) |
| + } |
| + }() |
| + wg.Wait() |
| + after, _ := f.fx.srv.HACapacity() |
| + if counted.reads.Load() != before || after != obs { |
| + t.Fatal("requests refreshed the shared observation") |
| + } |
| + // Existing validation across these doors lists edges and status twice. |
| + // Capacity adds no reads through either the observation or request client. |
| + evidenceLists := map[string]int{} |
| + for _, attempt := range transport.all() { |
| + for _, prefix := range []string{"control/edges/", "control/boxes/", "status/boxes/"} { |
| + if attempt.query.Get("prefix") == prefix { |
| + evidenceLists[prefix]++ |
| + } |
| + if strings.HasPrefix(attempt.key, prefix) { |
| + t.Errorf("request loaded capacity evidence body: %+v", attempt) |
| + } |
| + } |
| + } |
| + if !reflect.DeepEqual(evidenceLists, map[string]int{"control/edges/": 2, "status/boxes/": 2}) { |
| + t.Fatalf("evidence LISTs=%v, want existing validation's two per prefix", evidenceLists) |
| + } |
| + transport.noWrites(t) |
| + expectPages(t, pages, noRoomSubject("ie")) |
| +} |
| + |
| +func TestHACreateCapacityPageThrottle(t *testing.T) { |
| + f := capacityFixture(t, "plain") |
| + createCapacityEvidence(t, f.fx.srv, "zero", nil) |
| + old := pageNoCapacity |
| + var calls atomic.Int64 |
| + entered := make(chan struct{}, 4) |
| + releaseSend := make(chan struct{}) |
| + var releaseOnce sync.Once |
| + release := func() { releaseOnce.Do(func() { close(releaseSend) }) } |
| + defer release() |
| + pageNoCapacity = func(context.Context, string, string, string) error { |
| + n := calls.Add(1) |
| + entered <- struct{}{} |
| + if n == 1 { |
| + <-releaseSend |
| + return errors.New("test send failure") |
| + } |
| + return nil |
| + } |
| + defer func() { pageNoCapacity = old }() |
| + request := func() { |
| + code, _, body := f.request(t, "instance") |
| + if code != 503 { |
| + t.Errorf("%d %s", code, body) |
| + } |
| + } |
| + request() |
| + haAwait(t, entered) |
| + var wg sync.WaitGroup |
| + for range 8 { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); request() }() |
| + } |
| + wg.Wait() |
| + if calls.Load() != 1 { |
| + t.Fatal("concurrent refusals sent extra pages") |
| + } |
| + release() |
| + haWait(t, func() bool { |
| + f.fx.srv.noCapacity.mu.Lock() |
| + defer f.fx.srv.noCapacity.mu.Unlock() |
| + return len(f.fx.srv.noCapacity.last) == 0 |
| + }) |
| + request() |
| + haAwait(t, entered) |
| + for range 3 { |
| + request() |
| + } |
| + if calls.Load() != 2 { |
| + t.Fatal("successful send did not suppress repeats") |
| + } |
| + // A fresh server is a process restart: the hourly reservation is in memory. |
| + restarted, err := NewServer(f.fx.srv.cfg, f.fx.st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + restarted.dbReplica = f.fx.srv.dbReplica |
| + restarted.haCapacity.Store(f.fx.srv.haCapacity.Load()) |
| + req := httptest.NewRequest(http.MethodPost, "/api/cli/apps/bab/titogo/instances", strings.NewReader(`{"host":"capacity.go.tito.io","kind":"static"}`)) |
| + req.Header.Set("Authorization", "Bearer "+f.token) |
| + req.Header.Set("Content-Type", "application/json") |
| + w := httptest.NewRecorder() |
| + restarted.ServeHTTP(w, req) |
| + if w.Code != 503 { |
| + t.Fatalf("restart: %d %s", w.Code, w.Body) |
| + } |
| + haAwait(t, entered) |
| + if calls.Load() != 3 { |
| + t.Fatalf("restart sends=%d", calls.Load()) |
| + } |
| +} |
| + |
| +func TestHACapacityDoesNotGateExistingWake(t *testing.T) { |
| + for _, evidence := range []string{"zero", "unknown"} { |
| + t.Run(evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + fx := newConsoleFixture(t) |
| + const host = "web.kass.carlosapp.dev" |
| + sibling(t, fx, "kass", host, "edge") |
| + markHA(t, fx.rel, "bab", "kass", host) |
| + token := cliToken(t, fx, "paul@keymail.dev", "capacity-existing") |
| + fx.srv.cfg.AppsDomain = "carlosapp.dev" |
| + fx.srv.cfg.HomeRegion = "ie" |
| + fx.srv.cfg.HARegions = []string{"ie"} |
| + createCapacityEvidence(t, fx.srv, evidence, nil) |
| + writeHeldBox(t, fx, host, "kass", "v2") |
| + for _, door := range []struct{ name, method, path, body string }{ |
| + {"enable", http.MethodPut, "/instances-manifest", `{}`}, |
| + {"restart", http.MethodPost, "/restart", `{}`}, |
| + {"deploy promote", http.MethodPost, "/promote", `{"channel":"edge","version":"v2","hotfix":true}`}, |
| + {"retry", http.MethodPost, "/instances/" + host + "/retry", `{}`}, |
| + {"alias", http.MethodPost, "/domains", `{"host":"capacity-alias.example.com"}`}, |
| + } { |
| + code, _, out := rawReq(t, door.method, fx.ts.URL+"/api/cli/apps/bab/kass"+door.path, token, door.body) |
| + if code < 200 || code >= 300 { |
| + t.Fatalf("%s: %d %s", door.name, code, out) |
| + } |
| + } |
| + expectPages(t, pages) |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateCapacityPrecedence(t *testing.T) { |
| + for _, evidence := range []string{"zero", "unknown"} { |
| + for _, scenario := range []string{"auth", "duplicate-instance", "duplicate-sidecar", "shape", "invalid-channel", "import", "pooled-data", "nonhome-data", "nonhome-static", "app-home", "explicit-home", "outside-ha"} { |
| + t.Run(evidence+"/"+scenario, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "plain") |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + f.fx.srv.cfg.HARegions = []string{"ie", "de"} |
| + path, body, token := "/api/cli/apps/bab/titogo/instances", `{"host":"capacity.go.tito.io","kind":"static"}`, f.token |
| + want := 503 |
| + switch scenario { |
| + case "auth": |
| + token = cliToken(t, f.fx, "stranger@example.com", "capacity-stranger") |
| + want = 404 |
| + case "duplicate-instance": |
| + haPut(t, f.fx.rel, provision.RecordKey("bab", "titogo", "capacity.go.tito.io"), []byte(`{"schema":1,"host":"capacity.go.tito.io","app":"titogo","account":"bab","channel":"stable","kind":"static","created_at":"2026-11-01T00:00:00Z"}`)) |
| + want = 409 |
| + case "duplicate-sidecar": |
| + rec := provision.SidecarRecord{Schema: 1, Name: "capacity", Host: provision.SidecarHost("capacity", "titogo", "bab"), Account: "bab", App: "titogo", Channel: "stable", CreatedAt: time.Now().UTC()} |
| + if err := provision.CreateSidecarRecord(context.Background(), f.fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + path, body = "/api/cli/apps/bab/titogo/sidecars", `{"name":"capacity"}` |
| + want = 409 |
| + case "shape": |
| + body = `{"host":"capacity.go.tito.io","region":"de","kind":"not-a-kind"}` |
| + want = 400 |
| + case "invalid-channel": |
| + body = `{"host":"capacity.go.tito.io","region":"de","kind":"static","channel":"!"}` |
| + want = 400 |
| + case "import": |
| + body = `{"host":"capacity.go.tito.io","import":{}}` |
| + want = 409 |
| + case "pooled-data": |
| + m := titoManifest() |
| + m.Pool = "hapair" |
| + m.Regions = nil |
| + enableInstances(t, f.fx, "titogo", m) |
| + body = `{"host":"capacity.go.tito.io"}` |
| + want = 409 |
| + case "nonhome-data": |
| + body = `{"host":"capacity.go.tito.io","region":"de"}` |
| + want = 409 |
| + case "nonhome-static": |
| + body = `{"host":"capacity.go.tito.io","region":"de","kind":"static"}` |
| + case "app-home": |
| + body = `{"host":"capacity.go.tito.io"}` |
| + f.fx.srv.appRegionOf = func(int64, string) (string, string, error) { return "ie", "app", nil } |
| + case "explicit-home": |
| + body = `{"host":"capacity.go.tito.io","region":"ie","kind":"static"}` |
| + case "outside-ha": |
| + f.fx.srv.cfg.HARegions = []string{"de"} |
| + want = 201 |
| + } |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + data := &haCreateStore{Store: f.fx.srv.cfg.SeedData} |
| + f.fx.srv.cfg.Releases, f.fx.srv.cfg.SeedData = control, data |
| + local := capacityLocalWrites(t, f.fx) |
| + code, hdr, out := rawReq(t, http.MethodPost, f.fx.ts.URL+path, token, body) |
| + if code != want { |
| + t.Fatalf("%d %s, want %d", code, out, want) |
| + } |
| + if code == 201 { |
| + return |
| + } |
| + haCreateNoWrites(t, control, data) |
| + local() |
| + if want != 503 { |
| + if hdr.Get("Retry-After") != "" || strings.Contains(out, "Nothing was created.") { |
| + t.Fatalf("capacity masked validation: %v %s", hdr, out) |
| + } |
| + expectPages(t, pages) |
| + return |
| + } |
| + region := "ie" |
| + if scenario == "nonhome-static" { |
| + region = "de" |
| + } |
| + // The configured de region has a complete empty census. |
| + zero := evidence == "zero" || region == "de" |
| + msg := fmt.Sprintf(haCapacityUnknownRefusal, region) |
| + if zero { |
| + msg = noCapacityRefusal(region) |
| + } |
| + if hdr.Get("Retry-After") != "60" || errorText(out) != msg { |
| + t.Fatalf("%v %s", hdr, out) |
| + } |
| + if zero { |
| + expectPages(t, pages, noRoomSubject(region)) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateCapacityPendingProof(t *testing.T) { |
| + for _, mode := range []string{"plain", "lifetimes", "claims"} { |
| + for _, door := range []string{"domain", "browser"} { |
| + for _, evidence := range []string{"allow", "zero", "unknown"} { |
| + t.Run(mode+"/"+door+"/"+evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, mode) |
| + f.fx.srv.cfg.DomainProof = true |
| + f.fx.srv.lookupTXT = func(context.Context, string) ([]string, error) { return nil, errors.New("no proof") } |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + f.fx.srv.cfg.Releases = control |
| + local := capacityLocalWrites(t, f.fx) |
| + mark := 0 |
| + if f.claims != nil { |
| + mark = f.claims.rec.mark() |
| + } |
| + code, hdr, out := f.request(t, door) |
| + if evidence == "allow" { |
| + // Claims requires proof up front; the legacy arms can store pending proof. |
| + if mode == "claims" { |
| + if code != 409 || !strings.Contains(out, "prove you control this hostname") { |
| + t.Fatalf("proof refusal: %d %s", code, out) |
| + } |
| + } else if code < 200 || code >= 400 { |
| + t.Fatalf("pending: %d %s", code, out) |
| + } |
| + return |
| + } |
| + want := capacityUnknownIE |
| + if evidence == "zero" { |
| + want = noCapacityRefusal("ie") |
| + } |
| + if code != 503 || hdr.Get("Retry-After") != "60" || !strings.Contains(out, want) { |
| + t.Fatalf("%d %v %s", code, hdr, out) |
| + } |
| + if n, _ := control.counts(); n != 0 { |
| + t.Fatalf("pending proof writes=%d", n) |
| + } |
| + if f.claims != nil { |
| + wroteNothing(t, f.claims, mark) |
| + } |
| + local() |
| + if evidence == "zero" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestHACreateCapacityBeforeEnvironmentBinding(t *testing.T) { |
| + for _, evidence := range []string{"allow", "zero", "unknown"} { |
| + t.Run(evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "plain") |
| + key, before := putSeedStore(t, &claimCase{consoleFixture: f.fx}) |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + f.fx.srv.cfg.Releases = control |
| + local := capacityLocalWrites(t, f.fx) |
| + code, _, out := rawReq(t, http.MethodPost, instancesURL(f.fx, "bab", "titogo"), f.token, `{"host":"capacity.go.tito.io","environment":"canary"}`) |
| + after, _, err := f.fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if evidence == "allow" { |
| + if code != 201 || string(before) == string(after) { |
| + t.Fatalf("binding not exercised: %d %s", code, out) |
| + } |
| + return |
| + } |
| + if code != 503 || string(before) != string(after) { |
| + t.Fatalf("refusal bound environment: %d %s", code, out) |
| + } |
| + if n, _ := control.counts(); n != 0 { |
| + t.Fatalf("writes=%d", n) |
| + } |
| + local() |
| + if evidence == "zero" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateCapacityUnavailableObservation(t *testing.T) { |
| + for _, scenario := range []string{"not-started", "expired", "failed"} { |
| + t.Run(scenario, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "plain") |
| + if scenario != "not-started" { |
| + o := createCapacityEvidence(t, f.fx.srv, "allow", nil) |
| + if scenario == "expired" { |
| + o.current.Store(o.observe(context.Background(), time.Now().Add(-120*time.Second))) |
| + } else { |
| + o.store = &haControlledStore{Store: o.store, metadata: o.store.(haMetadataLister), failAt: 1} |
| + o.current.Store(o.observe(context.Background(), time.Now())) |
| + } |
| + } |
| + code, hdr, out := f.request(t, "instance") |
| + if code != 503 || hdr.Get("Retry-After") != "60" || errorText(out) != capacityUnknownIE { |
| + t.Fatalf("%d %v %s", code, hdr, out) |
| + } |
| + expectPages(t, pages) |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateCapacityClaimsPrivate(t *testing.T) { |
| + for _, evidence := range []string{"allow", "zero", "unknown"} { |
| + t.Run(evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "claims") |
| + approveStoreAccount(t, f.fx, "operator@keymail.dev") |
| + m := titoManifest() |
| + m.Regions = nil |
| + m.Pool = "" |
| + m.PrivateStorage = true |
| + enableInstances(t, f.fx, "titogo", m) |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + control := &haCreateStore{Store: f.fx.srv.cfg.Releases} |
| + f.fx.srv.cfg.Releases = control |
| + local := capacityLocalWrites(t, f.fx) |
| + mark := f.claims.rec.mark() |
| + code, _, out := f.request(t, "binary") |
| + if evidence == "allow" { |
| + if code != 201 && code != 202 { |
| + t.Fatalf("%d %s", code, out) |
| + } |
| + return |
| + } |
| + if code != 503 { |
| + t.Fatalf("%d %s", code, out) |
| + } |
| + if n, _ := control.counts(); n != 0 { |
| + t.Fatalf("writes=%d", n) |
| + } |
| + local() |
| + wroteNothing(t, f.claims, mark) |
| + if evidence == "zero" { |
| + expectPages(t, pages, noRoomSubject("ie")) |
| + } else { |
| + expectPages(t, pages) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHACreateCapacityReattachExistingFirstRoute(t *testing.T) { |
| + for _, evidence := range []string{"zero", "unknown"} { |
| + t.Run(evidence, func(t *testing.T) { |
| + pages := pagesTo(t) |
| + f := capacityFixture(t, "plain") |
| + createCapacityEvidence(t, f.fx.srv, "allow", nil) |
| + if code, _, out := f.request(t, "domain"); code != 200 && code != 201 { |
| + t.Fatalf("initial: %d %s", code, out) |
| + } |
| + before, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", "titogo", "capacity.example.com")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + createCapacityEvidence(t, f.fx.srv, evidence, nil) |
| + if code, _, out := f.request(t, "domain"); code != 200 && code != 201 { |
| + t.Fatalf("reattach: %d %s", code, out) |
| + } |
| + after, _, err := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", "titogo", "capacity.example.com")) |
| + if err != nil || string(before) != string(after) { |
| + t.Fatalf("reattach changed record: %v", err) |
| + } |
| + expectPages(t, pages) |
| + }) |
| + } |
| +} |