ha: observe verified regional capacity without claims
cmd/console/hacapacity_test.go+90 −0cmd/console/main.go+20 −3internal/console/hacapacity.go+515 −0internal/console/hacapacity_observe.go+546 −0internal/console/hacapacity_observe_test.go+586 −0internal/console/hacapacity_test.go+527 −0internal/console/server.go+7 −1
CI failed — run details
Intent
<task-notification> <task-id>b2uempxgv</task-id> <tool-use-id>toolu_01Ub6Jh2Zgz6tjTptk7SGnFf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/b2uempxgv.output</output-file> <status>completed</status> <summary>Background command "Wait for T0 implementer to finish or die" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a81cbd3bdce794e6b</task-id> <tool-use-id>toolu_01WiekdooawVW9CY8SanVkhF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/a81cbd3bdce794e6b.output</output-file> <status>completed</status> <summary>Agent "Review T0 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**T0 review: named_pools on existing edges evidence (ebe36811..79176bba)** Spec compliance: ✅ - **Missing:** nothing in T0's scope. Ruling R1 assigns the console decoder and the mixed-version create-handler witnesses to T1 and T3. - **Extra:** none. The edits to `internal/edge/testdata/edges-forward-hub.json` and `movesoffline_e2e_test.go` are needed by the new field and the extra return value (see below). - **Misunderstood:** none. Code quality: **Approved.** No P1 or P2 findings. **How the requirements are met** - **One source (R6):** `edgesFileEligibility` (`internal/host/edgesfile.go:1072-1085`) calls `provisionTickConfig(getenv)` once and gets the shared-pool answer, the inbound answer and the named pools from that one result. That function is the `ParseBoxPools` path the reconciler uses. It is still called once at arm (`:1165`). The rearm test checks this: `reads` goes to 1, then 2, then 4, matching the number of arms. - **Filtering:** keeps only names that are nonempty and pass `provision.ValidPool`, then sorts and removes repeats. `ParseBoxPools` passes invalid tokens through as written and turns `@shared` into `""`. Both are dropped, so an invalid token cannot affect evidence for valid pools. - **Matches the reconciler:** membership is exactly `poolServed`'s answer for every valid name (`reconcile.go:3313`), since `poolServed` is `slices.Contains(cfg.Pools, pool)` whenever the list is nonempty. The test checks this against a real `provision.Reconcile` run, not a copy of the predicate. No provision helper was exported. - **Always an explicit array:** the writer swaps a nil list for `[]string{}` (`edgesfile.go:956`) before building the comparison copy and the body, and the field has no `omitempty`. `edgesFileWriteClaims` is the only place that writes `control/edges/` (via `putReplacing` at `:995`), so every write path is covered. - **Cost and cadence:** no new object, timer, LIST or GET. The field rides the existing comparison copy, the replacing write and the change-index bump. The rearm test counts requests and index entries: a reordered or duplicated list causes 0 requests, a changed list causes 1 PUT and 1 index increment. Edges version stays at 1. - **Old readers:** I checked every `DisallowUnknownFields` use outside tests; none decodes an edges body. `edgesfile.Parse` gives the same result with and without the field, and `ReadSnapshot` accepts the golden body. - **No host-list inference:** names come only from the configuration. - **Hub golden edit:** `internal/edge/testdata/edges-forward-hub.json` is written by the host test (`edgesfile_forward_test.go:51`, "checked in for the edge package's issuer test"). The only change is `"named_pools":[]` in its serialization position. Host routes are unchanged. - **Offline-move test edit:** `movesoffline_e2e_test.go:399,410` takes the third return value and passes it into the identity, as the production loop does. No assertion was touched. - **Existing exact-body tests** (`edgesfile_test.go`): each expected body only gains `"named_pools":[]`. No assertion is weakened. **Findings (all P3)** 1. **P3, steady-state cost.** The first pass after the upgrade writes once per box. The gate is seeded from the stored body (`seedEdgesFileGate`, `edgesfile.go:1030-1045`), whose missing field decodes as nil and marshals as `null`. That differs from the new `[]`, so each box pays 1 PUT plus 1 index increment once per roll. This is unavoidable for a field that is always written, and steady state is 0 added. The census card and the budget row should still state the one-off roll write rather than a flat "0 added P". 2. **P3, test seam.** The golden's role fields come from a test fake (`internal/host/boxroles_test.go:191`) rather than the production publisher's Source. It does go through the real `RoleSource` interface and `snapshotBoxRole`, and the bytes are the real `edgesFilePass` output. Acceptable for R5's "real role-source seam". 3. **P3, handoff to T1.** The golden pins `"generation":"2026-11-04T12:00:00Z"`, so T1's freshness tests must inject a clock. The report says so. 4. **P3, handoff to T1/T3.** `named_pools` means "pool served", not "would mint". A box with `CARLOS_INBOUND=none` publishes its pools but refuses every new route (`reconcile.go:1887`). Design row 5 already requires named-pool membership AND `accepts_inbound=true`. T3 needs a witness for an inbound=none box with a named pool, or a console could admit onto a box that won't serve it. **⚠️ Cannot verify from the diff** - Census-card and envelope approval, plus the overlay, which the controller owns. The report's dry run shows `internal/host` envelopes re-pinned. - Darwin and Windows cross-builds: the implementer reports them clean and I did not re-run them. I ran no tests and left the tree unmodified.</result> <usage><subagent_tokens>75087</subagent_tokens><tool_uses>11</tool_uses><duration_ms>109834</duration_ms></usage> </task-notification>
Attributed to this commit: 14.3 g CO₂e (1,660,503 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p2b-build, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/cmd/console/hacapacity_test.go b/cmd/console/hacapacity_test.go| new file mode 100644 |
| index 000000000..98ac78f54 |
| --- /dev/null |
| +++ b/cmd/console/hacapacity_test.go |
| @@ -0,0 +1,90 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| +) |
| + |
| +func TestHACapacityServeActivation(t *testing.T) { |
| + // The non-HA path must not even call into the server. In particular, |
| + // CloudWatch-only activation remains T2's work. |
| + done := startHACapacity(context.Background(), nil, console.Config{}) |
| + select { |
| + case <-done: |
| + default: |
| + t.Fatal("non-HA started observer") |
| + } |
| + srv := &console.Server{} |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + // A configured HA region starts independently of HostClaim. The bare |
| + // server's invalid config closes promptly and leaves evidence unavailable. |
| + done = startHACapacity(ctx, srv, console.Config{HARegions: []string{"ie"}}) |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Fatal("invalid config runner stayed alive") |
| + } |
| + if _, ok := srv.HACapacity(); ok { |
| + t.Fatal("invalid config produced evidence") |
| + } |
| +} |
| +func TestHACapacityServeWiring(t *testing.T) { |
| + f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var serve *ast.FuncDecl |
| + for _, d := range f.Decls { |
| + if fn, ok := d.(*ast.FuncDecl); ok && fn.Name.Name == "serve" { |
| + serve = fn |
| + } |
| + } |
| + if serve == nil { |
| + t.Fatal("serve missing") |
| + } |
| + var starts, stops, waits int |
| + fields := map[string]string{} |
| + ast.Inspect(serve.Body, func(n ast.Node) bool { |
| + if kv, ok := n.(*ast.KeyValueExpr); ok { |
| + if k, ok := kv.Key.(*ast.Ident); ok { |
| + if call, ok := kv.Value.(*ast.CallExpr); ok && len(call.Args) == 1 { |
| + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && isIdent(sel.X, "os") && sel.Sel.Name == "Getenv" { |
| + if arg, ok := call.Args[0].(*ast.BasicLit); ok { |
| + fields[k.Name] = arg.Value |
| + } |
| + } |
| + } |
| + } |
| + } |
| + if call, ok := n.(*ast.CallExpr); ok { |
| + if fun, ok := call.Fun.(*ast.Ident); ok { |
| + switch fun.Name { |
| + case "startHACapacity": |
| + starts++ |
| + if len(call.Args) != 3 || !isIdent(call.Args[0], "capacityCtx") || !isIdent(call.Args[1], "srv") || !isIdent(call.Args[2], "cfg") { |
| + t.Error("observer not wired to serving lifetime/config") |
| + } |
| + case "stopCapacity": |
| + stops++ |
| + } |
| + } |
| + } |
| + if u, ok := n.(*ast.UnaryExpr); ok && u.Op == token.ARROW && isIdent(u.X, "capacityDone") { |
| + waits++ |
| + } |
| + return true |
| + }) |
| + if starts != 1 || stops != 2 || waits != 1 { |
| + t.Fatalf("start=%d cancel=%d shutdown wait=%d", starts, stops, waits) |
| + } |
| + if fields["HACapacityConfig"] != `"CONSOLE_HA_CAPACITY_CONFIG"` || fields["HACapacityDirectory"] != `"CARLOS_DEPLOYMENT_DIR"` { |
| + t.Fatalf("configuration wiring: %v", fields) |
| + } |
| +} |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 957306d7a..6e0e9143f 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -501,7 +501,9 @@ func serve() { |
| AWSAccount: strings.TrimSpace(os.Getenv("CARLOS_AWS_ACCOUNT")), |
| AppRegions: appRegionsSwitch(os.Getenv("CONSOLE_APP_REGIONS")), |
| // Region HA P1a: hosts created in these regions are born HA. |
| - HARegions: haRegionsList(os.Getenv("CONSOLE_HA_REGIONS")), |
| + HARegions: haRegionsList(os.Getenv("CONSOLE_HA_REGIONS")), |
| + HACapacityConfig: os.Getenv("CONSOLE_HA_CAPACITY_CONFIG"), |
| + HACapacityDirectory: os.Getenv("CARLOS_DEPLOYMENT_DIR"), |
| // GeoIP (geoip spec §11.3): the CONSOLE_GEOIP_DB override when set, |
| // otherwise the follower of this box's own edge mirror. |
| GeoIP: geoLocator(geoReader), |
| @@ -642,14 +644,19 @@ func serve() { |
| defer cancel() |
| srv.LoadHostsMode(ctx) |
| }() |
| + capacityCtx, stopCapacity := context.WithCancel(context.Background()) |
| + defer stopCapacity() |
| + capacityDone := startHACapacity(capacityCtx, srv, cfg) |
| // A graceful stop releases the app policy writer lease, so a rolled |
| // console's successor need not wait out its TTL (the housekeeper's |
| - // "graceful stand-down must be reachable"). Nothing else here shuts down |
| - // gracefully, so the handler exits straight after the release. |
| + // "graceful stand-down must be reachable"). Cancel and join the capacity |
| + // observer before releasing the lease and exiting. |
| go func() { |
| sig := make(chan os.Signal, 1) |
| signal.Notify(sig, syscall.SIGTERM, os.Interrupt) |
| <-sig |
| + stopCapacity() |
| + <-capacityDone |
| srv.ReleasePolicyWriter(context.Background()) |
| os.Exit(0) |
| }() |
| @@ -2069,3 +2076,13 @@ func pdfEngine(getenv func(string) string) (string, error) { |
| } |
| return addr, nil |
| } |
| + |
| +// startHACapacity keeps observation independent of claim-worker activation. |
| +func startHACapacity(ctx context.Context, srv *console.Server, cfg console.Config) <-chan struct{} { |
| + if len(cfg.HARegions) > 0 { |
| + return srv.StartHACapacityObservation(ctx) |
| + } |
| + done := make(chan struct{}) |
| + close(done) |
| + return done |
| +} |
diff --git a/internal/console/hacapacity.go b/internal/console/hacapacity.go| new file mode 100644 |
| index 000000000..1903b342f |
| --- /dev/null |
| +++ b/internal/console/hacapacity.go |
| @@ -0,0 +1,515 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "math" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +const ( |
| + haCapacityInterval = 60 * time.Second |
| + haCapacityDeadline = 45 * time.Second |
| + haCapacityLifetime = 120 * time.Second |
| + haCapacityBodyLimit = 1 << 20 |
| + haCapacityIdentityLimit = 64 << 10 |
| + haCapacityKeyLimit = 200 |
| + haCapacityRawStatusLimit = 1000 |
| +) |
| + |
| +var ( |
| + haAWSRegion = regexp.MustCompile(`^[a-z]{2}(?:-[a-z]+)+-[0-9]+$`) |
| + haInstanceID = regexp.MustCompile(`^i-(?:[0-9a-f]{8}|[0-9a-f]{17})$`) |
| + haFingerprint = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) |
| + errHACapacity = errors.New("ha_capacity_invalid_evidence") |
| +) |
| + |
| +type haCoordinates struct { |
| + AWSRegion string `json:"aws_region"` |
| + DataBucket string `json:"data_bucket"` |
| + DataBucketRegion string `json:"data_bucket_region"` |
| +} |
| +type haFixedBox struct { |
| + RegionCode string `json:"region_code"` |
| + InstanceID string `json:"instance_id"` |
| +} |
| +type haCapacityConfig struct { |
| + V int `json:"v"` |
| + Regions map[string]haCoordinates `json:"regions"` |
| + FixedBoxes map[string]haFixedBox `json:"fixed_boxes"` |
| + home string |
| + universe []string |
| +} |
| + |
| +// haJSON checks duplicate members before decoding; encoding/json otherwise keeps |
| +// the last value. Configuration also refuses null at every depth. |
| +func haJSON(raw []byte, noNull bool) error { |
| + d := json.NewDecoder(bytes.NewReader(raw)) |
| + var value func() error |
| + value = func() error { |
| + tok, err := d.Token() |
| + if err != nil { |
| + return err |
| + } |
| + if tok == nil && noNull { |
| + return errHACapacity |
| + } |
| + delim, ok := tok.(json.Delim) |
| + if !ok { |
| + return nil |
| + } |
| + switch delim { |
| + case '{': |
| + seen := map[string]bool{} |
| + for d.More() { |
| + k, err := d.Token() |
| + if err != nil { |
| + return err |
| + } |
| + s, ok := k.(string) |
| + if !ok || seen[s] { |
| + return errHACapacity |
| + } |
| + seen[s] = true |
| + if err := value(); err != nil { |
| + return err |
| + } |
| + } |
| + case '[': |
| + for d.More() { |
| + if err := value(); err != nil { |
| + return err |
| + } |
| + } |
| + default: |
| + return errHACapacity |
| + } |
| + _, err = d.Token() |
| + return err |
| + } |
| + if err := value(); err != nil { |
| + return err |
| + } |
| + if _, err := d.Token(); err != io.EOF { |
| + return errHACapacity |
| + } |
| + return nil |
| +} |
| +func parseHACapacityConfig(raw string, regions []string, home string) (*haCapacityConfig, error) { |
| + if len(raw) > haCapacityIdentityLimit || home == "" || !provision.ValidRegion(home) || haJSON([]byte(raw), true) != nil { |
| + return nil, errHACapacity |
| + } |
| + // Struct decoding is case-insensitive, so check the exact schema keys first. |
| + var root haFields |
| + if json.Unmarshal([]byte(raw), &root) != nil || !haOnlyFields(root, "v", "regions", "fixed_boxes") { |
| + return nil, errHACapacity |
| + } |
| + regionFields, regionsOK := haField[map[string]haFields](root, "regions") |
| + fixedFields, fixedOK := haField[map[string]haFields](root, "fixed_boxes") |
| + if !regionsOK || !fixedOK { |
| + return nil, errHACapacity |
| + } |
| + for _, fields := range regionFields { |
| + if !haOnlyFields(fields, "aws_region", "data_bucket", "data_bucket_region") { |
| + return nil, errHACapacity |
| + } |
| + } |
| + for _, fields := range fixedFields { |
| + if !haOnlyFields(fields, "region_code", "instance_id") { |
| + return nil, errHACapacity |
| + } |
| + } |
| + var c haCapacityConfig |
| + d := json.NewDecoder(strings.NewReader(raw)) |
| + d.DisallowUnknownFields() |
| + if d.Decode(&c) != nil || c.V != 1 || c.Regions == nil || c.FixedBoxes == nil || len(c.FixedBoxes) > haCapacityKeyLimit { |
| + return nil, errHACapacity |
| + } |
| + for code, coords := range c.Regions { |
| + if code == "" || !provision.ValidRegion(code) || !haAWSRegion.MatchString(coords.AWSRegion) || !objstore.ValidBucketName(coords.DataBucket) || !haAWSRegion.MatchString(coords.DataBucketRegion) { |
| + return nil, errHACapacity |
| + } |
| + } |
| + seen := map[string]bool{} |
| + for ref, pin := range c.FixedBoxes { |
| + if !boxid.ValidBox(ref) || !haInstanceID.MatchString(pin.InstanceID) || seen[pin.InstanceID] { |
| + return nil, errHACapacity |
| + } |
| + if _, ok := c.Regions[pin.RegionCode]; !ok { |
| + return nil, errHACapacity |
| + } |
| + seen[pin.InstanceID] = true |
| + } |
| + for _, r := range regions { |
| + if _, ok := c.Regions[r]; !ok { |
| + return nil, errHACapacity |
| + } |
| + } |
| + c.home = home |
| + c.universe = slices.Clone(regions) |
| + slices.Sort(c.universe) |
| + c.universe = slices.Compact(c.universe) |
| + return &c, nil |
| +} |
| +func haGroupReference(account, instance string) string { |
| + sum := sha256.Sum256([]byte("carlos-box-ref-v1|" + account + "|" + instance)) |
| + return "g-" + hex.EncodeToString(sum[:])[:20] |
| +} |
| + |
| +type haFields map[string]json.RawMessage |
| + |
| +func haOnlyFields(fields haFields, names ...string) bool { |
| + if fields == nil { |
| + return false |
| + } |
| + for key := range fields { |
| + if !slices.Contains(names, key) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func haField[T any](f haFields, key string) (v T, ok bool) { |
| + raw, ok := f[key] |
| + if !ok || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { |
| + return v, false |
| + } |
| + err := json.Unmarshal(raw, &v) |
| + return v, err == nil |
| +} |
| +func haTime(f haFields, key string) (time.Time, bool) { |
| + s, ok := haField[string](f, key) |
| + if !ok { |
| + return time.Time{}, false |
| + } |
| + t, e := time.Parse(time.RFC3339, s) |
| + return t, e == nil && !t.IsZero() |
| +} |
| + |
| +type haCapacityFile struct { |
| + key, ref string |
| + fields haFields |
| + malformed bool |
| + identityCode string |
| + instance string |
| + report *status.Box |
| + statusCode string |
| +} |
| + |
| +// HACapacityObservation retains producer evidence. Its fields and collections |
| +// are private: readers can share a generation without copying or changing it. |
| +// All projections recheck producer ages and the 120-second pass lifetime. |
| +type HACapacityObservation struct { |
| + id string |
| + started, completed time.Time |
| + config *haCapacityConfig |
| + fingerprint string |
| + unavailable string |
| + files []haCapacityFile |
| +} |
| + |
| +func (o *HACapacityObservation) ID() string { |
| + if o == nil { |
| + return "" |
| + } |
| + return o.id |
| +} |
| +func (o *HACapacityObservation) Times() (started, completed time.Time) { |
| + if o == nil { |
| + return |
| + } |
| + return o.started, o.completed |
| +} |
| +func (o *HACapacityObservation) available(now time.Time) bool { |
| + return o != nil && o.config != nil && o.unavailable == "" && !now.Before(o.started) && now.Sub(o.started) < haCapacityLifetime |
| +} |
| + |
| +// HACapacityRegional is suitable for a metric only when Complete is true. |
| +type HACapacityRegional struct { |
| + Count int |
| + Complete bool |
| +} |
| +type HACapacityDecisionKind string |
| + |
| +const ( |
| + HACapacityAllow HACapacityDecisionKind = "allow" |
| + HACapacityCompleteZero HACapacityDecisionKind = "complete_zero" |
| + HACapacityUnknown HACapacityDecisionKind = "unknown" |
| +) |
| + |
| +// MissingNamedPoolsOnly distinguishes missing publication from every other |
| +// uncertainty. A malformed publication never receives this flag. |
| +type HACapacityDecision struct { |
| + Kind HACapacityDecisionKind |
| + MissingNamedPoolsOnly bool |
| +} |
| + |
| +// HACapacityBlocker identifies a file and its current machine-readable reason. |
| +// These storage keys belong only on operator diagnostics, never member pages. |
| +type HACapacityBlocker struct{ Key, Code string } |
| + |
| +func (o *HACapacityObservation) Regional(region string, now time.Time) HACapacityRegional { |
| + n, complete, _ := o.project(region, "", false, now) |
| + return HACapacityRegional{n, complete} |
| +} |
| + |
| +// Decide takes a normalized placement code (the named home, not wire "") and |
| +// the pool ("" means shared). It performs no I/O and grants no box authority. |
| +func (o *HACapacityObservation) Decide(region, pool string, now time.Time) HACapacityDecision { |
| + n, complete, onlyPools := o.project(region, pool, true, now) |
| + if n > 0 { |
| + return HACapacityDecision{Kind: HACapacityAllow} |
| + } |
| + if complete { |
| + return HACapacityDecision{Kind: HACapacityCompleteZero} |
| + } |
| + return HACapacityDecision{Kind: HACapacityUnknown, MissingNamedPoolsOnly: onlyPools} |
| +} |
| +func (o *HACapacityObservation) project(region, pool string, narrow bool, now time.Time) (count int, complete, onlyPools bool) { |
| + if !o.available(now) || !slices.Contains(o.config.universe, region) { |
| + return 0, false, false |
| + } |
| + complete = true |
| + onlyPools = true |
| + for _, f := range o.files { |
| + eligible, known, code := o.classify(f, region, now) |
| + if eligible && narrow { |
| + eligible, known, code = haPool(f.fields, pool) |
| + } |
| + if eligible { |
| + count++ |
| + } |
| + if !known { |
| + complete = false |
| + if code != "named_pools_missing" { |
| + onlyPools = false |
| + } |
| + } |
| + } |
| + return count, complete, !complete && onlyPools |
| +} |
| +func (o *HACapacityObservation) Blockers(region string, now time.Time) []HACapacityBlocker { |
| + return o.blockers(region, "", false, now) |
| +} |
| + |
| +// CreateBlockers adds the requested pool's evidence to regional diagnostics. |
| +func (o *HACapacityObservation) CreateBlockers(region, pool string, now time.Time) []HACapacityBlocker { |
| + return o.blockers(region, pool, true, now) |
| +} |
| +func (o *HACapacityObservation) blockers(region, pool string, narrow bool, now time.Time) []HACapacityBlocker { |
| + if !o.available(now) { |
| + code := "observation_unavailable" |
| + if o != nil && o.unavailable != "" { |
| + code = o.unavailable |
| + } |
| + return []HACapacityBlocker{{Code: code}} |
| + } |
| + var out []HACapacityBlocker |
| + for _, f := range o.files { |
| + eligible, _, code := o.classify(f, region, now) |
| + if eligible && narrow { |
| + _, _, code = haPool(f.fields, pool) |
| + } |
| + if code != "" { |
| + out = append(out, HACapacityBlocker{f.key, code}) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// scope applies independently valid exclusions before demanding identity or |
| +// status. A broken field cannot exclude a box, but a valid non-HA neighbor can. |
| +func (o *HACapacityObservation) scope(f haCapacityFile, region string, now time.Time) (excluded bool, code string) { |
| + if f.malformed { |
| + return false, "edges_malformed" |
| + } |
| + fields := f.fields |
| + coords := o.config.Regions[region] |
| + wantPlacement := region |
| + if region == o.config.home { |
| + wantPlacement = "" |
| + } |
| + placement, placementOK := haField[string](fields, "placement") |
| + if _, present := fields["placement"]; !present { |
| + placementOK = true |
| + } |
| + placementOK = placementOK && provision.ValidRegion(placement) |
| + if placementOK && placement != wantPlacement { |
| + return true, "outside_region" |
| + } |
| + bucket, bucketOK := haField[string](fields, "data_bucket") |
| + bucketOK = bucketOK && objstore.ValidBucketName(bucket) |
| + if bucketOK && bucket != coords.DataBucket { |
| + return true, "outside_data_bucket" |
| + } |
| + bucketRegion, bucketRegionOK := haField[string](fields, "data_bucket_region") |
| + bucketRegionOK = bucketRegionOK && haAWSRegion.MatchString(bucketRegion) |
| + if bucketRegionOK && bucketRegion != coords.DataBucketRegion { |
| + return true, "outside_data_region" |
| + } |
| + fp, fpOK := haField[string](fields, "secrets_key_fp") |
| + fpOK = fpOK && haFingerprint.MatchString(fp) |
| + if fpOK && o.fingerprint != "" && fp != o.fingerprint { |
| + return true, "outside_fingerprint" |
| + } |
| + caps, capsOK := haField[[]string](fields, "capabilities") |
| + capsOK = capsOK && haJSON(fields["capabilities"], true) == nil |
| + for _, capability := range caps { |
| + if capability == "" { |
| + capsOK = false |
| + } |
| + } |
| + if capsOK && !slices.Contains(caps, "region-ha-1") { |
| + return true, "no_ha_capability" |
| + } |
| + hibernation, hibernationOK := haField[bool](fields, "hibernation_configured") |
| + if hibernationOK && !hibernation { |
| + return true, "no_hibernation" |
| + } |
| + at, atOK := haTime(fields, "generation") |
| + if atOK && now.Sub(at) > boxchoice.MaxEdgesAge { |
| + return true, "edges_stale" |
| + } |
| + v, vOK := haField[int](fields, "v") |
| + if !placementOK || !bucketOK || !bucketRegionOK || !fpOK || o.fingerprint == "" || !capsOK || !hibernationOK { |
| + return false, "scope_unknown" |
| + } |
| + if !vOK || v != 1 { |
| + return false, "edges_version" |
| + } |
| + if !atOK || at.After(now.Add(time.Minute)) { |
| + return false, "edges_time" |
| + } |
| + aws, awsOK := haField[string](fields, "region") |
| + if !awsOK || !haAWSRegion.MatchString(aws) { |
| + return false, "scope_unknown" |
| + } |
| + if aws != coords.AWSRegion { |
| + return false, "aws_region_conflict" |
| + } |
| + return false, "" |
| +} |
| +func (o *HACapacityObservation) classify(f haCapacityFile, region string, now time.Time) (eligible, known bool, code string) { |
| + excluded, code := o.scope(f, region, now) |
| + if excluded { |
| + return false, true, code |
| + } |
| + if code != "" { |
| + return false, false, code |
| + } |
| + box, bok := haField[string](f.fields, "box") |
| + id, iok := haField[string](f.fields, "box_id") |
| + if !bok || !iok || box != f.ref || id != f.ref { |
| + return false, false, "reference_conflict" |
| + } |
| + if f.identityCode != "" { |
| + return false, f.identityCode == "identity_invalid" || f.identityCode == "identity_unbound", f.identityCode |
| + } |
| + if f.instance == "" { |
| + return false, false, "identity_missing" |
| + } |
| + if f.statusCode != "" { |
| + return false, false, f.statusCode |
| + } |
| + if f.report == nil { |
| + return false, false, "status_missing" |
| + } |
| + b := f.report |
| + if b.Metrics == nil || b.Metrics.InstanceID == "" { |
| + return false, false, "status_instance_missing" |
| + } |
| + if b.Metrics.InstanceID != f.instance { |
| + return false, false, "instance_conflict" |
| + } |
| + if b.GeneratedAt.IsZero() || b.GeneratedAt.After(now.Add(time.Minute)) { |
| + return false, false, "status_time" |
| + } |
| + if status.BoxStale(*b, now, status.SnapshotPeriod) { |
| + return false, true, "status_stale" |
| + } |
| + role, rok := haField[string](f.fields, "box_role") |
| + admitted, aok := haField[bool](f.fields, "admitted") |
| + drained, dok := haField[bool](f.fields, "drained") |
| + draining, lok := haField[bool](f.fields, "draining") |
| + if _, present := f.fields["draining"]; !present { |
| + lok = true |
| + } |
| + if !rok || !aok || !dok || !lok || !slices.Contains([]string{"serve", "booting", "drain", "platform"}, role) { |
| + return false, false, "admission_unknown" |
| + } |
| + if role != "serve" || !admitted || drained || draining { |
| + return false, true, "admission_excluded" |
| + } |
| + head, ok := haField[haFields](f.fields, "headroom") |
| + if _, present := f.fields["headroom"]; !present { |
| + ok = true |
| + } |
| + if !ok { |
| + return false, false, "headroom_unknown" |
| + } |
| + numbers := make([]int64, 4) |
| + for i, key := range []string{"mem_free_mib", "mem_total_mib", "disk_free_mib", "disk_total_mib"} { |
| + n, ok := haField[int64](head, key) |
| + if _, present := head[key]; !present { |
| + ok = true |
| + } |
| + if !ok || n < 0 || n > math.MaxInt64/100 { |
| + return false, false, "headroom_unknown" |
| + } |
| + numbers[i] = n |
| + } |
| + _, memTotalPresent := head["mem_total_mib"] |
| + _, diskTotalPresent := head["disk_total_mib"] |
| + if (memTotalPresent && numbers[0] > numbers[1]) || (diskTotalPresent && numbers[2] > numbers[3]) { |
| + return false, false, "headroom_unknown" |
| + } |
| + generation, _ := haField[string](f.fields, "generation") |
| + cand := boxchoice.Candidate{BoxID: f.ref, Generation: generation, MemFreeMiB: numbers[0], MemTotalMiB: numbers[1], DiskFreeMiB: numbers[2], DiskTotalMiB: numbers[3]} |
| + if len(boxchoice.Placeable([]boxchoice.Candidate{cand}, nil, now)) == 0 { |
| + return false, true, "headroom_excluded" |
| + } |
| + return true, true, "" |
| +} |
| +func haPool(fields haFields, pool string) (eligible, known bool, code string) { |
| + inbound, ok := haField[bool](fields, "accepts_inbound") |
| + if !ok { |
| + return false, false, "inbound_unknown" |
| + } |
| + if !inbound { |
| + return false, true, "inbound_excluded" |
| + } |
| + if pool == "" { |
| + shared, ok := haField[bool](fields, "serves_shared_pool") |
| + if !ok { |
| + return false, false, "shared_pool_unknown" |
| + } |
| + return shared, true, "" |
| + } |
| + pools, ok := haField[[]string](fields, "named_pools") |
| + if !ok { |
| + if _, present := fields["named_pools"]; !present { |
| + return false, false, "named_pools_missing" |
| + } |
| + return false, false, "named_pools_malformed" |
| + } |
| + for _, p := range pools { |
| + if p == "" || !provision.ValidPool(p) { |
| + return false, false, "named_pools_malformed" |
| + } |
| + } |
| + return slices.Contains(pools, pool), true, "" |
| +} |
diff --git a/internal/console/hacapacity_observe.go b/internal/console/hacapacity_observe.go| new file mode 100644 |
| index 000000000..197413430 |
| --- /dev/null |
| +++ b/internal/console/hacapacity_observe.go |
| @@ -0,0 +1,546 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "log" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +const haStatusPrefix = "status/boxes/" |
| +const haConfigCopy = "HA capacity configuration is invalid for %s. Check the configured region, data bucket and box identities." |
| +const haStartCopy = "HA capacity observation started. Checking once a minute." |
| +const haFailureCopy = "HA capacity evidence is incomplete for %s. New creates are paused there." |
| +const haRecoveryCopy = "HA capacity evidence is available again for %s." |
| +const haUnboundCopy = "This box has a valid signed identity, but the console has no configured reference binding for it. It is excluded from capacity." |
| + |
| +type haObject struct { |
| + key string |
| + modified time.Time |
| +} |
| +type haMetadataLister interface { |
| + haListStatus(context.Context) ([]haObject, bool, error) |
| +} |
| + |
| +// haCapacityStore owns bounded transports, leaving every other reader's client |
| +// and listing semantics unchanged. Unsupported stores cannot form a census. |
| +type haCapacityStore struct { |
| + release.Store |
| + s3 *release.S3Store |
| + directory string |
| +} |
| + |
| +func newHACapacityStore(s release.Store, directory string) release.Store { |
| + b := &haCapacityStore{Store: s} |
| + switch s := s.(type) { |
| + case *release.S3Store: |
| + client := awss3.New(s.Client.Options(), func(o *awss3.Options) { o.Retryer = aws.NopRetryer{}; o.RetryMaxAttempts = 1 }) |
| + b.s3 = &release.S3Store{Client: client, Bucket: s.Bucket} |
| + case *release.DirStore: |
| + b.directory = directory |
| + } |
| + return b |
| +} |
| +func haRef(key, prefix string) (string, bool) { |
| + if !strings.HasPrefix(key, prefix) || !strings.HasSuffix(key, ".json") { |
| + return "", false |
| + } |
| + ref := strings.TrimSuffix(strings.TrimPrefix(key, prefix), ".json") |
| + return ref, boxid.ValidBox(ref) |
| +} |
| +func (s *haCapacityStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + cap := int64(haCapacityBodyLimit) |
| + switch { |
| + case strings.HasPrefix(key, boxid.Prefix): |
| + cap = haCapacityIdentityLimit |
| + if _, ok := haRef(key, boxid.Prefix); !ok { |
| + return nil, "", errHACapacity |
| + } |
| + case strings.HasPrefix(key, edgesfile.Prefix): |
| + if _, ok := haRef(key, edgesfile.Prefix); !ok { |
| + return nil, "", errHACapacity |
| + } |
| + case strings.HasPrefix(key, haStatusPrefix): |
| + if _, ok := haRef(key, haStatusPrefix); !ok { |
| + return nil, "", errHACapacity |
| + } |
| + default: |
| + return nil, "", errHACapacity |
| + } |
| + if err := ctx.Err(); err != nil { |
| + return nil, "", err |
| + } |
| + var body io.ReadCloser |
| + var etag string |
| + if s.s3 != nil { |
| + out, err := s.s3.Client.GetObject(ctx, &awss3.GetObjectInput{Bucket: &s.s3.Bucket, Key: &key}) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + body = out.Body |
| + etag = aws.ToString(out.ETag) |
| + } else if s.directory != "" { |
| + f, err := os.Open(filepath.Join(s.directory, filepath.FromSlash(key))) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + body = f |
| + } else { |
| + return nil, "", errHACapacity |
| + } |
| + defer body.Close() |
| + raw, err := io.ReadAll(io.LimitReader(body, cap+1)) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + if int64(len(raw)) > cap { |
| + return nil, "", errHACapacity |
| + } |
| + return raw, etag, ctx.Err() |
| +} |
| +func (s *haCapacityStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) { |
| + if prefix != edgesfile.Prefix || after != "" || limit != haCapacityKeyLimit+1 { |
| + return nil, errHACapacity |
| + } |
| + if s.s3 != nil { |
| + // PageLister's bounded branch sends one request. Inspect truncation too: |
| + // a service may truncate before MaxKeys, which must never imply zero. |
| + page := &haEdgesPage{store: s.s3} |
| + return page.ListPage(ctx, prefix, after, limit) |
| + } |
| + if s.directory == "" { |
| + return nil, errHACapacity |
| + } |
| + entries, more, err := s.dirPage(ctx, prefix, limit) |
| + if err != nil { |
| + return nil, err |
| + } |
| + keys := make([]string, 0, len(entries)) |
| + for _, e := range entries { |
| + keys = append(keys, e.key) |
| + } |
| + if more && len(keys) < limit { |
| + return nil, errHACapacity |
| + } |
| + return keys, nil |
| +} |
| + |
| +// haEdgesPage implements release.PageLister with a truncation check missing |
| +// from the general reader. It still performs exactly one bounded S3 LIST. |
| +type haEdgesPage struct{ store *release.S3Store } |
| + |
| +var _ release.PageLister = (*haEdgesPage)(nil) |
| + |
| +func (p *haEdgesPage) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) { |
| + out, err := p.store.Client.ListObjectsV2(ctx, &awss3.ListObjectsV2Input{Bucket: &p.store.Bucket, Prefix: &prefix, MaxKeys: aws.Int32(int32(limit))}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if aws.ToBool(out.IsTruncated) { |
| + return nil, errHACapacity |
| + } |
| + keys := make([]string, 0, len(out.Contents)) |
| + for _, o := range out.Contents { |
| + keys = append(keys, aws.ToString(o.Key)) |
| + } |
| + return keys, nil |
| +} |
| +func (s *haCapacityStore) haListStatus(ctx context.Context) ([]haObject, bool, error) { |
| + if s.s3 != nil { |
| + out, err := s.s3.Client.ListObjectsV2(ctx, &awss3.ListObjectsV2Input{Bucket: &s.s3.Bucket, Prefix: aws.String(haStatusPrefix), MaxKeys: aws.Int32(haCapacityRawStatusLimit)}) |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + mods := make([]haObject, 0, len(out.Contents)) |
| + for _, o := range out.Contents { |
| + mods = append(mods, haObject{aws.ToString(o.Key), aws.ToTime(o.LastModified)}) |
| + } |
| + return mods, aws.ToBool(out.IsTruncated), nil |
| + } |
| + if s.directory != "" { |
| + return s.dirPage(ctx, haStatusPrefix, haCapacityRawStatusLimit) |
| + } |
| + return nil, false, errHACapacity |
| +} |
| +func (s *haCapacityStore) dirPage(ctx context.Context, prefix string, limit int) ([]haObject, bool, error) { |
| + if err := ctx.Err(); err != nil { |
| + return nil, false, err |
| + } |
| + dir, err := os.Open(filepath.Join(s.directory, filepath.FromSlash(prefix))) |
| + if os.IsNotExist(err) { |
| + return nil, false, nil |
| + } |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + defer dir.Close() |
| + entries, err := dir.ReadDir(limit + 1) |
| + if err != nil && err != io.EOF { |
| + return nil, false, err |
| + } |
| + more := len(entries) > limit |
| + if more { |
| + entries = entries[:limit] |
| + } |
| + mods := make([]haObject, 0, len(entries)) |
| + for _, e := range entries { |
| + if !e.Type().IsRegular() { |
| + return nil, false, errHACapacity |
| + } |
| + info, err := e.Info() |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + mods = append(mods, haObject{prefix + e.Name(), info.ModTime()}) |
| + } |
| + sort.Slice(mods, func(i, j int) bool { return mods[i].key < mods[j].key }) |
| + return mods, more, ctx.Err() |
| +} |
| + |
| +// haStatusView gives LoadBoxesComplete the bounded, horizon-filtered list. |
| +// Embedding Store deliberately hides ModLister, preventing a second LIST. |
| +type haStatusView struct { |
| + release.Store |
| + keys []string |
| + labels map[string]string |
| + bad map[string]bool |
| +} |
| + |
| +func (v *haStatusView) List(context.Context, string) ([]string, error) { |
| + return append([]string(nil), v.keys...), nil |
| +} |
| +func (v *haStatusView) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + raw, tag, err := v.Store.Get(ctx, key) |
| + if err != nil { |
| + v.bad[key] = true |
| + return nil, "", err |
| + } |
| + if haJSON(raw, false) != nil { |
| + v.bad[key] = true |
| + return nil, "", errHACapacity |
| + } |
| + // Match the status parser's field-name handling, including JSON case |
| + // aliases, so a report cannot borrow another reference through "Label". |
| + var header struct { |
| + Label string `json:"label"` |
| + } |
| + if json.Unmarshal(raw, &header) != nil { |
| + v.bad[key] = true |
| + return nil, "", errHACapacity |
| + } |
| + v.labels[key] = header.Label |
| + return raw, tag, nil |
| +} |
| + |
| +type haClock interface { |
| + Now() time.Time |
| + Ticker(time.Duration) (<-chan time.Time, func()) |
| + Timeout(context.Context, time.Duration) (context.Context, context.CancelFunc) |
| +} |
| +type haWallClock struct{} |
| + |
| +func (haWallClock) Now() time.Time { return time.Now() } |
| +func (haWallClock) Ticker(d time.Duration) (<-chan time.Time, func()) { |
| + t := time.NewTicker(d) |
| + return t.C, t.Stop |
| +} |
| +func (haWallClock) Timeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) { |
| + return context.WithTimeout(ctx, d) |
| +} |
| + |
| +type haObserver struct { |
| + config *haCapacityConfig |
| + store release.Store |
| + verifier boxid.Verifier |
| + fingerprint string |
| + current atomic.Pointer[HACapacityObservation] |
| + sequence atomic.Uint64 |
| + once sync.Once |
| + done chan struct{} |
| + clock haClock |
| +} |
| + |
| +func newHAObserver(c *haCapacityConfig, s release.Store, v boxid.Verifier, fp string) *haObserver { |
| + return &haObserver{config: c, store: s, verifier: v, fingerprint: fp, done: make(chan struct{}), clock: haWallClock{}} |
| +} |
| +func (o *haObserver) fresh(start time.Time) *HACapacityObservation { |
| + return &HACapacityObservation{id: fmt.Sprintf("%d-%d", start.UnixNano(), o.sequence.Add(1)), started: start, completed: start, config: o.config, fingerprint: o.fingerprint} |
| +} |
| +func (o *haObserver) observe(ctx context.Context, start time.Time) *HACapacityObservation { |
| + obs := o.fresh(start) |
| + fail := func(code string) *HACapacityObservation { obs.unavailable = code; return obs } |
| + if o.config == nil { |
| + return fail("configuration_invalid") |
| + } |
| + pl, ok := o.store.(release.PageLister) |
| + if !ok { |
| + return fail("listing_unsupported") |
| + } |
| + keys, err := pl.ListPage(ctx, edgesfile.Prefix, "", haCapacityKeyLimit+1) |
| + if err != nil { |
| + return fail("edges_list_failed") |
| + } |
| + if len(keys) > haCapacityKeyLimit { |
| + return fail("edges_list_capped") |
| + } |
| + ml, ok := o.store.(haMetadataLister) |
| + if !ok { |
| + return fail("listing_unsupported") |
| + } |
| + mods, truncated, err := ml.haListStatus(ctx) |
| + if err != nil { |
| + return fail("status_list_failed") |
| + } |
| + if truncated || len(mods) > haCapacityRawStatusLimit { |
| + return fail("status_list_capped") |
| + } |
| + view := &haStatusView{Store: o.store, labels: map[string]string{}, bad: map[string]bool{}} |
| + seenStatus := map[string]bool{} |
| + for _, m := range mods { |
| + if !m.modified.IsZero() && m.modified.Before(start.Add(-24*time.Hour)) { |
| + continue |
| + } |
| + if _, ok := haRef(m.key, haStatusPrefix); !ok || seenStatus[m.key] { |
| + return fail("status_key_invalid") |
| + } |
| + seenStatus[m.key] = true |
| + view.keys = append(view.keys, m.key) |
| + } |
| + if len(view.keys) > haCapacityKeyLimit { |
| + return fail("status_list_capped") |
| + } |
| + // Per-key outcomes below scope failed reports to their exact reference. A |
| + // self-stale edges file needs no status, including an unreadable counterpart. |
| + boxes, _, err := status.LoadBoxesComplete(ctx, view) |
| + if err != nil { |
| + return fail("status_list_failed") |
| + } |
| + reports := map[string]*status.Box{} |
| + statusCodes := map[string]string{} |
| + for _, b := range boxes { |
| + if reports[b.Label] != nil { |
| + statusCodes[b.Label] = "status_duplicate" |
| + } |
| + copy := b |
| + reports[b.Label] = © |
| + } |
| + labels := map[string]int{} |
| + for _, label := range view.labels { |
| + labels[label]++ |
| + } |
| + for key, label := range view.labels { |
| + ref, _ := haRef(key, haStatusPrefix) |
| + if ref != label || !boxid.ValidBox(label) { |
| + statusCodes[ref] = "status_reference_conflict" |
| + statusCodes[label] = "status_reference_conflict" |
| + } |
| + if labels[label] > 1 { |
| + statusCodes[label] = "status_duplicate" |
| + } |
| + if reports[label] == nil { |
| + statusCodes[ref] = "status_unreadable" |
| + } |
| + } |
| + for key := range view.bad { |
| + ref, _ := haRef(key, haStatusPrefix) |
| + statusCodes[ref] = "status_unreadable" |
| + } |
| + refs := map[string]bool{} |
| + for _, key := range keys { |
| + ref, ok := haRef(key, edgesfile.Prefix) |
| + if !ok || refs[ref] { |
| + return fail("edges_key_invalid") |
| + } |
| + refs[ref] = true |
| + f := haCapacityFile{key: key, ref: ref, report: reports[ref], statusCode: statusCodes[ref]} |
| + raw, _, err := o.store.Get(ctx, key) |
| + if err != nil || haJSON(raw, false) != nil || json.Unmarshal(raw, &f.fields) != nil || f.fields == nil { |
| + f.malformed = true |
| + } |
| + obs.files = append(obs.files, f) |
| + } |
| + instances := map[string][]int{} |
| + refConflicts := map[string]bool{} |
| + for i := range obs.files { |
| + f := &obs.files[i] |
| + region := "" |
| + for _, r := range o.config.universe { |
| + excluded, code := obs.scope(*f, r, start) |
| + if !excluded && code == "" { |
| + region = r |
| + break |
| + } |
| + } |
| + if region == "" { |
| + continue |
| + } |
| + box, bok := haField[string](f.fields, "box") |
| + id, iok := haField[string](f.fields, "box_id") |
| + if !bok || !iok || box != f.ref || id != f.ref { |
| + refConflicts[f.ref] = true |
| + if bok { |
| + refConflicts[box] = true |
| + } |
| + if iok { |
| + refConflicts[id] = true |
| + } |
| + continue |
| + } |
| + raw, err := boxid.Load(ctx, o.store, f.ref) |
| + if err != nil { |
| + f.identityCode = "identity_missing" |
| + continue |
| + } |
| + if haJSON(raw, false) != nil { |
| + f.identityCode = "identity_invalid" |
| + continue |
| + } |
| + var identity haFields |
| + if json.Unmarshal(raw, &identity) == nil { |
| + if version, ok := haField[int](identity, "v"); !ok || version != 1 { |
| + f.identityCode = "identity_version" |
| + continue |
| + } |
| + } |
| + if o.verifier.Account == "" || o.verifier.Certs[o.config.Regions[region].AWSRegion] == nil { |
| + f.identityCode = "identity_verifier_unavailable" |
| + continue |
| + } |
| + ev, err := o.verifier.Enroll(raw, boxid.Expect{Box: f.ref, AWSRegion: o.config.Regions[region].AWSRegion}) |
| + if err != nil { |
| + f.identityCode = "identity_invalid" |
| + continue |
| + } |
| + f.instance = ev.Cloud.InstanceID |
| + instances[f.instance] = append(instances[f.instance], i) |
| + if strings.HasPrefix(f.ref, "g-") && f.ref != haGroupReference(ev.Cloud.Account, f.instance) { |
| + f.identityCode = "instance_conflict" |
| + } else if pin, ok := o.config.FixedBoxes[f.ref]; ok { |
| + if pin.RegionCode != region || pin.InstanceID != f.instance { |
| + f.identityCode = "instance_conflict" |
| + } |
| + } else if f.ref != haGroupReference(ev.Cloud.Account, f.instance) { |
| + f.identityCode = "identity_unbound" |
| + log.Printf(haUnboundCopy+" observation=%s box=%s", obs.id, f.ref) |
| + } |
| + } |
| + for _, indices := range instances { |
| + if len(indices) > 1 { |
| + for _, i := range indices { |
| + obs.files[i].identityCode = "identity_duplicate" |
| + } |
| + } |
| + } |
| + for i := range obs.files { |
| + if refConflicts[obs.files[i].ref] { |
| + obs.files[i].identityCode = "reference_conflict" |
| + } |
| + } |
| + if ctx.Err() != nil { |
| + return fail("observation_failed") |
| + } |
| + return obs |
| +} |
| +func (o *haObserver) start(ctx context.Context) <-chan struct{} { |
| + o.once.Do(func() { go o.run(ctx) }) |
| + return o.done |
| +} |
| +func (o *haObserver) run(ctx context.Context) { |
| + defer close(o.done) |
| + ticks, stop := o.clock.Ticker(haCapacityInterval) |
| + defer stop() |
| + log.Print(haStartCopy) |
| + incomplete := map[string]bool{} |
| + for { |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + start := o.clock.Now() |
| + pass, cancel := o.clock.Timeout(ctx, haCapacityDeadline) |
| + result := make(chan *HACapacityObservation, 1) |
| + go func() { result <- o.observe(pass, start) }() |
| + var obs *HACapacityObservation |
| + published := false |
| + select { |
| + case obs = <-result: |
| + if pass.Err() != nil { |
| + obs.unavailable = "observation_failed" |
| + } |
| + case <-pass.Done(): |
| + obs = o.fresh(start) |
| + obs.unavailable = "observation_failed" |
| + obs.completed = o.clock.Now() |
| + o.current.Store(obs) |
| + published = true |
| + // Do not overlap a canceled pass with its successor, even if a store is |
| + // slow to acknowledge cancellation. Readers already see unknown. |
| + <-result |
| + } |
| + cancel() |
| + if !published { |
| + obs.completed = o.clock.Now() |
| + o.current.Store(obs) |
| + } |
| + if ctx.Err() != nil { |
| + return |
| + } |
| + for _, r := range o.config.universe { |
| + bad := !obs.Regional(r, o.clock.Now()).Complete |
| + if bad && !incomplete[r] { |
| + log.Printf(haFailureCopy+" observation=%s", r, obs.id) |
| + } |
| + if !bad && incomplete[r] { |
| + log.Printf(haRecoveryCopy+" observation=%s", r, obs.id) |
| + } |
| + incomplete[r] = bad |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-ticks: |
| + } |
| + } |
| +} |
| + |
| +// StartHACapacityObservation starts at most one lifetime-owned runner. Call it |
| +// from serve, never NewServer. The returned channel closes after shutdown. |
| +func (s *Server) StartHACapacityObservation(ctx context.Context) <-chan struct{} { |
| + s.haCapacityStart.Do(func() { |
| + c, err := parseHACapacityConfig(s.cfg.HACapacityConfig, s.cfg.HARegions, s.cfg.HomeRegion) |
| + o := newHAObserver(c, newHACapacityStore(s.cfg.Releases, s.cfg.HACapacityDirectory), boxid.Verifier{Account: s.cfg.AWSAccount, Certs: s.boxCerts}, s.expectedSecretsFP()) |
| + s.haCapacity.Store(o) |
| + if err != nil || s.cfg.AWSAccount == "" || o.fingerprint == "" { |
| + log.Printf(haConfigCopy, strings.Join(s.cfg.HARegions, ",")) |
| + close(o.done) |
| + return |
| + } |
| + o.start(ctx) |
| + }) |
| + return s.haCapacity.Load().done |
| +} |
| + |
| +// HACapacity returns the current immutable generation without loading or waiting. |
| +// False means missing, failed or expired evidence; callers must refuse unknown. |
| +func (s *Server) HACapacity() (*HACapacityObservation, bool) { |
| + o := s.haCapacity.Load() |
| + if o == nil { |
| + return nil, false |
| + } |
| + obs := o.current.Load() |
| + return obs, obs.available(o.clock.Now()) |
| +} |
diff --git a/internal/console/hacapacity_observe_test.go b/internal/console/hacapacity_observe_test.go| new file mode 100644 |
| index 000000000..62011b42f |
| --- /dev/null |
| +++ b/internal/console/hacapacity_observe_test.go |
| @@ -0,0 +1,586 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/xml" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +type haDoer func(*http.Request) (*http.Response, error) |
| + |
| +func (f haDoer) Do(r *http.Request) (*http.Response, error) { return f(r) } |
| +func haS3(t *testing.T, do haDoer) *release.S3Store { |
| + t.Helper() |
| + return &release.S3Store{Bucket: "control-test", Client: awss3.New(awss3.Options{ |
| + Region: "eu-west-1", BaseEndpoint: aws.String("https://s3.invalid"), UsePathStyle: true, HTTPClient: do, |
| + Credentials: aws.CredentialsProviderFunc(func(context.Context) (aws.Credentials, error) { |
| + return aws.Credentials{AccessKeyID: "test", SecretAccessKey: "test"}, nil |
| + }), |
| + })} |
| +} |
| +func haResponse(r *http.Request, code int, body io.ReadCloser) *http.Response { |
| + return &http.Response{StatusCode: code, Header: make(http.Header), Body: body, Request: r} |
| +} |
| + |
| +type haXMLObject struct { |
| + Key string |
| + LastModified *string `xml:",omitempty"` |
| +} |
| +type haXMLList struct { |
| + XMLName xml.Name `xml:"ListBucketResult"` |
| + Truncated bool `xml:"IsTruncated"` |
| + Contents []haXMLObject `xml:"Contents"` |
| +} |
| + |
| +func haListXML(objects []haXMLObject, truncated bool) string { |
| + b, _ := xml.Marshal(haXMLList{Truncated: truncated, Contents: objects}) |
| + return string(b) |
| +} |
| + |
| +func TestHACapacityBudgetTransport(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + edges, status, old int |
| + truncated, missingMod bool |
| + wantComplete bool |
| + }{ |
| + {name: "empty", wantComplete: true}, |
| + {name: "200 edges", edges: 200, wantComplete: true}, |
| + {name: "201 edges", edges: 201}, |
| + {name: "200 recent status", status: 200, wantComplete: true}, |
| + {name: "201 recent status", status: 201}, |
| + {name: "old status do not consume cap", status: 2, old: 998, wantComplete: true}, |
| + {name: "1000 old complete", old: 1000, wantComplete: true}, |
| + {name: "1000 truncated", old: 1000, truncated: true}, |
| + {name: "short truncated", old: 2, truncated: true}, |
| + {name: "missing modification retained", status: 201, missingMod: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var lists, gets int |
| + recent := haTestNow.Format(time.RFC3339) |
| + old := haTestNow.Add(-24*time.Hour - time.Nanosecond).Format(time.RFC3339Nano) |
| + ds := haS3(t, func(r *http.Request) (*http.Response, error) { |
| + var body string |
| + if r.URL.Query().Get("list-type") == "2" { |
| + lists++ |
| + q := r.URL.Query() |
| + if q.Get("continuation-token") != "" || q.Get("start-after") != "" { |
| + t.Error("unexpected pagination") |
| + } |
| + var objects []haXMLObject |
| + switch q.Get("prefix") { |
| + case edgesFilePrefix: |
| + if q.Get("max-keys") != "201" { |
| + t.Errorf("edges max-keys=%s", q.Get("max-keys")) |
| + } |
| + for i := 0; i < tc.edges; i++ { |
| + objects = append(objects, haXMLObject{Key: fmt.Sprintf("control/edges/box-%03d.json", i)}) |
| + } |
| + body = haListXML(objects, false) |
| + case haStatusPrefix: |
| + if q.Get("max-keys") != "1000" { |
| + t.Errorf("status max-keys=%s", q.Get("max-keys")) |
| + } |
| + for i := 0; i < tc.old; i++ { |
| + objects = append(objects, haXMLObject{Key: fmt.Sprintf("status/boxes/old-%03d.json", i), LastModified: &old}) |
| + } |
| + for i := 0; i < tc.status; i++ { |
| + var mod *string |
| + if !tc.missingMod { |
| + mod = &recent |
| + } |
| + objects = append(objects, haXMLObject{Key: fmt.Sprintf("status/boxes/live-%03d.json", i), LastModified: mod}) |
| + } |
| + body = haListXML(objects, tc.truncated) |
| + default: |
| + t.Fatalf("unexpected list %s", q.Get("prefix")) |
| + } |
| + } else { |
| + gets++ |
| + key := strings.TrimPrefix(r.URL.Path, "/control-test/") |
| + if strings.Contains(key, "old-") { |
| + t.Fatal("GET for old report") |
| + } |
| + if strings.HasPrefix(key, edgesFilePrefix) { |
| + body = `{"v":1,"capabilities":[]}` |
| + } else { |
| + ref, _ := haRef(key, haStatusPrefix) |
| + body = fmt.Sprintf(`{"label":%q,"generated_at":"2026-11-04T12:00:00Z"}`, ref) |
| + } |
| + } |
| + return haResponse(r, 200, io.NopCloser(strings.NewReader(body))), nil |
| + }) |
| + o := newHAObserver(haConfig(t), newHACapacityStore(ds, ""), boxid.Verifier{}, haTestFP) |
| + obs := haObserve(t, o) |
| + if got := obs.Regional("ie", haTestNow).Complete; got != tc.wantComplete { |
| + t.Fatalf("complete=%v unavailable=%s", got, obs.unavailable) |
| + } |
| + wantLists := 2 |
| + if tc.edges > 200 { |
| + wantLists = 1 |
| + } |
| + if lists != wantLists { |
| + t.Fatalf("LISTs=%d want=%d", lists, wantLists) |
| + } |
| + wantGets := 0 |
| + if tc.wantComplete { |
| + wantGets = tc.edges + tc.status |
| + } |
| + if gets != wantGets { |
| + t.Fatalf("GETs=%d want=%d", gets, wantGets) |
| + } |
| + }) |
| + } |
| +} |
| +func TestHACapacityBudgetMissingModAndHorizon(t *testing.T) { |
| + old := haTestNow.Add(-24*time.Hour - time.Nanosecond).Format(time.RFC3339Nano) |
| + exact := haTestNow.Add(-24 * time.Hour).Format(time.RFC3339Nano) |
| + var gets []string |
| + s := haS3(t, func(r *http.Request) (*http.Response, error) { |
| + if r.URL.Query().Get("list-type") == "2" { |
| + body := haListXML(nil, false) |
| + if r.URL.Query().Get("prefix") == haStatusPrefix { |
| + body = haListXML([]haXMLObject{{Key: haStatusPrefix + "old.json", LastModified: &old}, {Key: haStatusPrefix + "exact.json", LastModified: &exact}, {Key: haStatusPrefix + "missing.json"}}, false) |
| + } |
| + return haResponse(r, 200, io.NopCloser(strings.NewReader(body))), nil |
| + } |
| + key := strings.TrimPrefix(r.URL.Path, "/control-test/") |
| + gets = append(gets, key) |
| + ref, _ := haRef(key, haStatusPrefix) |
| + return haResponse(r, 200, io.NopCloser(strings.NewReader(fmt.Sprintf(`{"label":%q}`, ref)))), nil |
| + }) |
| + haObserve(t, newHAObserver(haConfig(t), newHACapacityStore(s, ""), boxid.Verifier{}, haTestFP)) |
| + if len(gets) != 2 || gets[0] != haStatusPrefix+"exact.json" || gets[1] != haStatusPrefix+"missing.json" { |
| + t.Fatalf("horizon GETs %v", gets) |
| + } |
| +} |
| +func TestHACapacityBudgetOneWireAttempt(t *testing.T) { |
| + for _, operation := range []string{"edges-list", "status-list", "get"} { |
| + t.Run(operation, func(t *testing.T) { |
| + calls := 0 |
| + s := haS3(t, func(r *http.Request) (*http.Response, error) { |
| + calls++ |
| + return haResponse(r, 503, io.NopCloser(strings.NewReader(`<Error><Code>SlowDown</Code><Message>test</Message></Error>`))), nil |
| + }) |
| + original := s.Client.Options().Retryer |
| + limited := newHACapacityStore(s, "").(*haCapacityStore) |
| + var err error |
| + switch operation { |
| + case "edges-list": |
| + _, err = limited.ListPage(context.Background(), edgesFilePrefix, "", 201) |
| + case "status-list": |
| + _, _, err = limited.haListStatus(context.Background()) |
| + case "get": |
| + _, _, err = limited.Get(context.Background(), edgesFilePrefix+"leo.json") |
| + } |
| + if err == nil || calls != 1 { |
| + t.Fatalf("calls=%d err=%v", calls, err) |
| + } |
| + if s.Client.Options().Retryer != original || s.Client == limited.s3.Client { |
| + t.Fatal("changed shared client") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type haBodyCounter struct { |
| + remaining, read int |
| + closed bool |
| +} |
| + |
| +func (b *haBodyCounter) Read(p []byte) (int, error) { |
| + if b.remaining == 0 { |
| + return 0, io.EOF |
| + } |
| + n := len(p) |
| + if n > b.remaining { |
| + n = b.remaining |
| + } |
| + for i := 0; i < n; i++ { |
| + p[i] = ' ' |
| + } |
| + b.read += n |
| + b.remaining -= n |
| + return n, nil |
| +} |
| +func (b *haBodyCounter) Close() error { b.closed = true; return nil } |
| +func TestHACapacityBudgetBodyTransportCaps(t *testing.T) { |
| + for _, key := range []string{edgesFilePrefix + "leo.json", haStatusPrefix + "leo.json", boxid.Key("leo")} { |
| + limit := haCapacityBodyLimit |
| + if strings.HasPrefix(key, boxid.Prefix) { |
| + limit = haCapacityIdentityLimit |
| + } |
| + for _, extra := range []int{0, 1, 100000} { |
| + t.Run(fmt.Sprintf("%s/%d", key, extra), func(t *testing.T) { |
| + counter := &haBodyCounter{remaining: limit + extra} |
| + s := haS3(t, func(r *http.Request) (*http.Response, error) { return haResponse(r, 200, counter), nil }) |
| + _, _, err := newHACapacityStore(s, "").Get(context.Background(), key) |
| + if (err == nil) != (extra == 0) { |
| + t.Fatalf("size=%d err=%v", limit+extra, err) |
| + } |
| + if counter.read > limit+1 || !counter.closed { |
| + t.Fatalf("transport read=%d closed=%v", counter.read, counter.closed) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| +func TestHACapacityBudgetActualReads(t *testing.T) { |
| + o, local, _ := haFixture(t) |
| + gets := map[string]int{} |
| + lists := map[string]int{} |
| + s := haS3(t, func(r *http.Request) (*http.Response, error) { |
| + if r.URL.Query().Get("list-type") == "2" { |
| + prefix := r.URL.Query().Get("prefix") |
| + lists[prefix]++ |
| + now := haTestNow.Format(time.RFC3339) |
| + return haResponse(r, 200, io.NopCloser(strings.NewReader(haListXML([]haXMLObject{{Key: prefix + "leo.json", LastModified: &now}}, false)))), nil |
| + } |
| + key := strings.TrimPrefix(r.URL.Path, "/control-test/") |
| + gets[key]++ |
| + b, _, err := local.Get(r.Context(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return haResponse(r, 200, io.NopCloser(strings.NewReader(string(b)))), nil |
| + }) |
| + o.store = newHACapacityStore(s, "") |
| + obs := haObserve(t, o) |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityAllow { |
| + t.Fatalf("transport fixture: %+v %+v", d, obs.Blockers("ie", haTestNow)) |
| + } |
| + if len(lists) != 2 || lists[edgesFilePrefix] != 1 || lists[haStatusPrefix] != 1 || len(gets) != 3 { |
| + t.Fatalf("lists=%v gets=%v", lists, gets) |
| + } |
| + for key, n := range gets { |
| + if n != 1 { |
| + t.Fatalf("%s fetched %d times", key, n) |
| + } |
| + } |
| + for i := 0; i < 100; i++ { |
| + obs.Decide("ie", "hapair", haTestNow) |
| + obs.Regional("ie", haTestNow) |
| + } |
| + if len(gets) != 3 || gets[boxid.Key("leo")] != 1 { |
| + t.Fatal("request path reloaded") |
| + } |
| +} |
| +func TestHACapacityBudgetDirectory(t *testing.T) { |
| + root := t.TempDir() |
| + s := release.NewDirStore(root) |
| + for i := 0; i < 202; i++ { |
| + key := fmt.Sprintf("status/boxes/old-%03d.json", i) |
| + haPut(t, s, key, []byte("malformed old report")) |
| + at := haTestNow.Add(-25 * time.Hour) |
| + if err := os.Chtimes(filepath.Join(root, key), at, at); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + haPut(t, s, haStatusPrefix+"live.json", []byte(`{"label":"live"}`)) |
| + o := newHAObserver(haConfig(t), newHACapacityStore(s, root), boxid.Verifier{}, haTestFP) |
| + if obs := haObserve(t, o); !obs.Regional("ie", haTestNow).Complete { |
| + t.Fatalf("old directory reports: %s", obs.unavailable) |
| + } |
| + for i := 202; i < 1001; i++ { |
| + haPut(t, s, fmt.Sprintf("status/boxes/old-%03d.json", i), []byte(`{}`)) |
| + } |
| + if obs := haObserve(t, o); obs.Regional("ie", haTestNow).Complete { |
| + t.Fatal("directory raw cap ignored") |
| + } |
| +} |
| + |
| +// haTestClock advances deadlines separately from scheduled ticks, so a missed |
| +// scheduler wakeup cannot accidentally refresh an expired observation. |
| +type haTestClock struct { |
| + mu sync.Mutex |
| + now time.Time |
| + tick chan time.Time |
| + deadlines []haTestDeadline |
| +} |
| +type haTestDeadline struct { |
| + at time.Time |
| + cancel context.CancelFunc |
| +} |
| + |
| +func newHATestClock() *haTestClock { |
| + return &haTestClock{now: haTestNow, tick: make(chan time.Time, 1)} |
| +} |
| +func (c *haTestClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now } |
| +func (c *haTestClock) Ticker(d time.Duration) (<-chan time.Time, func()) { |
| + if d != 60*time.Second { |
| + panic("wrong interval") |
| + } |
| + return c.tick, func() {} |
| +} |
| +func (c *haTestClock) Timeout(parent context.Context, d time.Duration) (context.Context, context.CancelFunc) { |
| + if d != 45*time.Second { |
| + panic("wrong timeout") |
| + } |
| + ctx, cancel := context.WithCancel(parent) |
| + c.mu.Lock() |
| + c.deadlines = append(c.deadlines, haTestDeadline{c.now.Add(d), cancel}) |
| + c.mu.Unlock() |
| + return ctx, cancel |
| +} |
| +func (c *haTestClock) advance(d time.Duration, tick bool) { |
| + c.mu.Lock() |
| + c.now = c.now.Add(d) |
| + now := c.now |
| + var cancels []context.CancelFunc |
| + var keep []haTestDeadline |
| + for _, deadline := range c.deadlines { |
| + if !deadline.at.After(now) { |
| + cancels = append(cancels, deadline.cancel) |
| + } else { |
| + keep = append(keep, deadline) |
| + } |
| + } |
| + c.deadlines = keep |
| + c.mu.Unlock() |
| + for _, cancel := range cancels { |
| + cancel() |
| + } |
| + if tick { |
| + c.tick <- now |
| + } |
| +} |
| + |
| +type haControlledStore struct { |
| + release.Store |
| + metadata haMetadataLister |
| + listCalls atomic.Int64 |
| + statusCalls atomic.Int64 |
| + blockAt int64 |
| + block, entered chan struct{} |
| + failAt int64 |
| +} |
| + |
| +func (s *haControlledStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) { |
| + n := s.listCalls.Add(1) |
| + if n == s.blockAt { |
| + close(s.entered) |
| + select { |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + case <-s.block: |
| + } |
| + } |
| + if n == s.failAt { |
| + return nil, errHACapacity |
| + } |
| + return s.Store.(release.PageLister).ListPage(ctx, prefix, after, limit) |
| +} |
| +func (s *haControlledStore) haListStatus(ctx context.Context) ([]haObject, bool, error) { |
| + s.statusCalls.Add(1) |
| + return s.metadata.haListStatus(ctx) |
| +} |
| +func haWait(t *testing.T, condition func() bool) { |
| + t.Helper() |
| + end := time.Now().Add(5 * time.Second) |
| + for !condition() { |
| + if time.Now().After(end) { |
| + t.Fatal("condition timed out") |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| +} |
| +func haAwait(t *testing.T, ch <-chan struct{}) { |
| + t.Helper() |
| + select { |
| + case <-ch: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("channel timed out") |
| + } |
| +} |
| +func haRunner(t *testing.T, o *haObserver, blockAt, failAt int64) (*haTestClock, *haControlledStore, context.CancelFunc, <-chan struct{}) { |
| + t.Helper() |
| + clock := newHATestClock() |
| + o.clock = clock |
| + store := &haControlledStore{Store: o.store, metadata: o.store.(haMetadataLister), blockAt: blockAt, failAt: failAt, block: make(chan struct{}), entered: make(chan struct{})} |
| + o.store = store |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := o.start(ctx) |
| + t.Cleanup(func() { cancel(); haAwait(t, done) }) |
| + return clock, store, cancel, done |
| +} |
| +func TestHACapacityRunner(t *testing.T) { |
| + o, _, _ := haFixture(t) |
| + clock, store, cancel, done := haRunner(t, o, 2, 0) |
| + s := &Server{} |
| + s.haCapacity.Store(o) |
| + haWait(t, func() bool { |
| + obs, ok := s.HACapacity() |
| + return ok && obs.Decide("ie", "hapair", clock.Now()).Kind == HACapacityAllow |
| + }) |
| + first, _ := s.HACapacity() |
| + // Idempotence includes a second caller carrying an already canceled context. |
| + canceled, stop := context.WithCancel(context.Background()) |
| + stop() |
| + if again := o.start(canceled); again != done { |
| + t.Fatal("second loop") |
| + } |
| + clock.advance(60*time.Second, true) |
| + haAwait(t, store.entered) |
| + clock.advance(time.Nanosecond, false) |
| + var wg sync.WaitGroup |
| + for i := 0; i < 50; i++ { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + obs, ok := s.HACapacity() |
| + if !ok || obs != first || obs.Decide("ie", "hapair", clock.Now()).Kind != HACapacityAllow { |
| + t.Error("in-flight pass lost prior generation") |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if store.listCalls.Load() != 2 { |
| + t.Fatalf("reader started a pass: %d", store.listCalls.Load()) |
| + } |
| + // A timed-out successor replaces success before its 120-second expiry. |
| + clock.advance(45*time.Second, false) |
| + haWait(t, func() bool { obs, ok := s.HACapacity(); return obs != first && !ok }) |
| + if obs, _ := s.HACapacity(); obs.Decide("ie", "hapair", clock.Now()).Kind != HACapacityUnknown { |
| + t.Fatal("timeout retained success") |
| + } |
| + cancel() |
| + haAwait(t, done) |
| + before := store.listCalls.Load() |
| + clock.advance(time.Minute, true) |
| + time.Sleep(5 * time.Millisecond) |
| + if store.listCalls.Load() != before { |
| + t.Fatal("shutdown left runner alive") |
| + } |
| +} |
| +func TestHACapacityRunnerErrorReplacesSuccess(t *testing.T) { |
| + o, _, _ := haFixture(t) |
| + clock, store, _, _ := haRunner(t, o, 0, 2) |
| + haWait(t, func() bool { return o.current.Load() != nil }) |
| + first := o.current.Load() |
| + clock.advance(time.Minute, true) |
| + haWait(t, func() bool { return o.current.Load() != first }) |
| + if obs := o.current.Load(); obs.available(clock.Now()) || obs.Decide("ie", "hapair", clock.Now()).Kind != HACapacityUnknown { |
| + t.Fatal("error retained success") |
| + } |
| + if store.listCalls.Load() != 2 { |
| + t.Fatal("error retried") |
| + } |
| + clock.advance(time.Minute, true) |
| + haWait(t, func() bool { return o.current.Load().available(clock.Now()) }) |
| + if store.listCalls.Load() != 3 { |
| + t.Fatal("recovery off schedule") |
| + } |
| +} |
| +func TestHACapacityRunnerMissedTickAndProducerAging(t *testing.T) { |
| + for _, producer := range []string{"edges", "status", "neither"} { |
| + t.Run(producer, func(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + if producer == "edges" { |
| + haPut(t, s, edgesFilePrefix+"leo.json", haEdit(t, haGolden(t), func(m map[string]any) { m["generation"] = haTestNow.Add(-14 * time.Minute).Format(time.RFC3339) })) |
| + } |
| + if producer == "status" { |
| + raw, _, _ := s.Get(context.Background(), haStatusPrefix+"leo.json") |
| + haPut(t, s, haStatusPrefix+"leo.json", haEdit(t, raw, func(m map[string]any) { m["generated_at"] = haTestNow.Add(-14 * time.Minute).Format(time.RFC3339) })) |
| + } |
| + clock, _, _, _ := haRunner(t, o, 0, 0) |
| + haWait(t, func() bool { return o.current.Load() != nil }) |
| + obs := o.current.Load() |
| + if d := obs.Decide("ie", "hapair", clock.Now()); d.Kind != HACapacityAllow { |
| + t.Fatalf("initial: %+v", d) |
| + } |
| + clock.advance(60*time.Second, false) |
| + if d := obs.Decide("ie", "hapair", clock.Now()); d.Kind != HACapacityAllow { |
| + t.Fatalf("exact producer age: %+v", d) |
| + } |
| + clock.advance(time.Nanosecond, false) |
| + want := HACapacityCompleteZero |
| + if producer == "neither" { |
| + want = HACapacityAllow |
| + } |
| + if d := obs.Decide("ie", "hapair", clock.Now()); d.Kind != want { |
| + t.Fatalf("producer aged: %+v", d) |
| + } |
| + clock.advance(60*time.Second-time.Nanosecond, false) |
| + if o.current.Load() != obs { |
| + t.Fatal("missed tick loaded") |
| + } |
| + if d := obs.Decide("ie", "hapair", clock.Now()); d.Kind != HACapacityUnknown { |
| + t.Fatalf("expiry: %+v", d) |
| + } |
| + }) |
| + } |
| +} |
| +func TestHACapacityRunnerHourlyBudget(t *testing.T) { |
| + root := t.TempDir() |
| + local := release.NewDirStore(root) |
| + o := newHAObserver(haConfig(t), newHACapacityStore(local, root), boxid.Verifier{}, haTestFP) |
| + clock, store, _, _ := haRunner(t, o, 0, 0) |
| + haWait(t, func() bool { return o.current.Load() != nil }) |
| + if store.listCalls.Load() != 1 || store.statusCalls.Load() != 1 { |
| + t.Fatal("initial pass did not cost two LISTs") |
| + } |
| + for i := 1; i <= 60; i++ { |
| + previous := o.current.Load() |
| + clock.advance(time.Minute, true) |
| + haWait(t, func() bool { return o.current.Load() != previous }) |
| + } |
| + if store.listCalls.Load() != 61 || store.statusCalls.Load() != 61 { |
| + t.Fatalf("initial + 60: edges=%d status=%d", store.listCalls.Load(), store.statusCalls.Load()) |
| + } |
| +} |
| +func TestHACapacityStartup(t *testing.T) { |
| + root := t.TempDir() |
| + local := release.NewDirStore(root) |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{Releases: local, Tweak: func(c *Config) { |
| + c.HARegions = []string{"ie"} |
| + c.HomeRegion = "ie" |
| + c.HACapacityConfig = haTestConfig |
| + c.HACapacityDirectory = root |
| + c.AWSAccount = moveTestAccount |
| + c.SecretsPub = testKeyPub |
| + }}) |
| + if fx.srv.haCapacity.Load() != nil { |
| + t.Fatal("NewServer started observer") |
| + } |
| + if _, ok := fx.srv.HACapacity(); ok { |
| + t.Fatal("before first pass available") |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + done := fx.srv.StartHACapacityObservation(ctx) |
| + if fx.srv.StartHACapacityObservation(ctx) != done { |
| + t.Fatal("second start") |
| + } |
| + haWait(t, func() bool { _, ok := fx.srv.HACapacity(); return ok }) |
| + cancel() |
| + haAwait(t, done) |
| + invalid := &Server{cfg: Config{HARegions: []string{"ie"}, HomeRegion: "ie"}} |
| + done = invalid.StartHACapacityObservation(context.Background()) |
| + haAwait(t, done) |
| + if _, ok := invalid.HACapacity(); ok { |
| + t.Fatal("invalid config available") |
| + } |
| +} |
| +func TestHACapacityUnknownUnsupportedStore(t *testing.T) { |
| + local := release.NewDirStore(t.TempDir()) |
| + // Hiding optional interfaces must not invoke the unbounded List fallback. |
| + hidden := struct{ release.Store }{local} |
| + o := newHAObserver(haConfig(t), hidden, boxid.Verifier{}, haTestFP) |
| + if obs := haObserve(t, o); obs.available(haTestNow) { |
| + t.Fatal("unsupported store available") |
| + } |
| +} |
diff --git a/internal/console/hacapacity_test.go b/internal/console/hacapacity_test.go| new file mode 100644 |
| index 000000000..611fb8ada |
| --- /dev/null |
| +++ b/internal/console/hacapacity_test.go |
| @@ -0,0 +1,527 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const haTestConfig = `{"v":1,"regions":{"ie":{"aws_region":"eu-west-1","data_bucket":"test-data","data_bucket_region":"eu-west-1"},"de":{"aws_region":"eu-central-1","data_bucket":"test-de","data_bucket_region":"eu-central-1"}},"fixed_boxes":{"leo":{"region_code":"ie","instance_id":"i-0123456789abcdef0"}}}` |
| + |
| +var haTestNow = time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) |
| + |
| +const haTestFP = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" |
| + |
| +func haConfig(t *testing.T) *haCapacityConfig { |
| + t.Helper() |
| + c, err := parseHACapacityConfig(haTestConfig, []string{"ie", "de"}, "ie") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c |
| +} |
| +func haPut(t *testing.T, s release.Store, key string, body []byte) { |
| + t.Helper() |
| + _, etag, _ := s.Get(context.Background(), key) |
| + if _, err := s.Put(context.Background(), key, body, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func haGolden(t *testing.T) []byte { |
| + t.Helper() |
| + b, e := os.ReadFile("../host/testdata/edges-p2b-golden.json") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return b |
| +} |
| +func haEdit(t *testing.T, b []byte, edit func(map[string]any)) []byte { |
| + t.Helper() |
| + var m map[string]any |
| + if e := json.Unmarshal(b, &m); e != nil { |
| + t.Fatal(e) |
| + } |
| + edit(m) |
| + b, e := json.Marshal(m) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return b |
| +} |
| +func haFixture(t *testing.T) (*haObserver, *release.DirStore, *boxidtest.Signer) { |
| + t.Helper() |
| + root := t.TempDir() |
| + s := release.NewDirStore(root) |
| + signer := boxidtest.NewSigner(t) |
| + haPut(t, s, "control/edges/leo.json", haGolden(t)) |
| + haPut(t, s, "status/boxes/leo.json", []byte(`{"label":"leo","generated_at":"2026-11-04T12:00:00Z","metrics":{"instance_id":"i-0123456789abcdef0"}}`)) |
| + rec, _ := signer.Record(t, "leo", moveTestAccount, "eu-west-1", "i-0123456789abcdef0") |
| + if e := boxid.Publish(context.Background(), s, rec); e != nil { |
| + t.Fatal(e) |
| + } |
| + o := newHAObserver(haConfig(t), newHACapacityStore(s, root), boxid.Verifier{Account: moveTestAccount, Certs: signer.Certs()}, haTestFP) |
| + return o, s, signer |
| +} |
| +func haObserve(t *testing.T, o *haObserver) *HACapacityObservation { |
| + t.Helper() |
| + return o.observe(context.Background(), haTestNow) |
| +} |
| +func TestHACapacityConfiguredUniverse(t *testing.T) { |
| + c := haConfig(t) |
| + root := t.TempDir() |
| + s := release.NewDirStore(root) |
| + o := newHAObserver(c, newHACapacityStore(s, root), boxid.Verifier{}, haTestFP) |
| + obs := haObserve(t, o) |
| + for _, r := range []string{"ie", "de"} { |
| + if v := obs.Regional(r, haTestNow); v.Count != 0 || !v.Complete { |
| + t.Fatalf("%s: %+v", r, v) |
| + } |
| + } |
| + for _, raw := range []string{"", "null", strings.Replace(haTestConfig, `"v":1`, `"v":2`, 1), strings.Replace(haTestConfig, `"v":1`, `"v":1,"v":1`, 1), strings.Replace(haTestConfig, `"aws_region":"eu-west-1"`, `"aws_region":null`, 1), strings.Replace(haTestConfig, `"v":1`, `"unknown":1,"v":1`, 1)} { |
| + if _, err := parseHACapacityConfig(raw, []string{"ie"}, "ie"); err == nil { |
| + t.Errorf("accepted %s", raw) |
| + } |
| + } |
| +} |
| +func TestHACapacityIdentityAndScope(t *testing.T) { |
| + o, _, _ := haFixture(t) |
| + obs := haObserve(t, o) |
| + if v := obs.Regional("ie", haTestNow); v.Count != 1 || !v.Complete { |
| + t.Fatalf("golden: %+v", v) |
| + } |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityAllow { |
| + t.Fatalf("golden decision: %+v", d) |
| + } |
| + if d := obs.Decide("ie", "", haTestNow); d.Kind != HACapacityCompleteZero { |
| + t.Fatalf("shared: %+v", d) |
| + } |
| + if v := obs.Regional("de", haTestNow); !v.Complete || v.Count != 0 { |
| + t.Fatalf("absent region: %+v", v) |
| + } |
| +} |
| +func TestHACapacityUnknownIsNotZero(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + if e := s.Delete(context.Background(), "status/boxes/leo.json"); e != nil { |
| + t.Fatal(e) |
| + } |
| + obs := haObserve(t, o) |
| + if v := obs.Regional("ie", haTestNow); v.Complete { |
| + t.Fatalf("missing status: %+v", v) |
| + } |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("missing status: %+v", d) |
| + } |
| + haPut(t, s, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { m["generation"] = haTestNow.Add(-25 * time.Hour).Format(time.RFC3339) })) |
| + if v := haObserve(t, o).Regional("ie", haTestNow); !v.Complete || v.Count != 0 { |
| + t.Fatalf("self-stale: %+v", v) |
| + } |
| +} |
| +func TestHACapacityBudget(t *testing.T) { |
| + o, _, _ := haFixture(t) |
| + obs := haObserve(t, o) |
| + if obs.ID() == "" { |
| + t.Fatal("missing observation identifier") |
| + } |
| + if v := obs.Regional("ie", haTestNow.Add(120*time.Second)); v.Complete { |
| + t.Fatalf("expired observation: %+v", v) |
| + } |
| +} |
| + |
| +func TestHACapacityConfiguredUniverseStrict(t *testing.T) { |
| + cases := map[string]string{ |
| + "case alias": strings.Replace(haTestConfig, `"v":1`, `"V":1`, 1), |
| + "case duplicate": strings.Replace(haTestConfig, `"v":1`, `"v":1,"V":1`, 1), |
| + "nested case alias": strings.Replace(haTestConfig, `"aws_region"`, `"AWS_REGION"`, 1), |
| + "fixed case alias": strings.Replace(haTestConfig, `"instance_id"`, `"Instance_ID"`, 1), |
| + "unknown nested": strings.Replace(haTestConfig, `"aws_region":"eu-west-1"`, `"extra":true,"aws_region":"eu-west-1"`, 1), |
| + "duplicate nested": strings.Replace(haTestConfig, `"data_bucket":"test-data"`, `"data_bucket":"test-data","data_bucket":"test-data"`, 1), |
| + "empty coordinate": strings.Replace(haTestConfig, `"data_bucket":"test-data"`, `"data_bucket":""`, 1), |
| + "bad bucket": strings.Replace(haTestConfig, `"data_bucket":"test-data"`, `"data_bucket":"bad/bucket"`, 1), |
| + "bad aws region": strings.Replace(haTestConfig, `"eu-west-1"`, `"../west"`, 1), |
| + "bad region": strings.Replace(haTestConfig, `"ie":`, `"IE":`, 1), |
| + "bad reference": strings.Replace(haTestConfig, `"leo":`, `"../leo":`, 1), |
| + "bad iid": strings.Replace(haTestConfig, `i-0123456789abcdef0`, `oops`, 1), |
| + "missing field": strings.Replace(haTestConfig, `"fixed_boxes":{"leo":{"region_code":"ie","instance_id":"i-0123456789abcdef0"}}`, `"fixed_boxes":{}`, 1), |
| + "absent fixed map": strings.Replace(haTestConfig, `,"fixed_boxes":{"leo":{"region_code":"ie","instance_id":"i-0123456789abcdef0"}}`, ``, 1), |
| + "null map": strings.Replace(haTestConfig, `"fixed_boxes":{"leo":{"region_code":"ie","instance_id":"i-0123456789abcdef0"}}`, `"fixed_boxes":null`, 1), |
| + "duplicate binding": strings.Replace(haTestConfig, `"fixed_boxes":{`, `"fixed_boxes":{"sophie":{"region_code":"ie","instance_id":"i-0123456789abcdef0"},`, 1), |
| + "trailing": haTestConfig + ` {}`, |
| + "oversize": haTestConfig + strings.Repeat(" ", haCapacityIdentityLimit), |
| + } |
| + // An empty pin map is legal: pins bind identities, not membership. |
| + delete(cases, "missing field") |
| + for name, raw := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + if _, err := parseHACapacityConfig(raw, []string{"ie"}, "ie"); err == nil { |
| + t.Fatal("accepted invalid config") |
| + } |
| + }) |
| + } |
| + if _, err := parseHACapacityConfig(haTestConfig, []string{"missing"}, "ie"); err == nil { |
| + t.Fatal("missing configured region accepted") |
| + } |
| + for _, home := range []string{"", "IE", "../../ie"} { |
| + if _, err := parseHACapacityConfig(haTestConfig, []string{"ie"}, home); err == nil { |
| + t.Fatal("invalid home accepted") |
| + } |
| + } |
| + padded := haTestConfig + strings.Repeat(" ", haCapacityIdentityLimit-len(haTestConfig)) |
| + if _, err := parseHACapacityConfig(padded, []string{"ie"}, "ie"); err != nil { |
| + t.Fatal("exact 64KiB rejected") |
| + } |
| + for _, n := range []int{200, 201} { |
| + var m map[string]any |
| + json.Unmarshal([]byte(haTestConfig), &m) |
| + pins := map[string]any{} |
| + for i := 0; i < n; i++ { |
| + pins[fmt.Sprintf("box-%d", i)] = map[string]any{"region_code": "ie", "instance_id": fmt.Sprintf("i-%017x", i)} |
| + } |
| + m["fixed_boxes"] = pins |
| + b, _ := json.Marshal(m) |
| + _, err := parseHACapacityConfig(string(b), []string{"ie"}, "ie") |
| + if (err == nil) != (n == 200) { |
| + t.Fatalf("%d pins: %v", n, err) |
| + } |
| + } |
| +} |
| +func TestHACapacityIdentityAndScopePrecedence(t *testing.T) { |
| + type testCase struct { |
| + name string |
| + edit func(map[string]any) |
| + kind HACapacityDecisionKind |
| + count int |
| + complete bool |
| + noStatus bool |
| + } |
| + tests := []testCase{ |
| + {"omitted placement", func(m map[string]any) { delete(m, "placement") }, HACapacityAllow, 1, true, false}, |
| + {"empty placement", func(m map[string]any) { m["placement"] = "" }, HACapacityAllow, 1, true, false}, |
| + {"null placement", func(m map[string]any) { m["placement"] = nil }, HACapacityUnknown, 0, false, false}, |
| + {"malformed placement", func(m map[string]any) { m["placement"] = 42 }, HACapacityUnknown, 0, false, false}, |
| + {"home must stay empty", func(m map[string]any) { m["placement"] = "ie" }, HACapacityCompleteZero, 0, true, true}, |
| + {"other placement", func(m map[string]any) { m["placement"] = "fr" }, HACapacityCompleteZero, 0, true, true}, |
| + {"other data bucket", func(m map[string]any) { m["data_bucket"] = "other-data" }, HACapacityCompleteZero, 0, true, true}, |
| + {"other data region", func(m map[string]any) { m["data_bucket_region"] = "us-east-1" }, HACapacityCompleteZero, 0, true, true}, |
| + {"other fingerprint", func(m map[string]any) { m["secrets_key_fp"] = "sha256:" + strings.Repeat("b", 64) }, HACapacityCompleteZero, 0, true, true}, |
| + {"malformed fingerprint", func(m map[string]any) { m["secrets_key_fp"] = "bad" }, HACapacityUnknown, 0, false, false}, |
| + {"null bucket", func(m map[string]any) { m["data_bucket"] = nil }, HACapacityUnknown, 0, false, false}, |
| + {"no HA neighbor", func(m map[string]any) { m["capabilities"] = []string{}; delete(m, "admitted"); m["placement"] = nil }, HACapacityCompleteZero, 0, true, true}, |
| + {"no hibernation", func(m map[string]any) { m["hibernation_configured"] = false; delete(m, "admitted") }, HACapacityCompleteZero, 0, true, true}, |
| + {"unknown version", func(m map[string]any) { m["v"] = 2 }, HACapacityUnknown, 0, false, false}, |
| + {"old edge no status", func(m map[string]any) { |
| + m["generation"] = haTestNow.Add(-15*time.Minute - time.Nanosecond).Format(time.RFC3339Nano) |
| + }, HACapacityCompleteZero, 0, true, true}, |
| + {"edge exact age", func(m map[string]any) { m["generation"] = haTestNow.Add(-15 * time.Minute).Format(time.RFC3339) }, HACapacityAllow, 1, true, false}, |
| + {"edge exact skew", func(m map[string]any) { m["generation"] = haTestNow.Add(time.Minute).Format(time.RFC3339) }, HACapacityAllow, 1, true, false}, |
| + {"edge excessive skew", func(m map[string]any) { |
| + m["generation"] = haTestNow.Add(time.Minute + time.Nanosecond).Format(time.RFC3339Nano) |
| + }, HACapacityUnknown, 0, false, false}, |
| + {"zero edge time", func(m map[string]any) { m["generation"] = "0001-01-01T00:00:00Z" }, HACapacityUnknown, 0, false, false}, |
| + {"missing generation", func(m map[string]any) { delete(m, "generation") }, HACapacityUnknown, 0, false, false}, |
| + {"box mismatch", func(m map[string]any) { m["box"] = "sophie" }, HACapacityUnknown, 0, false, false}, |
| + {"box id mismatch", func(m map[string]any) { m["box_id"] = "sophie" }, HACapacityUnknown, 0, false, false}, |
| + {"wire AWS conflict", func(m map[string]any) { m["region"] = "us-east-1" }, HACapacityUnknown, 0, false, false}, |
| + {"booting", func(m map[string]any) { m["box_role"] = "booting" }, HACapacityCompleteZero, 0, true, false}, |
| + {"drain", func(m map[string]any) { m["box_role"] = "drain" }, HACapacityCompleteZero, 0, true, false}, |
| + {"platform", func(m map[string]any) { m["box_role"] = "platform" }, HACapacityCompleteZero, 0, true, false}, |
| + {"unknown role", func(m map[string]any) { m["box_role"] = "new-role" }, HACapacityUnknown, 0, false, false}, |
| + {"missing role", func(m map[string]any) { delete(m, "box_role") }, HACapacityUnknown, 0, false, false}, |
| + {"missing admitted", func(m map[string]any) { delete(m, "admitted") }, HACapacityUnknown, 0, false, false}, |
| + {"null drained", func(m map[string]any) { m["drained"] = nil }, HACapacityUnknown, 0, false, false}, |
| + {"bad boolean", func(m map[string]any) { m["admitted"] = "true" }, HACapacityUnknown, 0, false, false}, |
| + {"not admitted", func(m map[string]any) { m["admitted"] = false }, HACapacityCompleteZero, 0, true, false}, |
| + {"drained", func(m map[string]any) { m["drained"] = true }, HACapacityCompleteZero, 0, true, false}, |
| + {"legacy draining", func(m map[string]any) { m["draining"] = true }, HACapacityCompleteZero, 0, true, false}, |
| + {"malformed legacy draining", func(m map[string]any) { m["draining"] = nil }, HACapacityUnknown, 0, false, false}, |
| + {"absent headroom", func(m map[string]any) { delete(m, "headroom") }, HACapacityCompleteZero, 0, true, false}, |
| + {"absent totals", func(m map[string]any) { m["headroom"] = map[string]any{} }, HACapacityCompleteZero, 0, true, false}, |
| + {"exact headroom", func(m map[string]any) { |
| + m["headroom"] = map[string]any{"mem_total_mib": 100, "mem_free_mib": 15, "disk_total_mib": 100, "disk_free_mib": 10} |
| + }, HACapacityAllow, 1, true, false}, |
| + {"low memory", func(m map[string]any) { m["headroom"].(map[string]any)["mem_free_mib"] = 153 }, HACapacityCompleteZero, 0, true, false}, |
| + {"low disk", func(m map[string]any) { m["headroom"].(map[string]any)["disk_free_mib"] = 409 }, HACapacityCompleteZero, 0, true, false}, |
| + {"inconsistent zero total", func(m map[string]any) { m["headroom"].(map[string]any)["mem_total_mib"] = 0 }, HACapacityUnknown, 0, false, false}, |
| + {"negative total", func(m map[string]any) { m["headroom"].(map[string]any)["mem_total_mib"] = -1 }, HACapacityUnknown, 0, false, false}, |
| + {"free exceeds total", func(m map[string]any) { m["headroom"].(map[string]any)["mem_free_mib"] = 1025 }, HACapacityUnknown, 0, false, false}, |
| + {"overflow", func(m map[string]any) { |
| + m["headroom"].(map[string]any)["mem_total_mib"] = json.Number("9223372036854775807") |
| + }, HACapacityUnknown, 0, false, false}, |
| + {"fraction", func(m map[string]any) { m["headroom"].(map[string]any)["mem_free_mib"] = 0.5 }, HACapacityUnknown, 0, false, false}, |
| + {"null headroom number", func(m map[string]any) { m["headroom"].(map[string]any)["disk_free_mib"] = nil }, HACapacityUnknown, 0, false, false}, |
| + {"closed inbound", func(m map[string]any) { m["accepts_inbound"] = false }, HACapacityCompleteZero, 1, true, false}, |
| + {"missing inbound", func(m map[string]any) { delete(m, "accepts_inbound") }, HACapacityUnknown, 1, true, false}, |
| + {"empty pools", func(m map[string]any) { m["named_pools"] = []string{} }, HACapacityCompleteZero, 1, true, false}, |
| + {"missing pools", func(m map[string]any) { delete(m, "named_pools") }, HACapacityUnknown, 1, true, false}, |
| + {"null pools", func(m map[string]any) { m["named_pools"] = nil }, HACapacityUnknown, 1, true, false}, |
| + {"wrong pools type", func(m map[string]any) { m["named_pools"] = "hapair" }, HACapacityUnknown, 1, true, false}, |
| + {"invalid pool name", func(m map[string]any) { m["named_pools"] = []string{"../pool"} }, HACapacityUnknown, 1, true, false}, |
| + } |
| + // Reuse the signed fixture: every subtest changes serialized evidence, then |
| + // calls the production store/decoder/verifier path anew. |
| + o, s, _ := haFixture(t) |
| + statusRaw, _, _ := s.Get(context.Background(), haStatusPrefix+"leo.json") |
| + identityRaw, _, _ := s.Get(context.Background(), boxid.Key("leo")) |
| + for _, tt := range tests { |
| + t.Run(tt.name, func(t *testing.T) { |
| + haPut(t, s, haStatusPrefix+"leo.json", statusRaw) |
| + haPut(t, s, boxid.Key("leo"), identityRaw) |
| + if tt.noStatus { |
| + s.Delete(context.Background(), haStatusPrefix+"leo.json") |
| + s.Delete(context.Background(), boxid.Key("leo")) |
| + } |
| + haPut(t, s, edgesFilePrefix+"leo.json", haEdit(t, haGolden(t), tt.edit)) |
| + obs := haObserve(t, o) |
| + v := obs.Regional("ie", haTestNow) |
| + d := obs.Decide("ie", "hapair", haTestNow) |
| + if v.Count != tt.count || v.Complete != tt.complete || d.Kind != tt.kind { |
| + t.Fatalf("regional=%+v decision=%+v blockers=%+v", v, d, obs.Blockers("ie", haTestNow)) |
| + } |
| + if d.MissingNamedPoolsOnly != (tt.name == "missing pools") { |
| + t.Fatalf("missing pool discriminator: %+v", d) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestHACapacityIdentityAndScopeSignedEvidence(t *testing.T) { |
| + o, s, signer := haFixture(t) |
| + original, _, _ := s.Get(context.Background(), boxid.Key("leo")) |
| + for _, tt := range []struct { |
| + name, account, region, instance string |
| + want HACapacityDecisionKind |
| + }{ |
| + {"wrong account", "999988887777", "eu-west-1", "i-0123456789abcdef0", HACapacityCompleteZero}, |
| + {"wrong signed region", moveTestAccount, "us-east-1", "i-0123456789abcdef0", HACapacityCompleteZero}, |
| + {"copied signed identity", moveTestAccount, "eu-west-1", "i-0123456789abcdef1", HACapacityUnknown}, |
| + } { |
| + t.Run(tt.name, func(t *testing.T) { |
| + _, raw := signer.Record(t, "leo", tt.account, tt.region, tt.instance) |
| + haPut(t, s, boxid.Key("leo"), raw) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != tt.want { |
| + t.Fatalf("%+v", d) |
| + } |
| + }) |
| + } |
| + haPut(t, s, boxid.Key("leo"), []byte(`{"v":1,"box":"leo","identity_document":"bad","identity_signature":"bad"}`)) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityCompleteZero { |
| + t.Fatalf("invalid signature: %+v", d) |
| + } |
| + haPut(t, s, boxid.Key("leo"), original) |
| + delete(o.config.FixedBoxes, "leo") |
| + obs := haObserve(t, o) |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityCompleteZero { |
| + t.Fatalf("unbound: %+v", d) |
| + } |
| + if b := obs.Blockers("ie", haTestNow); len(b) != 1 || b[0].Code != "identity_unbound" { |
| + t.Fatalf("unbound diagnostic: %+v", b) |
| + } |
| + // A copied identity under a second ref makes the entire affected set unknown, |
| + // including the valid fixed pin. Merely excluding the unbound alias is unsafe. |
| + o.config.FixedBoxes["leo"] = haFixedBox{"ie", "i-0123456789abcdef0"} |
| + haPut(t, s, edgesFilePrefix+"alias.json", haEdit(t, haGolden(t), func(m map[string]any) { m["box"] = "alias"; m["box_id"] = "alias" })) |
| + _, alias := signer.Record(t, "alias", moveTestAccount, "eu-west-1", "i-0123456789abcdef0") |
| + haPut(t, s, boxid.Key("alias"), alias) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("duplicate iid: %+v", d) |
| + } |
| +} |
| +func TestHACapacityIdentityAndScopeStatus(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + original, _, _ := s.Get(context.Background(), haStatusPrefix+"leo.json") |
| + for _, tt := range []struct { |
| + name string |
| + edit func(map[string]any) |
| + want HACapacityDecisionKind |
| + }{ |
| + {"empty iid", func(m map[string]any) { m["metrics"] = map[string]any{"instance_id": ""} }, HACapacityUnknown}, |
| + {"absent metrics", func(m map[string]any) { delete(m, "metrics") }, HACapacityUnknown}, |
| + {"wrong iid", func(m map[string]any) { m["metrics"] = map[string]any{"instance_id": "i-0123456789abcdef1"} }, HACapacityUnknown}, |
| + {"wrong label", func(m map[string]any) { m["label"] = "elsewhere" }, HACapacityUnknown}, |
| + {"malformed time", func(m map[string]any) { m["generated_at"] = "bad" }, HACapacityUnknown}, |
| + {"zero generation", func(m map[string]any) { m["generated_at"] = "0001-01-01T00:00:00Z" }, HACapacityUnknown}, |
| + {"future", func(m map[string]any) { |
| + m["generated_at"] = haTestNow.Add(time.Minute + time.Nanosecond).Format(time.RFC3339Nano) |
| + }, HACapacityUnknown}, |
| + {"exact future", func(m map[string]any) { m["generated_at"] = haTestNow.Add(time.Minute).Format(time.RFC3339) }, HACapacityAllow}, |
| + {"exact age", func(m map[string]any) { m["generated_at"] = haTestNow.Add(-15 * time.Minute).Format(time.RFC3339) }, HACapacityAllow}, |
| + {"stale", func(m map[string]any) { |
| + m["generated_at"] = haTestNow.Add(-15*time.Minute - time.Nanosecond).Format(time.RFC3339Nano) |
| + }, HACapacityCompleteZero}, |
| + } { |
| + t.Run(tt.name, func(t *testing.T) { |
| + haPut(t, s, haStatusPrefix+"leo.json", haEdit(t, original, tt.edit)) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != tt.want { |
| + t.Fatalf("%+v", d) |
| + } |
| + }) |
| + } |
| + haPut(t, s, haStatusPrefix+"leo.json", original) |
| + haPut(t, s, haStatusPrefix+"duplicate.json", original) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("duplicate label: %+v", d) |
| + } |
| +} |
| +func TestHACapacityUnknownIsNotZeroMixed(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + haPut(t, s, edgesFilePrefix+"unknown.json", []byte(`{"v":1,"placement":""}`)) |
| + obs := haObserve(t, o) |
| + if v := obs.Regional("ie", haTestNow); v.Count != 1 || v.Complete { |
| + t.Fatalf("positive plus unknown metric: %+v", v) |
| + } |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityAllow { |
| + t.Fatalf("positive witness lost: %+v", d) |
| + } |
| + if d := obs.Decide("ie", "other", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("no positive witness: %+v", d) |
| + } |
| + s.Delete(context.Background(), edgesFilePrefix+"unknown.json") |
| + haPut(t, s, edgesFilePrefix+"leo.json", haEdit(t, haGolden(t), func(m map[string]any) { delete(m, "named_pools"); m["serves_shared_pool"] = true })) |
| + obs = haObserve(t, o) |
| + if d := obs.Decide("ie", "", haTestNow); d.Kind != HACapacityAllow { |
| + t.Fatalf("old publisher shared: %+v", d) |
| + } |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown || !d.MissingNamedPoolsOnly { |
| + t.Fatalf("old publisher named: %+v", d) |
| + } |
| + if v := obs.Regional("ie", haTestNow); v.Count != 1 || !v.Complete { |
| + t.Fatalf("old publisher metric: %+v", v) |
| + } |
| +} |
| +func TestHACapacityGroupReferenceGolden(t *testing.T) { |
| + // Same vector as host.TestGroupBoxReferenceGolden, whose unexported |
| + // derivation is deliberately kept out of console's dependency graph. |
| + if got := haGroupReference("123456789012", "i-0a61f580df1acfa65"); got != "g-c48ba25b2d17574d23d9" { |
| + t.Fatal(got) |
| + } |
| + o, s, signer := haFixture(t) |
| + s.Delete(context.Background(), edgesFilePrefix+"leo.json") |
| + ref := haGroupReference(moveTestAccount, "i-0123456789abcdef0") |
| + haPut(t, s, edgesFilePrefix+ref+".json", haEdit(t, haGolden(t), func(m map[string]any) { |
| + m["box"] = ref |
| + m["box_id"] = ref |
| + m["box_role"] = "booting" |
| + m["admitted"] = false |
| + })) |
| + _, raw := signer.Record(t, ref, moveTestAccount, "eu-west-1", "i-0123456789abcdef0") |
| + haPut(t, s, boxid.Key(ref), raw) |
| + haPut(t, s, haStatusPrefix+ref+".json", []byte(fmt.Sprintf(`{"label":%q,"generated_at":"2026-11-04T12:00:00Z","metrics":{"instance_id":"i-0123456789abcdef0"}}`, ref))) |
| + obs := haObserve(t, o) |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityCompleteZero { |
| + t.Fatalf("group not yet admitted: %+v", d) |
| + } |
| + if b := obs.Blockers("ie", haTestNow); len(b) != 1 || b[0].Code != "admission_excluded" { |
| + t.Fatalf("group binding failed: %+v", b) |
| + } |
| +} |
| + |
| +func TestHACapacityUnknownIsNotZeroMalformed(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + keys := []string{edgesFilePrefix + "leo.json", haStatusPrefix + "leo.json", boxid.Key("leo")} |
| + original := map[string][]byte{} |
| + for _, key := range keys { |
| + b, _, _ := s.Get(context.Background(), key) |
| + original[key] = b |
| + } |
| + for _, key := range keys { |
| + t.Run(key, func(t *testing.T) { |
| + limit := haCapacityBodyLimit |
| + if key == boxid.Key("leo") { |
| + limit = haCapacityIdentityLimit |
| + } |
| + haPut(t, s, key, []byte(strings.Repeat(" ", limit+1))) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("oversize became zero: %+v", d) |
| + } |
| + haPut(t, s, key, original[key]) |
| + }) |
| + } |
| + for name, raw := range map[string][]byte{ |
| + "duplicate field": []byte(`{"v":1,"capabilities":["region-ha-1"],"capabilities":[]}`), |
| + "invalid JSON": []byte(`{`), |
| + "null body": []byte(`null`), |
| + "null capability member": haEdit(t, haGolden(t), func(m map[string]any) { m["capabilities"] = []any{nil} }), |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + haPut(t, s, keys[0], raw) |
| + if v := haObserve(t, o).Regional("ie", haTestNow); v.Complete { |
| + t.Fatalf("malformed classified: %+v", v) |
| + } |
| + }) |
| + } |
| + haPut(t, s, keys[0], original[keys[0]]) |
| + haPut(t, s, keys[2], haEdit(t, original[keys[2]], func(m map[string]any) { m["v"] = 2 })) |
| + if d := haObserve(t, o).Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("unknown identity version: %+v", d) |
| + } |
| +} |
| + |
| +func TestHACapacityIdentityAndScopeDuplicateRef(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + haPut(t, s, edgesFilePrefix+"alias.json", haGolden(t)) |
| + obs := haObserve(t, o) |
| + if v := obs.Regional("ie", haTestNow); v.Count != 0 || v.Complete { |
| + t.Fatalf("duplicate published reference: %+v", v) |
| + } |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("conflicting ref admitted: %+v", d) |
| + } |
| +} |
| +func TestHACapacityUnknownIsNotZeroScoped(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + s.Delete(context.Background(), haStatusPrefix+"leo.json") |
| + obs := haObserve(t, o) |
| + if v := obs.Regional("ie", haTestNow); v.Complete { |
| + t.Fatal("missing report did not affect home") |
| + } |
| + if v := obs.Regional("de", haTestNow); !v.Complete || v.Count != 0 { |
| + t.Fatalf("scoped failure affected other region: %+v", v) |
| + } |
| + // An unassignable key can hide evidence of any configured region. |
| + haPut(t, s, edgesFilePrefix+"bad.key.json", haGolden(t)) |
| + if v := haObserve(t, o).Regional("de", haTestNow); v.Complete { |
| + t.Fatal("unassignable key ignored") |
| + } |
| +} |
| +func TestHACapacityIdentityAndScopeMixedPublishers(t *testing.T) { |
| + o, s, signer := haFixture(t) |
| + haPut(t, s, edgesFilePrefix+"sophie.json", haEdit(t, haGolden(t), func(m map[string]any) { m["box"] = "sophie"; m["box_id"] = "sophie"; delete(m, "named_pools") })) |
| + o.config.FixedBoxes["sophie"] = haFixedBox{"ie", "i-0123456789abcdef1"} |
| + _, raw := signer.Record(t, "sophie", moveTestAccount, "eu-west-1", "i-0123456789abcdef1") |
| + haPut(t, s, boxid.Key("sophie"), raw) |
| + haPut(t, s, haStatusPrefix+"sophie.json", []byte(`{"label":"sophie","generated_at":"2026-11-04T12:00:00Z","metrics":{"instance_id":"i-0123456789abcdef1"}}`)) |
| + obs := haObserve(t, o) |
| + if v := obs.Regional("ie", haTestNow); v.Count != 2 || !v.Complete { |
| + t.Fatalf("mixed metric: %+v", v) |
| + } |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityAllow { |
| + t.Fatalf("new positive: %+v", d) |
| + } |
| + if d := obs.Decide("ie", "other", haTestNow); d.Kind != HACapacityUnknown || !d.MissingNamedPoolsOnly { |
| + t.Fatalf("old missing publication: %+v", d) |
| + } |
| + if b := obs.CreateBlockers("ie", "hapair", haTestNow); len(b) != 1 || b[0].Code != "named_pools_missing" { |
| + t.Fatalf("pool diagnostics: %+v", b) |
| + } |
| +} |
| + |
| +func TestHACapacityIdentityAndScopeStatusLabelAlias(t *testing.T) { |
| + o, s, _ := haFixture(t) |
| + if err := s.Delete(context.Background(), haStatusPrefix+"leo.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + // encoding/json matches exported struct fields case-insensitively. The |
| + // binding must use the same decoded label as LoadBoxesComplete. |
| + haPut(t, s, haStatusPrefix+"other.json", []byte(`{"label":"other","Label":"leo","generated_at":"2026-11-04T12:00:00Z","metrics":{"instance_id":"i-0123456789abcdef0"}}`)) |
| + obs := haObserve(t, o) |
| + if d := obs.Decide("ie", "hapair", haTestNow); d.Kind != HACapacityUnknown { |
| + t.Fatalf("borrowed status under another key: %+v", d) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 9a2409a73..d90316399 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -609,6 +609,10 @@ type Config struct { |
| // Seeds, imports and sidecars are never stamped, and an HA host's moves |
| // and places, and imports into an HA region, are refused up front. |
| HARegions []string |
| + // HACapacityConfig is the strict CONSOLE_HA_CAPACITY_CONFIG document. |
| + HACapacityConfig string |
| + // HACapacityDirectory is the local deployment-store root, when using DirStore. |
| + HACapacityDirectory string |
| // AppRegions is CONSOLE_APP_REGIONS=on (nearest-region spec §5.6). Off |
| // never stops the create door's fill for rows already holding a region. |
| AppRegions bool |
| @@ -991,7 +995,9 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| - demoTransport http.RoundTripper |
| + haCapacityStart sync.Once |
| + haCapacity atomic.Pointer[haObserver] |
| + demoTransport http.RoundTripper |
| demoAdmission demoAdmissionCache |
| demoStatus demoStatusLimiter |