ha: publish regional capacity from console start
cmd/console/hacapacity_test.go+163 −2cmd/console/main.go+2 −2internal/console/awsregionmetric.go+9 −1internal/console/awsregionmetric_test.go+246 −0internal/console/hacapacity.go+3 −0internal/console/hacapacity_observe.go+6 −1internal/console/hostclaimops.go+0 −9internal/console/regioncapacity.go+59 −82internal/console/regioncapacity_test.go+89 −181internal/console/server.go+2 −0
CI failed — run details
Intent
<task-notification> <task-id>bbt5lw2vq</task-id> <tool-use-id>toolu_01FZ9DLijPkkuw4fEC5caWxE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/bbt5lw2vq.output</output-file> <status>completed</status> <summary>Background command "Wait for T1 fix round 1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a9179c5093c4a7b8a</task-id> <tool-use-id>toolu_01STYgv9shafRe4km4j26qLJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/a9179c5093c4a7b8a.output</output-file> <status>killed</status> <summary>Agent "Re-review T1 fix round 1" was stopped by Claude</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> </task-notification>
<task-notification> <task-id>a83fa16362c26896d</task-id> <tool-use-id>toolu_01CsZkvvJjKWosKDqGdh3YGZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/de069047-3c6a-40e7-ae66-85194f066976/tasks/a83fa16362c26896d.output</output-file> <status>completed</status> <summary>Agent "Re-review T1 fix round 1 (Opus)" 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>All four findings are addressed, and the fix diff has no new P1 or P2 breakage. I only read code; I ran no tests. **1. P2-1 (I2, ruling R7): ADDRESSED.** - Classification at `internal/console/hacapacity.go:420` is still an allowlist: only `identity_invalid` and `identity_unbound` count as excluded. Every other code, including the new `identity_malformed` and `identity_unreadable`, lands on unknown by default. - `enrollIdentity` (`internal/console/hacapacity_observe.go:451-524`) checks the record before calling `Enroll`. Bad JSON, duplicate keys, trailing data, a non-object or `null` record, unknown fields, wrong or null field types, and bad base64 in the document or signature all return `identity_malformed`. So do a document that is not a JSON object and wrong types on `accountId`, `region` or `instanceId`. An unknown version returns `identity_version`. All of these are unknown. - If `Enroll` fails, the result is `identity_invalid` only when the failure is proven separately: - the record names a different box (:513); - `rsa.ErrVerification` under the certificate for the document's region (:518); `x509` returns that RSA error unwrapped, so `errors.Is` works; - a valid signature with the wrong account, the wrong region or no instance (:519). - Anything else falls through to `identity_unreadable` (:523), which is unknown. That covers a missing certificate, a public key that isn't RSA, a nil key, tofu or roster conflicts, and an invalid reference. Matching on exact key names is stricter than `Enroll`'s case-insensitive decode, so evidence that `Enroll` rejects as malformed can't reach the exclusion branch. The classification is fail-safe. - Tests: - The `identity_document:"bad"` witness now expects Unknown (`internal/console/hacapacity_test.go:315-317`). - A fresh in-scope box with its record deleted gives Unknown plus `identity_missing` (`hacapacity_test.go:549`). - The malformed and verification table is at `hacapacity_test.go:531-596`. - Wrong account, wrong signed region and no instance give complete-zero, and a copied identity gives Unknown (`hacapacity_test.go:302-305`). - A nil-key verifier gives `identity_unreadable` and Unknown. **2. P3-2 (ruling R8): ADDRESSED.** At `internal/console/hacapacity.go:504`, absent or `null` `named_pools` gives `named_pools_missing`; any other bad type gives `named_pools_malformed`. The test at `hacapacity_test.go:598-625` checks the `MissingNamedPoolsOnly` flag and the blocker code for absent, null and wrong type. **3. P3-1: ADDRESSED.** `internal/console/hacapacity_observe.go:206` skips subdirectories and `*.tmp` files before the regular-file check. The S3 path is unchanged. `TestHACapacityS3ScratchKeysRemainUnknown` (`hacapacity_observe_test.go:663`) confirms `.tmp` and nested keys still make every region unknown, and `TestHACapacityDirectoryIgnoresScratch` (:590) covers the directory side. **4. P3-3: ADDRESSED.** The per-pass log is gone. `haLogUnboundChanges` (`hacapacity_observe.go:526-546`) logs once on entering the unbound state and once on leaving it. A failed observation (`obs.unavailable`) keeps the prior set. It is wired in at :592. `TestHACapacityRunnerUnboundTransitions` (`hacapacity_observe_test.go:626`) covers repeat passes, a failed LIST and recovery, leaving, and re-entry. **New P1/P2 in the fix diff:** none found. **Out-of-scope P3s:** - `release.DirStore.List` (`internal/release/store.go:630-640`) walks into ordinary subdirectories and lists their files; it only prunes `.carlos-write-*`. The console adapter skips every subdirectory instead, so a nested file is ignored on a directory store but makes the region unknown on S3. Writers use flat keys, so this can't produce a false zero, but it is not quite "like `DirStore.List`". - `dirPage` filters after the raw `ReadDir(limit+1)` cut. Scratch entries still count toward the bound, so many `.tmp` files can set `more` and turn the result unknown. That is fail-safe. - A temporary per-file read failure on an unbound box makes C11 log leave, then enter again (one enter/leave pair per flap). That is noise, not a correctness problem. - An empty but valid-base64 signature is classed as a bad signature (excluded), not malformed. That is defensible under R7.</result> <usage><subagent_tokens>60512</subagent_tokens><tool_uses>9</tool_uses><duration_ms>103182</duration_ms></usage> </task-notification>
Attributed to this commit: 10.9 g CO₂e (1,347,591 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| index 98ac78f54..9de008463 100644 |
| --- a/cmd/console/hacapacity_test.go |
| +++ b/cmd/console/hacapacity_test.go |
| @@ -1,19 +1,29 @@ |
| package main |
| import ( |
| + "bytes" |
| "context" |
| "go/ast" |
| "go/parser" |
| "go/token" |
| + "log" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| 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. |
| + // With neither activation setting, the helper never calls the server. |
| + t.Setenv("CARLOS_REGION_METRICS", "") |
| done := startHACapacity(context.Background(), nil, console.Config{}) |
| select { |
| case <-done: |
| @@ -88,3 +98,154 @@ func TestHACapacityServeWiring(t *testing.T) { |
| t.Fatalf("configuration wiring: %v", fields) |
| } |
| } |
| + |
| +func TestHACapacityStartsWithoutClaims(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + ha, metrics bool |
| + }{ |
| + {"both", true, true}, {"admission_only", true, false}, {"metrics_only", false, true}, {"disabled", false, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + for _, key := range []string{"AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_SESSION_TOKEN", "AWS_ENDPOINT_URL"} { |
| + t.Setenv(key, "") |
| + } |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("CARLOS_REGION_METRICS", "") |
| + if tc.metrics { |
| + t.Setenv("CARLOS_REGION_METRICS", "cloudwatch") |
| + } |
| + var calls atomic.Int64 |
| + wire := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + w.Header().Set("Content-Type", "application/cbor") |
| + w.Header().Set("smithy-protocol", "rpc-v2-cbor") |
| + w.Write([]byte{0xa0}) |
| + })) |
| + defer wire.Close() |
| + t.Setenv("AWS_ENDPOINT_URL_CLOUDWATCH", wire.URL) |
| + var logs capacityStartupLogs |
| + previous := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(previous) |
| + root := t.TempDir() |
| + st, err := console.Open(filepath.Join(root, "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + _, pub, err := appconfig.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := console.Config{HomeRegion: "ie", AWSAccount: "123456789012", SecretsPub: pub, Releases: release.NewDirStore(root), HACapacityDirectory: root, |
| + HACapacityConfig: `{"v":1,"regions":{"ie":{"aws_region":"eu-west-1","data_bucket":"test-data","data_bucket_region":"eu-west-1"}},"fixed_boxes":{}}`} |
| + if tc.ha { |
| + cfg.HARegions = []string{"ie"} |
| + } |
| + srv, err := console.NewServer(cfg, st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := srv.HACapacity(); ok { |
| + t.Fatal("constructor started observation") |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + done := startHACapacity(ctx, srv, cfg) |
| + defer func() { |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Error("capacity cleanup timed out") |
| + } |
| + }() |
| + if tc.ha || tc.metrics { |
| + if again := startHACapacity(ctx, srv, cfg); done != again { |
| + t.Fatal("duplicate capacity lifecycle") |
| + } |
| + deadline := time.Now().Add(3 * time.Second) |
| + for { |
| + _, available := srv.HACapacity() |
| + if available && (!tc.metrics || calls.Load() > 0) { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("observer available=%v metric calls=%d", available, calls.Load()) |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + } |
| + // Calling the real claim startup cannot add a second metric producer. |
| + srv.StartClaimRecoveryPass(ctx) |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(time.Second): |
| + t.Fatal("capacity workers did not stop") |
| + } |
| + want := int64(0) |
| + if tc.metrics { |
| + want = 1 |
| + } |
| + wantObservers := 0 |
| + if tc.ha || tc.metrics { |
| + wantObservers = 1 |
| + } |
| + if got := strings.Count(logs.String(), "HA capacity observation started."); got != wantObservers { |
| + t.Fatalf("observer starts=%d want=%d", got, wantObservers) |
| + } |
| + if got := strings.Count(logs.String(), "eligible-capacity metric armed"); got != int(want) { |
| + t.Fatalf("metric starts=%d want=%d", got, want) |
| + } |
| + if calls.Load() != want { |
| + t.Fatalf("metric calls=%d want %d", calls.Load(), want) |
| + } |
| + if !tc.ha && !tc.metrics { |
| + if _, ok := srv.HACapacity(); ok { |
| + t.Fatal("disabled observer ran") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type capacityStartupLogs struct { |
| + mu sync.Mutex |
| + buffer bytes.Buffer |
| +} |
| + |
| +func (b *capacityStartupLogs) Write(p []byte) (int, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buffer.Write(p) |
| +} |
| +func (b *capacityStartupLogs) String() string { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buffer.String() |
| +} |
| + |
| +func TestHACapacityClaimStartupOwnsNoMetric(t *testing.T) { |
| + f, err := parser.ParseFile(token.NewFileSet(), "../../internal/console/hostclaimops.go", nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, decl := range f.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Name.Name != "StartClaimRecoveryPass" { |
| + continue |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + if id, ok := n.(*ast.Ident); ok && strings.Contains(strings.ToLower(id.Name), "capacity") { |
| + t.Errorf("claim recovery still starts capacity via %s", id.Name) |
| + } |
| + return true |
| + }) |
| + } |
| +} |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 6e0e9143f..8f3f0395a 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -2079,8 +2079,8 @@ func pdfEngine(getenv func(string) string) (string, error) { |
| // 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) |
| + if len(cfg.HARegions) > 0 || strings.TrimSpace(os.Getenv("CARLOS_REGION_METRICS")) == "cloudwatch" { |
| + return srv.StartHACapacity(ctx) |
| } |
| done := make(chan struct{}) |
| close(done) |
diff --git a/internal/console/awsregionmetric.go b/internal/console/awsregionmetric.go| index 077db6170..64ab276b5 100644 |
| --- a/internal/console/awsregionmetric.go |
| +++ b/internal/console/awsregionmetric.go |
| @@ -63,8 +63,16 @@ func capacityPublisherFromEnv(ctx context.Context, getenv func(string) string) c |
| log.Printf("console: eligible-capacity metric disabled: load aws config: %v", err) |
| return nil |
| } |
| + return newCloudWatchCapacity(cfg) |
| +} |
| + |
| +func newCloudWatchCapacity(cfg aws.Config) cloudWatchCapacity { |
| return cloudWatchCapacity{now: time.Now, put: func(ctx context.Context, awsRegion string, in *cloudwatch.PutMetricDataInput) error { |
| - _, err := cloudwatch.NewFromConfig(cfg, func(o *cloudwatch.Options) { o.Region = awsRegion }).PutMetricData(ctx, in) |
| + _, err := cloudwatch.NewFromConfig(cfg, func(o *cloudwatch.Options) { |
| + o.Region = awsRegion |
| + o.Retryer = aws.NopRetryer{} |
| + o.RetryMaxAttempts = 1 |
| + }).PutMetricData(ctx, in) |
| return err |
| }} |
| } |
diff --git a/internal/console/awsregionmetric_test.go b/internal/console/awsregionmetric_test.go| new file mode 100644 |
| index 000000000..a25eb57c4 |
| --- /dev/null |
| +++ b/internal/console/awsregionmetric_test.go |
| @@ -0,0 +1,246 @@ |
| +package console |
| + |
| +import ( |
| + "compress/gzip" |
| + "context" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/aws/retry" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/aws/smithy-go/encoding/cbor" |
| +) |
| + |
| +func TestCapacityCloudWatchWireAndRecovery(t *testing.T) { |
| + o, local, _ := haFixture(t) |
| + var reads atomic.Int64 |
| + o.store = newHACapacityStore(haS3(t, func(r *http.Request) (*http.Response, error) { |
| + reads.Add(1) |
| + if r.URL.Query().Get("list-type") == "2" { |
| + prefix := r.URL.Query().Get("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/") |
| + body, _, err := local.Get(r.Context(), key) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return haResponse(r, 200, io.NopCloser(strings.NewReader(string(body)))), nil |
| + }), "") |
| + o.clock = newHATestClock() |
| + o.current.Store(haObserve(t, o)) |
| + if reads.Load() != 5 { |
| + t.Fatalf("observation attempts=%d", reads.Load()) |
| + } |
| + s := &Server{} |
| + s.haCapacity.Store(o) |
| + |
| + type request struct { |
| + host, auth, path, contentType string |
| + body []byte |
| + } |
| + var mu sync.Mutex |
| + var requests []request |
| + var fail atomic.Bool |
| + fail.Store(true) |
| + wire := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + var body io.Reader = r.Body |
| + if r.Header.Get("Content-Encoding") == "gzip" { |
| + z, err := gzip.NewReader(r.Body) |
| + if err != nil { |
| + t.Error(err) |
| + w.WriteHeader(400) |
| + return |
| + } |
| + defer z.Close() |
| + body = z |
| + } |
| + b, err := io.ReadAll(body) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + mu.Lock() |
| + requests = append(requests, request{r.Host, r.Header.Get("Authorization"), r.URL.Path, r.Header.Get("Content-Type"), b}) |
| + mu.Unlock() |
| + w.Header().Set("Content-Type", "application/cbor") |
| + w.Header().Set("smithy-protocol", "rpc-v2-cbor") |
| + if strings.Contains(r.Host, "eu-central-1") && fail.Load() { |
| + w.WriteHeader(500) |
| + w.Write(cbor.Encode(cbor.Map{"__type": cbor.String("InternalServiceFault"), "message": cbor.String("test failure")})) |
| + return |
| + } |
| + w.Write(cbor.Encode(cbor.Map{})) |
| + })) |
| + defer wire.Close() |
| + endpoint, err := url.Parse(wire.URL) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + client := wire.Client() |
| + cfg := aws.Config{Region: "us-east-1", Credentials: credentials.NewStaticCredentialsProvider("test", "test", ""), |
| + Retryer: func() aws.Retryer { |
| + return retry.NewStandard(func(o *retry.StandardOptions) { o.MaxAttempts = 3; o.MaxBackoff = time.Millisecond }) |
| + }, |
| + HTTPClient: haDoer(func(r *http.Request) (*http.Response, error) { |
| + // Retain the SDK's destination in Host; route every packet to loopback. |
| + local := r.Clone(r.Context()) |
| + local.Host = r.URL.Host |
| + local.URL.Scheme = endpoint.Scheme |
| + local.URL.Host = endpoint.Host |
| + return client.Do(local) |
| + }), |
| + } |
| + pub := newCloudWatchCapacity(cfg) |
| + pub.now = func() time.Time { return haTestNow } |
| + var logs haLogBuffer |
| + previous := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(previous) |
| + clock := newHATestClock() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { defer close(done); s.runCapacityPass(ctx, pub, clock) }() |
| + defer func() { cancel(); haAwait(t, done) }() |
| + count := func() int { mu.Lock(); defer mu.Unlock(); return len(requests) } |
| + for pass := 1; pass <= 11; pass++ { |
| + if pass > 1 { |
| + clock.tick <- haTestNow |
| + } |
| + haWait(t, func() bool { return count() >= pass*2 }) |
| + if pass == 1 { |
| + haWait(t, func() bool { return strings.Contains(logs.String(), "failure #1)") }) |
| + } |
| + // No automatic retry between ticks, even after a retryable HTTP 500. |
| + time.Sleep(10 * time.Millisecond) |
| + if count() != pass*2 { |
| + t.Fatalf("pass %d: attempts=%d want=%d", pass, count(), pass*2) |
| + } |
| + } |
| + fail.Store(false) |
| + clock.tick <- haTestNow |
| + haWait(t, func() bool { return strings.Contains(logs.String(), "recovered after 11 failure(s)") }) |
| + cancel() |
| + haAwait(t, done) |
| + if count() != 24 { |
| + t.Fatalf("attempts=%d want=24", count()) |
| + } |
| + if reads.Load() != 5 { |
| + t.Fatalf("metric reloaded evidence: reads=%d", reads.Load()) |
| + } |
| + if strings.Count(logs.String(), "eligible-capacity metric (failure #") != 2 || strings.Count(logs.String(), "metric recovered") != 1 || strings.Count(logs.String(), "metric armed") != 1 { |
| + t.Fatalf("logs: %s", logs.String()) |
| + } |
| + for i, r := range requests { |
| + region, placement, value := "eu-central-1", "de", float64(0) |
| + if i%2 == 1 { |
| + region, placement, value = "eu-west-1", "ie", 1 |
| + } |
| + if r.host != "monitoring."+region+".amazonaws.com" || !strings.Contains(r.auth, "/"+region+"/monitoring/aws4_request") { |
| + t.Fatalf("destination: %+v", r) |
| + } |
| + // Every captured call must be PutMetricData: no metric reads or other services. |
| + if r.path != "/service/GraniteServiceVersion20100801/operation/PutMetricData" || r.contentType != "application/cbor" { |
| + t.Fatalf("operation=%s content-type=%s", r.path, r.contentType) |
| + } |
| + decoded, rest := capacityWireCBOR(t, r.body) |
| + if len(rest) != 0 { |
| + t.Fatalf("trailing CBOR: %x", rest) |
| + } |
| + body, ok := decoded.(cbor.Map) |
| + if !ok { |
| + t.Fatalf("body=%#v", decoded) |
| + } |
| + if body["Namespace"] != cbor.String("Carlos/Region") { |
| + t.Fatalf("namespace=%#v", body) |
| + } |
| + data, ok := body["MetricData"].(cbor.List) |
| + if !ok || len(data) != 1 { |
| + t.Fatalf("data=%#v", body) |
| + } |
| + datum, ok := data[0].(cbor.Map) |
| + if !ok { |
| + t.Fatalf("datum=%#v", data) |
| + } |
| + wantDims := cbor.List{cbor.Map{"Name": cbor.String("Region"), "Value": cbor.String(placement)}} |
| + if datum["MetricName"] != cbor.String("EligibleBoxes") || datum["Unit"] != cbor.String("Count") || !reflect.DeepEqual(datum["Dimensions"], wantDims) { |
| + t.Fatalf("datum=%#v", datum) |
| + } |
| + number, err := cbor.AsFloat64(datum["Value"]) |
| + if err != nil || number != value { |
| + t.Fatalf("value=%v %v", number, err) |
| + } |
| + stamp, ok := datum["Timestamp"].(*cbor.Tag) |
| + if !ok { |
| + t.Fatalf("timestamp=%#v", datum["Timestamp"]) |
| + } |
| + seconds, err := cbor.AsFloat64(stamp.Value) |
| + if err != nil || stamp.ID != 1 || seconds != float64(haTestNow.Unix()) { |
| + t.Fatalf("timestamp=%+v %v", stamp, err) |
| + } |
| + if resolution, ok := datum["StorageResolution"]; ok && fmt.Sprint(resolution) != "60" { |
| + t.Fatalf("resolution=%v", resolution) |
| + } |
| + } |
| +} |
| + |
| +// The SDK emits indefinite maps/lists; encoding/cbor.Decode handles only |
| +// definite containers. Decode this fixture's containers and delegate scalar |
| +// decoding to the SDK. Its scalar encoding is canonical and preserves lengths. |
| +func capacityWireCBOR(t *testing.T, p []byte) (cbor.Value, []byte) { |
| + t.Helper() |
| + if len(p) == 0 { |
| + t.Fatal("truncated CBOR") |
| + } |
| + if p[0] != 0xbf && p[0] != 0x9f { |
| + v, err := cbor.Decode(p) |
| + if err != nil { |
| + t.Fatalf("scalar %x: %v", p, err) |
| + } |
| + n := len(cbor.Encode(v)) |
| + if n > len(p) { |
| + t.Fatal("truncated scalar") |
| + } |
| + return v, p[n:] |
| + } |
| + isMap := p[0] == 0xbf |
| + p = p[1:] |
| + m := cbor.Map{} |
| + var list cbor.List |
| + for len(p) > 0 && p[0] != 0xff { |
| + v, rest := capacityWireCBOR(t, p) |
| + p = rest |
| + if isMap { |
| + key, ok := v.(cbor.String) |
| + if !ok { |
| + t.Fatalf("map key=%#v", v) |
| + } |
| + value, rest := capacityWireCBOR(t, p) |
| + p = rest |
| + if _, exists := m[string(key)]; exists { |
| + t.Fatalf("duplicate key %s", key) |
| + } |
| + m[string(key)] = value |
| + } else { |
| + list = append(list, v) |
| + } |
| + } |
| + if len(p) == 0 { |
| + t.Fatal("unterminated CBOR") |
| + } |
| + if isMap { |
| + return m, p[1:] |
| + } |
| + return list, p[1:] |
| +} |
diff --git a/internal/console/hacapacity.go b/internal/console/hacapacity.go| index 6d25781df..ddaaeb9c3 100644 |
| --- a/internal/console/hacapacity.go |
| +++ b/internal/console/hacapacity.go |
| @@ -160,6 +160,9 @@ func parseHACapacityConfig(raw string, regions []string, home string) (*haCapaci |
| } |
| c.home = home |
| c.universe = slices.Clone(regions) |
| + for region := range c.Regions { |
| + c.universe = append(c.universe, region) |
| + } |
| slices.Sort(c.universe) |
| c.universe = slices.Compact(c.universe) |
| return &c, nil |
diff --git a/internal/console/hacapacity_observe.go b/internal/console/hacapacity_observe.go| index a4309508f..089ec9072 100644 |
| --- a/internal/console/hacapacity_observe.go |
| +++ b/internal/console/hacapacity_observe.go |
| @@ -279,11 +279,13 @@ type haObserver struct { |
| sequence atomic.Uint64 |
| once sync.Once |
| done chan struct{} |
| + ready chan struct{} |
| + readyOnce sync.Once |
| 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{}} |
| + return &haObserver{config: c, store: s, verifier: v, fingerprint: fp, done: make(chan struct{}), ready: 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} |
| @@ -576,6 +578,7 @@ func (o *haObserver) run(ctx context.Context) { |
| obs.unavailable = "observation_failed" |
| obs.completed = o.clock.Now() |
| o.current.Store(obs) |
| + o.readyOnce.Do(func() { close(o.ready) }) |
| published = true |
| // Do not overlap a canceled pass with its successor, even if a store is |
| // slow to acknowledge cancellation. Readers already see unknown. |
| @@ -585,6 +588,7 @@ func (o *haObserver) run(ctx context.Context) { |
| if !published { |
| obs.completed = o.clock.Now() |
| o.current.Store(obs) |
| + o.readyOnce.Do(func() { close(o.ready) }) |
| } |
| if ctx.Err() != nil { |
| return |
| @@ -617,6 +621,7 @@ func (s *Server) StartHACapacityObservation(ctx context.Context) <-chan struct{} |
| s.haCapacity.Store(o) |
| if err != nil || s.cfg.AWSAccount == "" || o.fingerprint == "" { |
| log.Printf(haConfigCopy, strings.Join(s.cfg.HARegions, ",")) |
| + close(o.ready) |
| close(o.done) |
| return |
| } |
diff --git a/internal/console/hostclaimops.go b/internal/console/hostclaimops.go| index f7d8989e7..344d43a1e 100644 |
| --- a/internal/console/hostclaimops.go |
| +++ b/internal/console/hostclaimops.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "errors" |
| "log" |
| - "os" |
| "time" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| @@ -55,14 +54,6 @@ func (s *Server) StartClaimRecoveryPass(ctx context.Context) { |
| log.Printf("console: claim recovery: %v", hostops.ErrContract) |
| return |
| } |
| - // The eligible-capacity metric (region HA spec 2 §4, regioncapacity.go) |
| - // runs beside claim recovery, on a host-claim console with region HA |
| - // on and a metrics adapter armed. |
| - if s.cfg.RegionHA { |
| - if pub := capacityPublisherFromEnv(ctx, os.Getenv); pub != nil { |
| - go s.runCapacityPass(ctx, pub) |
| - } |
| - } |
| t := time.NewTicker(claimRecoveryInterval) |
| defer t.Stop() |
| for { |
diff --git a/internal/console/regioncapacity.go b/internal/console/regioncapacity.go| index 7b0ae977b..302f45d69 100644 |
| --- a/internal/console/regioncapacity.go |
| +++ b/internal/console/regioncapacity.go |
| @@ -5,125 +5,102 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| - "sort" |
| + "os" |
| + "strings" |
| "time" |
| - "github.com/carlosframework/platform/internal/boxchoice" |
| "github.com/carlosframework/platform/internal/hostops" |
| - "github.com/carlosframework/platform/internal/park" |
| ) |
| -// The eligible-capacity metric (region HA spec 2 §4, A1-11): once a |
| -// minute the console counts, for each region its boxes publish, the boxes |
| -// that could take a new instance now (hostops.ExecutorChooser.Capacity: |
| -// enrolled, active, unfenced and placeable), and publishes the counts. An |
| -// alarm on the count catches what the cloud's own group metrics cannot: a |
| -// box that is in service but never enrolled, and a launch loop. Where the |
| -// counts go is an adapter's business (awsregionmetric.go); a console with |
| -// none publishes nothing. |
| - |
| -// capacityInterval is how often the counts are published. |
| +// Regional eligibility comes from the shared observation, independent of claims, |
| +// pool membership and inbound acceptance. Only complete regions emit a datum. |
| const capacityInterval = time.Minute |
| -// regionCapacity is one region's count. Placement is the CARLOS placement |
| -// code the metric is keyed by; AWSRegion is where its boxes run. |
| type regionCapacity struct { |
| Placement, AWSRegion string |
| Eligible int |
| } |
| -// capacityPublisher sends the counts to a metrics service. |
| type capacityPublisher interface { |
| PublishCapacity(ctx context.Context, counts []regionCapacity) error |
| } |
| -// regionCapacities counts each placement the snapshot's files name, sorted |
| -// by placement, and takes each one's AWS region from capacity's answer: |
| -// the signed roster's, never the files' own claim, so a stale or |
| -// misconfigured file naming another AWS region cannot send a region's |
| -// count elsewhere (Astra 2a round 2 finding 3). A placement the roster |
| -// does not know (no region entry, so no box there can be chosen) is left |
| -// out. A placement whose count fails, or whose read is incomplete |
| -// (hostops.ErrEvidenceIncomplete), is left out too and its error returned |
| -// with the counts that did succeed: publishing 0 for it would trip the |
| -// eligible-capacity alarm on a transient read failure, whereas a missing |
| -// data point is the alarm's own signal if the failure lasts (spec §4, |
| -// A2-8). Only a complete read that finds no placeable box is a 0. |
| -// |
| -// A home box publishes the home's placement code, "". It is counted under |
| -// home, the home's roster name, as the chooser reads it (Capacity's and |
| -// eligible's mapping of park.HomeRegion to HomeName), so the home region's |
| -// count goes to the AWS region the signed roster gives home (Astra 2a |
| -// final review, P2). With no home name the chooser places nothing in the |
| -// home, and its boxes are left out. |
| -func regionCapacities(ctx context.Context, snap boxchoice.Snapshot, home string, capacity func(context.Context, string) (int, string, error)) ([]regionCapacity, error) { |
| - named := map[string]bool{} |
| - for _, b := range snap.Boxes { |
| - if p := capacityPlacement(home, b.Placement); p != "" { |
| - named[p] = true |
| - } |
| - } |
| - placements := make([]string, 0, len(named)) |
| - for p := range named { |
| - placements = append(placements, p) |
| +// regionCapacities projects one generation over its configured universe. Both |
| +// the canonical code and the destination AWS region come from console config. |
| +func regionCapacities(obs *HACapacityObservation, now time.Time) ([]regionCapacity, error) { |
| + if !obs.available(now) { |
| + return nil, hostops.ErrEvidenceIncomplete |
| } |
| - sort.Strings(placements) |
| - var out []regionCapacity |
| + var counts []regionCapacity |
| var errs []error |
| - for _, p := range placements { |
| - n, aws, err := capacity(ctx, p) |
| - if errors.Is(err, hostops.ErrContract) { |
| - continue |
| - } |
| - if err != nil { |
| - errs = append(errs, fmt.Errorf("count %s: %w", p, err)) |
| + for _, region := range obs.config.universe { |
| + verdict := obs.Regional(region, now) |
| + if !verdict.Complete { |
| + errs = append(errs, fmt.Errorf("count %s: %w", region, hostops.ErrEvidenceIncomplete)) |
| continue |
| } |
| - out = append(out, regionCapacity{Placement: p, AWSRegion: aws, Eligible: n}) |
| + counts = append(counts, regionCapacity{region, obs.config.Regions[region].AWSRegion, verdict.Count}) |
| } |
| - return out, errors.Join(errs...) |
| + return counts, errors.Join(errs...) |
| } |
| -// capacityPlacement is the region a box's placement code is counted under: |
| -// the code itself, or for the home's "" the home's name, exactly when the |
| -// chooser maps park.HomeRegion to it (home is a placement code). "" is |
| -// counted nowhere. |
| -func capacityPlacement(home, code string) string { |
| - if region := park.PlacementRegion(code); region == park.HomeRegion && home != "" && park.PlacementRegion(home) == home { |
| - return home |
| - } |
| - return code |
| -} |
| - |
| -// publishCapacity counts and publishes once. |
| func (s *Server) publishCapacity(ctx context.Context, pub capacityPublisher) error { |
| - x := s.placementChooser("") |
| - if x == nil { |
| - return hostops.ErrContract |
| - } |
| - snap, err := s.liveEdges(ctx) |
| - if err != nil { |
| - return err |
| + obs, available := s.HACapacity() |
| + if !available { |
| + return hostops.ErrEvidenceIncomplete |
| } |
| - counts, countErr := regionCapacities(ctx, boxSnapshot(snap), x.HomeName, x.Capacity) |
| + counts, countErr := regionCapacities(obs, s.haCapacity.Load().clock.Now()) |
| if len(counts) == 0 { |
| return countErr |
| } |
| - // The regions that counted are published even when another failed: |
| - // the failed one has no data point, which is the alarm's signal. |
| return errors.Join(pub.PublishCapacity(ctx, counts), countErr) |
| } |
| +// StartHACapacity starts the serve-owned observation and optional metric loop |
| +// once. Its completion channel joins both workers on console shutdown. |
| +func (s *Server) StartHACapacity(ctx context.Context) <-chan struct{} { |
| + s.capacityStart.Do(func() { |
| + s.capacityDone = make(chan struct{}) |
| + metrics := strings.TrimSpace(os.Getenv("CARLOS_REGION_METRICS")) == "cloudwatch" |
| + if len(s.cfg.HARegions) == 0 && !metrics { |
| + close(s.capacityDone) |
| + return |
| + } |
| + observed := s.StartHACapacityObservation(ctx) |
| + var pub capacityPublisher |
| + if metrics { |
| + pub = capacityPublisherFromEnv(ctx, os.Getenv) |
| + } |
| + go func() { |
| + defer close(s.capacityDone) |
| + if pub != nil { |
| + // The first metric uses the initial generation, not a startup race with |
| + // the observer. Subsequent metric ticks never wait for a refresh. |
| + select { |
| + case <-s.haCapacity.Load().ready: |
| + case <-ctx.Done(): |
| + } |
| + s.runCapacityPass(ctx, pub, haWallClock{}) |
| + } |
| + <-observed |
| + }() |
| + }) |
| + return s.capacityDone |
| +} |
| + |
| // runCapacityPass publishes every capacityInterval until ctx ends. A |
| // failed pass is logged on its first failure and every tenth; the alarm |
| // treats missing data as breaching, so a console that stops publishing is |
| // itself an alert. |
| -func (s *Server) runCapacityPass(ctx context.Context, pub capacityPublisher) { |
| +func (s *Server) runCapacityPass(ctx context.Context, pub capacityPublisher, clock haClock) { |
| log.Printf("console: eligible-capacity metric armed (every %s)", capacityInterval) |
| - t := time.NewTicker(capacityInterval) |
| - defer t.Stop() |
| + ticks, stop := clock.Ticker(capacityInterval) |
| + defer stop() |
| fails := 0 |
| for { |
| + if ctx.Err() != nil { |
| + return |
| + } |
| pass, cancel := context.WithTimeout(ctx, capacityInterval) |
| err := s.publishCapacity(pass, pub) |
| cancel() |
| @@ -140,7 +117,7 @@ func (s *Server) runCapacityPass(ctx context.Context, pub capacityPublisher) { |
| select { |
| case <-ctx.Done(): |
| return |
| - case <-t.C: |
| + case <-ticks: |
| } |
| } |
| } |
diff --git a/internal/console/regioncapacity_test.go b/internal/console/regioncapacity_test.go| index 239363a72..25fe94eda 100644 |
| --- a/internal/console/regioncapacity_test.go |
| +++ b/internal/console/regioncapacity_test.go |
| @@ -3,122 +3,14 @@ package console |
| import ( |
| "context" |
| "errors" |
| + "github.com/aws/aws-sdk-go-v2/service/cloudwatch" |
| + "github.com/carlosframework/platform/internal/hostops" |
| + "github.com/carlosframework/platform/internal/release" |
| "reflect" |
| "testing" |
| "time" |
| - |
| - "github.com/aws/aws-sdk-go-v2/service/cloudwatch" |
| - |
| - "github.com/carlosframework/platform/internal/boxchoice" |
| - "github.com/carlosframework/platform/internal/hostops" |
| ) |
| -// The count runs without any cloud adapter (§25): it reads only the |
| -// edges snapshot and the chooser. Each region's AWS region is the |
| -// chooser's (the signed roster's), whatever a file claims: box z's file |
| -// names uk in eu-west-1. |
| -func TestRegionCapacitiesCountsEachPlacement(t *testing.T) { |
| - snap := boxchoice.Snapshot{Complete: true, Boxes: []boxchoice.Box{ |
| - {BoxID: "a", Placement: "uk", Region: "eu-west-2"}, |
| - {BoxID: "b", Placement: "uk", Region: "eu-west-2"}, |
| - {BoxID: "c", Placement: "ie", Region: "eu-west-1"}, |
| - {BoxID: "d", Placement: "fleet/pi", Region: "eu-west-1"}, |
| - {BoxID: "e", Placement: ""}, |
| - {BoxID: "z", Placement: "uk", Region: "eu-west-1"}, |
| - }} |
| - asked := []string{} |
| - capacity := func(_ context.Context, p string) (int, string, error) { |
| - asked = append(asked, p) |
| - switch p { |
| - case "uk": |
| - return 2, "eu-west-2", nil |
| - case "ie": |
| - return 0, "eu-west-1", nil |
| - } |
| - return 0, "", hostops.ErrContract // no roster region: left out |
| - } |
| - got, err := regionCapacities(context.Background(), snap, "", capacity) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - want := []regionCapacity{{Placement: "ie", AWSRegion: "eu-west-1", Eligible: 0}, {Placement: "uk", AWSRegion: "eu-west-2", Eligible: 2}} |
| - if !reflect.DeepEqual(got, want) || !reflect.DeepEqual(asked, []string{"fleet/pi", "ie", "uk"}) { |
| - t.Fatalf("got %+v asked %v", got, asked) |
| - } |
| -} |
| - |
| -// Controller ruling: a region whose count fails, or whose read is |
| -// incomplete, gets no data point (never a 0, which would trip the alarm on |
| -// a transient read failure; missing data is the alarm's own signal if it |
| -// lasts). The other regions' counts are unaffected, and the error is |
| -// returned so the pass logs it. |
| -func TestRegionCapacitiesOmitsARegionWhoseReadFailed(t *testing.T) { |
| - snap := boxchoice.Snapshot{Complete: true, Boxes: []boxchoice.Box{ |
| - {BoxID: "a", Placement: "ie"}, {BoxID: "b", Placement: "uk"}, {BoxID: "c", Placement: "us"}, |
| - }} |
| - for name, failure := range map[string]error{ |
| - "incomplete": hostops.ErrEvidenceIncomplete, |
| - "other": errors.New("SlowDown"), |
| - } { |
| - capacity := func(_ context.Context, p string) (int, string, error) { |
| - if p == "uk" { |
| - return 0, "", failure |
| - } |
| - return 1, "eu-" + p, nil |
| - } |
| - got, err := regionCapacities(context.Background(), snap, "", capacity) |
| - want := []regionCapacity{{Placement: "ie", AWSRegion: "eu-ie", Eligible: 1}, {Placement: "us", AWSRegion: "eu-us", Eligible: 1}} |
| - if !errors.Is(err, failure) || !reflect.DeepEqual(got, want) { |
| - t.Fatalf("%s: got %+v, %v; want %+v and the failure", name, got, err, want) |
| - } |
| - } |
| -} |
| - |
| -// Astra 2a final review, P2: a home box publishes the home's placement |
| -// code "". It is counted under the home's roster name, as the chooser |
| -// reads it, once whether the home's boxes publish "" or the name; with no |
| -// home name (or one that is not a placement code) the chooser places |
| -// nothing in the home, and it is not asked. |
| -func TestRegionCapacitiesCountsTheHomeUnderItsName(t *testing.T) { |
| - snap := boxchoice.Snapshot{Complete: true, Boxes: []boxchoice.Box{ |
| - {BoxID: "a", Placement: ""}, {BoxID: "b", Placement: ""}, {BoxID: "c", Placement: "ie"}, {BoxID: "d", Placement: "uk"}, |
| - }} |
| - for home, wantAsked := range map[string][]string{ |
| - "ie": {"ie", "uk"}, |
| - "": {"ie", "uk"}, |
| - "Not/Code": {"ie", "uk"}, |
| - "de": {"de", "ie", "uk"}, |
| - } { |
| - asked := []string{} |
| - capacity := func(_ context.Context, p string) (int, string, error) { |
| - asked = append(asked, p) |
| - return 2, "aws-" + p, nil |
| - } |
| - got, err := regionCapacities(context.Background(), snap, home, capacity) |
| - if err != nil || !reflect.DeepEqual(asked, wantAsked) || len(got) != len(wantAsked) { |
| - t.Fatalf("home %q: got %+v, %v, asked %v; want %v asked", home, got, err, asked, wantAsked) |
| - } |
| - } |
| -} |
| - |
| -// The same end to end, with only home boxes: each publishes placement "", |
| -// and the pass publishes the home's placeable count, non-zero, to the AWS |
| -// region the signed roster gives the home (ie, eu-west-1). |
| -func TestPublishCapacityCountsTheHomeRegion(t *testing.T) { |
| - cx := haClaimCase(t, "ie") |
| - home := func(m map[string]any) { m["placement"] = "" } |
| - publishHABox(t, cx, "box-ie-default", false, home) |
| - publishHABox(t, cx, "box-ie-tito", false, home) |
| - var pub capacityRecorder |
| - if err := cx.srv.publishCapacity(context.Background(), &pub); err != nil { |
| - t.Fatal(err) |
| - } |
| - if len(pub.got) != 1 || pub.got[0].Placement != "ie" || pub.got[0].AWSRegion != "eu-west-1" || pub.got[0].Eligible == 0 { |
| - t.Fatalf("published %+v (%d calls), want the home ie with a non-zero count in eu-west-1", pub.got, pub.calls) |
| - } |
| -} |
| - |
| -// capacityRecorder keeps what one pass would publish. |
| type capacityRecorder struct { |
| got []regionCapacity |
| calls int |
| @@ -130,83 +22,84 @@ func (c *capacityRecorder) PublishCapacity(_ context.Context, counts []regionCap |
| return nil |
| } |
| -// Astra 2a round 2 finding 3, end to end: a stray box's edges file naming |
| -// ie in another AWS region (and sorting after the real box) does not move |
| -// ie's count out of the roster's eu-west-1. |
| -func TestPublishCapacityTakesTheRegionFromTheRoster(t *testing.T) { |
| - cx := haClaimCase(t, "") |
| - publishHABox(t, cx, "box-ie-default", false, nil) |
| - publishHABox(t, cx, "box-ie-stray", false, func(m map[string]any) { m["region"] = "eu-west-2" }) |
| - var pub capacityRecorder |
| - if err := cx.srv.publishCapacity(context.Background(), &pub); err != nil { |
| - t.Fatal(err) |
| - } |
| - want := []regionCapacity{{Placement: "ie", AWSRegion: "eu-west-1", Eligible: 1}} |
| - if !reflect.DeepEqual(pub.got, want) { |
| - t.Fatalf("published %+v, want %+v", pub.got, want) |
| - } |
| -} |
| - |
| -// Controller ruling 1: the pass counts through the scoped chooser, so a |
| -// region with a placeable box publishes a non-zero count (an unscoped |
| -// chooser answers 0 for every region). |
| -func TestPublishCapacityCountsPlaceableBoxes(t *testing.T) { |
| - cx := haClaimCase(t, "") |
| - publishHABox(t, cx, "box-ie-default", false, nil) |
| - var pub capacityRecorder |
| - if err := cx.srv.publishCapacity(context.Background(), &pub); err != nil { |
| - t.Fatal(err) |
| - } |
| - if len(pub.got) != 1 || pub.got[0].Placement != "ie" || pub.got[0].Eligible != 1 { |
| - t.Fatalf("published %+v, want ie with 1", pub.got) |
| +func TestRegionCapacitiesObservation(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + edit func(*testing.T, release.Store) |
| + wantIE int |
| + incomplete bool |
| + }{ |
| + {name: "eligible", wantIE: 1}, |
| + {name: "empty", edit: func(t *testing.T, store release.Store) { |
| + if err := store.Delete(context.Background(), "control/edges/leo.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {name: "missing_status", incomplete: true, edit: func(t *testing.T, store release.Store) { |
| + if err := store.Delete(context.Background(), "status/boxes/leo.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }}, |
| + {name: "wrong_file_aws_region", incomplete: true, edit: func(t *testing.T, store release.Store) { |
| + haPut(t, store, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { m["region"] = "us-east-1" })) |
| + }}, |
| + {name: "pool_and_inbound_independent", wantIE: 1, edit: func(t *testing.T, store release.Store) { |
| + haPut(t, store, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { |
| + delete(m, "named_pools") |
| + m["accepts_inbound"] = false |
| + m["serves_shared_pool"] = false |
| + })) |
| + }}, |
| + {name: "file_cannot_add_region", edit: func(t *testing.T, store release.Store) { |
| + haPut(t, store, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) { m["placement"] = "us" })) |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + o, store, _ := haFixture(t) |
| + if tc.edit != nil { |
| + tc.edit(t, store) |
| + } |
| + clock := newHATestClock() |
| + o.clock = clock |
| + o.current.Store(haObserve(t, o)) |
| + s := &Server{} |
| + s.haCapacity.Store(o) |
| + rec := &capacityRecorder{} |
| + err := s.publishCapacity(context.Background(), rec) |
| + if errors.Is(err, hostops.ErrEvidenceIncomplete) != tc.incomplete || (err != nil && !tc.incomplete) { |
| + t.Fatalf("error=%v", err) |
| + } |
| + want := []regionCapacity{{"de", "eu-central-1", 0}} |
| + if !tc.incomplete { |
| + want = append(want, regionCapacity{"ie", "eu-west-1", tc.wantIE}) |
| + } |
| + if !reflect.DeepEqual(rec.got, want) || rec.calls != 1 { |
| + t.Fatalf("got=%+v calls=%d want=%+v", rec.got, rec.calls, want) |
| + } |
| + // The same stored generation expires at use, without another store read. |
| + clock.advance(120*time.Second, false) |
| + rec = &capacityRecorder{} |
| + if err = s.publishCapacity(context.Background(), rec); !errors.Is(err, hostops.ErrEvidenceIncomplete) || rec.calls != 0 { |
| + t.Fatalf("expired: %v %+v", err, rec) |
| + } |
| + }) |
| } |
| } |
| -// Controller ruling 2: an incomplete read publishes nothing for the |
| -// region (not 0), while a complete read with no placeable box publishes 0. |
| -func TestPublishCapacityIncompleteReadPublishesNothingButNoRoomPublishesZero(t *testing.T) { |
| - ctx := context.Background() |
| - cx := haClaimCase(t, "") |
| - publishHABox(t, cx, "box-ie-default", true, nil) // stale: named, not placeable |
| - var pub capacityRecorder |
| - if err := cx.srv.publishCapacity(ctx, &pub); err != nil { |
| +func TestRegionCapacitiesConfiguredUnion(t *testing.T) { |
| + c, err := parseHACapacityConfig(haTestConfig, []string{"ie"}, "ie") |
| + if err != nil { |
| t.Fatal(err) |
| } |
| - want := []regionCapacity{{Placement: "ie", AWSRegion: "eu-west-1", Eligible: 0}} |
| - if pub.calls != 1 || !reflect.DeepEqual(pub.got, want) { |
| - t.Fatalf("a complete read with no placeable box published %+v (%d calls), want %+v", pub.got, pub.calls, want) |
| - } |
| - |
| - publishHABox(t, cx, "box-ie-default", false, nil) |
| - pub = capacityRecorder{} |
| - edges := cx.srv.cfg.ClaimAuthority.Executors.Edges |
| - cx.srv.cfg.ClaimAuthority.Executors.Edges = func(ctx context.Context) (boxchoice.Snapshot, error) { |
| - snap, err := edges(ctx) |
| - snap.Complete = false |
| - return snap, err |
| - } |
| - err := cx.srv.publishCapacity(ctx, &pub) |
| - if !errors.Is(err, hostops.ErrEvidenceIncomplete) { |
| - t.Fatalf("an incomplete read: %v, want ErrEvidenceIncomplete", err) |
| - } |
| - if pub.calls != 0 || pub.got != nil { |
| - t.Fatalf("an incomplete read published %+v (%d calls), want nothing", pub.got, pub.calls) |
| + if !reflect.DeepEqual(c.universe, []string{"de", "ie"}) { |
| + t.Fatalf("universe=%v", c.universe) |
| } |
| -} |
| - |
| -// The same, with the only box's own file naming another AWS region: the |
| -// chooser does not count a box whose file disagrees with the roster, and |
| -// the 0 still goes to the roster's eu-west-1, not the file's eu-west-2. |
| -func TestPublishCapacityIgnoresTheBoxsOwnAWSRegion(t *testing.T) { |
| - cx := haClaimCase(t, "") |
| - publishHABox(t, cx, "box-ie-default", false, func(m map[string]any) { m["region"] = "eu-west-2" }) |
| - var pub capacityRecorder |
| - if err := cx.srv.publishCapacity(context.Background(), &pub); err != nil { |
| + c, err = parseHACapacityConfig(haTestConfig, nil, "ie") |
| + if err != nil { |
| t.Fatal(err) |
| } |
| - want := []regionCapacity{{Placement: "ie", AWSRegion: "eu-west-1", Eligible: 0}} |
| - if !reflect.DeepEqual(pub.got, want) { |
| - t.Fatalf("published %+v, want %+v", pub.got, want) |
| + if !reflect.DeepEqual(c.universe, []string{"de", "ie"}) { |
| + t.Fatalf("metrics-only universe=%v", c.universe) |
| } |
| } |
| @@ -227,7 +120,7 @@ func TestPlacementChooserIsScopedLikeCreate(t *testing.T) { |
| } |
| } |
| -func TestCloudWatchCapacityPublishesEachRegionInItsOwnRegion(t *testing.T) { |
| +func TestCapacityCloudWatchPublishesEachRegionInItsOwnRegion(t *testing.T) { |
| now := time.Date(2026, 10, 16, 12, 0, 0, 0, time.UTC) |
| type call struct { |
| region, ns, metric, dim string |
| @@ -251,3 +144,18 @@ func TestCloudWatchCapacityPublishesEachRegionInItsOwnRegion(t *testing.T) { |
| t.Fatal("published with CARLOS_REGION_METRICS unset") |
| } |
| } |
| + |
| +func TestRegionCapacitiesUnavailablePublishesNothing(t *testing.T) { |
| + o, store, _ := haFixture(t) |
| + haPut(t, store, "control/edges/leo.json", []byte(`{`)) |
| + o.clock = newHATestClock() |
| + o.current.Store(haObserve(t, o)) |
| + s := &Server{} |
| + s.haCapacity.Store(o) |
| + for _, srv := range []*Server{s, {}} { |
| + rec := &capacityRecorder{} |
| + if err := srv.publishCapacity(context.Background(), rec); !errors.Is(err, hostops.ErrEvidenceIncomplete) || rec.calls != 0 { |
| + t.Fatalf("unavailable: error=%v published=%+v", err, rec) |
| + } |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index d90316399..f5923e8d1 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -995,6 +995,8 @@ type Config struct { |
| // Server is the console's http.Handler. |
| type Server struct { |
| + capacityStart sync.Once |
| + capacityDone chan struct{} |
| haCapacityStart sync.Once |
| haCapacity atomic.Pointer[haObserver] |
| demoTransport http.RoundTripper |