carlos / platform Public

region labels: the console's region name map, on the change index and its backstop (plan 1 task 4)

Baselines for the store-call budget and GET /api/cli/apps pinned at origin/main a64f5a41.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4df3f1678d131b02f23dfeab74921cba2509c9cb parent 80ffa15
6 files changed, +608 −9
  • cmd/console/changeindex_test.go +4 −3
  • cmd/console/main.go +13 −6
  • internal/console/regionbudget_test.go +204 −0
  • internal/console/regionnames.go +154 −0
  • internal/console/regionnames_test.go +229 −0
  • internal/console/server.go +4 −0
diff --git a/cmd/console/changeindex_test.go b/cmd/console/changeindex_test.go
index 7545d50f3..aaef3eada 100644
--- a/cmd/console/changeindex_test.go
+++ b/cmd/console/changeindex_test.go
@@ -33,8 +33,9 @@ func TestChangeIndexArming(t *testing.T) {
{"read", true, false},
{"read", false, true},
} {
- if got := armChangeIndex(env(c.val), c.hostClaim, ds) != nil; got != c.armed {
- t.Errorf("CARLOS_CHANGE_INDEX=%q host claim %v: armed %v, want %v", c.val, c.hostClaim, got, c.armed)
+ v, w := armChangeIndex(env(c.val), c.hostClaim, ds)
+ if got := v != nil; got != c.armed || (w != nil) != c.armed {
+ t.Errorf("CARLOS_CHANGE_INDEX=%q host claim %v: armed view %v, watch %v, want both %v", c.val, c.hostClaim, got, w != nil, c.armed)
}
}
}
@@ -44,7 +45,7 @@ func TestRecordViewBackstopRebuildsAtStart(t *testing.T) {
t.Parallel()
ds := release.NewDirStore(t.TempDir())
ds.EnableChangeIndex()
- v := armChangeIndex(func(string) string { return "read" }, false, ds)
+ v, _ := armChangeIndex(func(string) string { return "read" }, false, ds)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { recordViewBackstopLoop(ctx, v); close(done) }()
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 7e3c9c0d0..a007e6389 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -586,10 +586,16 @@ func serve() {
// view over the deployment store, rebuilt at start and every backstop.
// Armed before any worker starts. Unset is nil: every sweep walks the
// bucket as before.
- if v := armChangeIndex(os.Getenv, cfg.HostClaim, rel); v != nil {
+ var edgesWatch *release.ChangeWatch
+ if v, w := armChangeIndex(os.Getenv, cfg.HostClaim, rel); v != nil {
srv.SetRecordView(v)
go recordViewBackstopLoop(context.Background(), v)
+ edgesWatch = w
}
+ // The region labels' name map (region labels spec §3.2): one edges read
+ // at start, then at most every 10 minutes on a generation change, else
+ // every 30 (±10%).
+ go srv.RunRegionNames(context.Background(), edgesWatch)
// The move pass's pages (moves Plan 5 Task 7): the console's alert sinks,
// armed before the claim runtime binds the pass, so no pass runs unarmed.
armMovesPaging(context.Background(), cfg, os.Getenv)
@@ -1661,17 +1667,18 @@ const recordViewWalkTimeout = 5 * time.Minute
// CARLOS_CHANGE_INDEX is exactly "read" (change-index design §7), or nil. A
// host-claim console stays disarmed: the run and seed sweeps, the view's
// only readers, are off there, so a view would only cost its backstop walks.
-func armChangeIndex(getenv func(string) string, hostClaim bool, rel release.Store) *provision.RecordView {
+func armChangeIndex(getenv func(string) string, hostClaim bool, rel release.Store) (*provision.RecordView, *release.ChangeWatch) {
if getenv("CARLOS_CHANGE_INDEX") != "read" {
- return nil
+ return nil, nil
}
if hostClaim {
log.Printf("console: change index: CARLOS_CHANGE_INDEX=read is ignored on a host-claim console, whose sweeps are off")
- return nil
+ return nil, nil
}
- v := provision.NewRecordView(rel, release.NewChangeWatch(rel))
+ w := release.NewChangeWatch(rel)
+ v := provision.NewRecordView(rel, w)
log.Printf("console: change index armed: the run and seed sweeps read the record view (backstop %s)", release.ChangeIndexBackstop)
- return v
+ return v, w
}
// recordViewBackstopLoop is the view's backstop (design §4.4): Rebuild at
diff --git a/internal/console/regionbudget_test.go b/internal/console/regionbudget_test.go
new file mode 100644
index 000000000..9496ad8e3
--- /dev/null
+++ b/internal/console/regionbudget_test.go
@@ -0,0 +1,204 @@
+package console
+
+import (
+ "context"
+ "maps"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// opCountStore counts every store call, across all five release.Store
+// methods, by method and the key's first segment ("Get apps", "List status").
+type opCountStore struct {
+ release.Store
+ mu sync.Mutex
+ by map[string]int
+}
+
+func (c *opCountStore) note(op, key string) {
+ seg, _, _ := strings.Cut(key, "/")
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.by == nil {
+ c.by = map[string]int{}
+ }
+ c.by[op+" "+seg]++
+}
+
+func (c *opCountStore) Get(ctx context.Context, k string) ([]byte, string, error) {
+ c.note("Get", k)
+ return c.Store.Get(ctx, k)
+}
+
+func (c *opCountStore) Put(ctx context.Context, k string, b []byte, ifMatch string) (string, error) {
+ c.note("Put", k)
+ return c.Store.Put(ctx, k, b, ifMatch)
+}
+
+func (c *opCountStore) List(ctx context.Context, p string) ([]string, error) {
+ c.note("List", p)
+ return c.Store.List(ctx, p)
+}
+
+func (c *opCountStore) ListDirs(ctx context.Context, p string) ([]string, error) {
+ c.note("ListDirs", p)
+ return c.Store.ListDirs(ctx, p)
+}
+
+func (c *opCountStore) Delete(ctx context.Context, k string) error {
+ c.note("Delete", k)
+ return c.Store.Delete(ctx, k)
+}
+
+func (c *opCountStore) reset() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.by = map[string]int{}
+}
+
+func (c *opCountStore) snapshot() map[string]int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return maps.Clone(c.by)
+}
+
+func (c *opCountStore) total() int {
+ n := 0
+ for _, v := range c.snapshot() {
+ n += v
+ }
+ return n
+}
+
+// budgetRequests are the requests whose store calls the labels must not add
+// to (spec §7): every page the labels touch and every door they add fields
+// to, in a fixed order (the box-report cache is shared between them).
+var budgetRequests = []string{
+ "GET /a/{sqid}/",
+ "GET /a/{sqid}/apps/shop",
+ "GET /a/{sqid}/apps/shop/instances",
+ "GET /a/{sqid}/apps/shop/instances/" + remoteHost,
+ "GET /a/{sqid}/apps/shop/deployments",
+ "GET /a/{sqid}/apps/shop/settings",
+ "CLI /api/cli/apps/{sqid}/shop/instances",
+ "CLI /api/cli/apps/{sqid}/shop/instances/" + remoteHost,
+ "CLI /api/cli/apps/{sqid}/list",
+ "CLI /api/cli/apps/{sqid}/shop/regions",
+ "CLI /api/cli/apps/{sqid}/shop/routes",
+}
+
+// writeBudgetEdges names the home ie and writes the three boxes' edges
+// files, as later tasks' writeRegionEdges does, so the baseline is measured
+// over the same bucket the labels later read.
+func writeBudgetEdges(t *testing.T, tb *twoBoxes) {
+ t.Helper()
+ tb.fx.srv.cfg.HomeRegion = "ie"
+ for _, f := range []struct{ machine, placement, aws string }{
+ {"box-a", "", "eu-west-1"}, {"box-b", "uk", "eu-west-2"}, {"box-c", "au", "ap-southeast-2"},
+ } {
+ label := status.Label(f.machine)
+ body := `{"v":1,"box":"` + label + `","eip":"192.0.2.10","region":"` + f.aws + `","placement":"` + f.placement + `","hosts":{}}`
+ if _, err := tb.fx.rel.Put(context.Background(), "control/edges/"+label+".json", []byte(body), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// measureBudget runs each request once with every store call counted, the
+// clock fixed and the DNS guidance's edge fold stubbed (it predates the
+// labels), and returns each request's calls.
+func measureBudget(t *testing.T, tb *twoBoxes) map[string]map[string]int {
+ t.Helper()
+ cs := &opCountStore{Store: tb.fx.rel}
+ tb.fx.srv.cfg.Releases = cs
+ tb.fx.srv.foldEdgeIPs = func(context.Context) []string { return nil }
+ clock := time.Now()
+ tb.fx.srv.boxReports.now = func() time.Time { return clock }
+ out := map[string]map[string]int{}
+ for _, req := range budgetRequests {
+ kind, path, _ := strings.Cut(req, " ")
+ path = strings.ReplaceAll(path, "{sqid}", tb.sqid)
+ cs.reset()
+ var code int
+ if kind == "GET" {
+ code, _, _ = get(t, tb.browser, tb.fx.ts.URL+path)
+ } else {
+ code, _, _ = rawReq(t, http.MethodGet, tb.fx.ts.URL+path, tb.token, "")
+ }
+ if code != http.StatusOK {
+ t.Fatalf("%s = %d", req, code)
+ }
+ out[req] = cs.snapshot()
+ }
+ return out
+}
+
+// regionBudgetBaseline is measureBudget at the branch base (origin/main a64f5a41, before
+// any region-label code), pasted from Step 2's failing run.
+var regionBudgetBaseline = map[string]map[string]int{
+ "CLI /api/cli/apps/{sqid}/list": {},
+ "CLI /api/cli/apps/{sqid}/shop/instances": {"Get apps": 3, "Get control": 3, "Get status": 2, "List apps": 1, "List control": 1, "List status": 1},
+ "CLI /api/cli/apps/{sqid}/shop/instances/eu.shop.example.com": {"Get apps": 1, "Get control": 3, "List control": 1},
+ "CLI /api/cli/apps/{sqid}/shop/regions": {"Get apps": 1, "Get control": 9, "Get status": 4, "List control": 3, "List status": 2},
+ "CLI /api/cli/apps/{sqid}/shop/routes": {"Get status": 2, "List status": 1},
+ "GET /a/{sqid}/": {"Get apps": 4, "Get status": 2, "List apps": 2, "List status": 1},
+ "GET /a/{sqid}/apps/shop": {"Get accounts": 1, "Get apps": 4, "Get metrics": 48, "List alerts": 1, "List apps": 2, "List metrics": 1},
+ "GET /a/{sqid}/apps/shop/deployments": {"Get accounts": 1, "Get apps": 3, "List apps": 1},
+ "GET /a/{sqid}/apps/shop/instances": {"Get accounts": 1, "Get apps": 4, "Get control": 3, "Get status": 2, "List apps": 1, "List control": 1, "List status": 1},
+ "GET /a/{sqid}/apps/shop/instances/eu.shop.example.com": {"Get accounts": 1, "Get apps": 3, "List apps": 1},
+ "GET /a/{sqid}/apps/shop/settings": {"Get accounts": 2, "Get apps": 11, "Get status": 2, "List apps": 5, "List control": 1, "List domains": 1, "List status": 1},
+}
+
+// TestRegionLabelsAddNoStoreReads (spec §7, labels R2-1): no request makes a
+// store call the base did not, and /list makes none at all. A request may
+// make fewer (Task 10 drops the Running tab's second edges read).
+func TestRegionLabelsAddNoStoreReads(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, true)
+ writeBudgetEdges(t, tb)
+ tb.fx.srv.refreshRegionNames(context.Background(), nil, time.Now())
+ got := measureBudget(t, tb)
+ if len(regionBudgetBaseline) == 0 {
+ t.Fatalf("no baseline yet: at the branch base, paste this as regionBudgetBaseline:\n%#v", got)
+ }
+ for req, calls := range got {
+ want, ok := regionBudgetBaseline[req]
+ if !ok {
+ t.Errorf("%s has no baseline", req)
+ continue
+ }
+ for op, n := range calls {
+ if n > want[op] {
+ t.Errorf("%s: %d %q calls, %d at the base: the labels added a store call", req, n, op, want[op])
+ }
+ }
+ }
+ if calls := got["CLI /api/cli/apps/{sqid}/list"]; len(calls) != 0 {
+ t.Errorf("/list made store calls %v, want none", calls)
+ }
+}
+
+// plainAppListBaseline is GET /api/cli/apps's body at the branch base,
+// pasted from Step 2's failing run. The labels never touch that door (§10).
+const plainAppListBaseline = "{\"accounts\":[{\"apps\":[\"kass\"],\"name\":\"ops\",\"role\":\"owner\",\"sqid\":\"bab\"},{\"apps\":[\"shop\"],\"name\":\"Shop\",\"role\":\"owner\",\"sqid\":\"mtz\"}]}\n"
+
+func TestPlainAppListIsUnchanged(t *testing.T) {
+ tb := newTwoBoxes(t)
+ tb.setUp(t, true)
+ code, _, body := rawReq(t, http.MethodGet, tb.fx.ts.URL+"/api/cli/apps", tb.token, "")
+ if code != http.StatusOK {
+ t.Fatalf("/api/cli/apps = %d %s", code, body)
+ }
+ if plainAppListBaseline == "" {
+ t.Fatalf("no baseline yet: at the branch base, paste this as plainAppListBaseline:\n%q", body)
+ }
+ if body != plainAppListBaseline {
+ t.Fatalf("GET /api/cli/apps changed:\n got %q\nwant %q", body, plainAppListBaseline)
+ }
+}
diff --git a/internal/console/regionnames.go b/internal/console/regionnames.go
new file mode 100644
index 000000000..666970f65
--- /dev/null
+++ b/internal/console/regionnames.go
@@ -0,0 +1,154 @@
+package console
+
+import (
+ "context"
+ "log"
+ "math/rand/v2"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/regionlabel"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The region name map (region labels spec §3.2, §7). It is rebuilt from one
+// edges read when the change index shows control/edges at a new generation,
+// at most once per regionNamesFloor, else on the backstop. It never polls
+// the change index itself: it reads the generation the record view's own
+// polls observed (release.ChangeWatch.Gen). Nothing reads edges files while
+// rendering.
+const (
+ regionNamesFloor = 10 * time.Minute
+ regionNamesTick = time.Minute
+ regionNamesScope = "control/edges"
+)
+
+// scopeGens is the one thing the map asks of the change index.
+type scopeGens interface {
+ Gen(scope string) (uint64, bool)
+}
+
+// regionNamesState is Server.labelNames.
+type regionNamesState struct {
+ mu sync.Mutex
+ names regionlabel.Names
+ read bool // a rebuild has produced names
+ lastOK bool // the last try succeeded (a complete read)
+ readAt time.Time // the last rebuild that produced names
+ tryAt time.Time // the last try, whatever its outcome
+ gen uint64 // control/edges' generation when names were last read
+ genKnown bool // ... and whether the watch could vouch for it
+ backstop time.Duration // this cycle's jittered backstop
+}
+
+// due says whether a rebuild should be tried at now, given the scope's
+// generation (genOK false: the watch cannot vouch, so only the backstop
+// counts). A failed or incomplete try is retried at the floor.
+func (st *regionNamesState) due(now time.Time, gen uint64, genOK bool) bool {
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ switch {
+ case st.tryAt.IsZero():
+ return true
+ case !st.lastOK:
+ return now.Sub(st.tryAt) >= regionNamesFloor
+ case genOK && (!st.genKnown || gen != st.gen):
+ return now.Sub(st.tryAt) >= regionNamesFloor
+ }
+ return now.Sub(st.readAt) >= st.backstop
+}
+
+// regionNamesBackstop is release.ChangeIndexBackstop jittered by up to 10%
+// either way, drawn once per cycle.
+func regionNamesBackstop() time.Duration {
+ b := release.ChangeIndexBackstop
+ return b - b/10 + rand.N(b/5)
+}
+
+// regionNames is the last good map; the zero Names (every label its code)
+// before one.
+func (s *Server) regionNames() regionlabel.Names {
+ s.labelNames.mu.Lock()
+ defer s.labelNames.mu.Unlock()
+ return s.labelNames.names
+}
+
+// regionHome is the home's name every label folds "" into: claims-aware,
+// as homeRegionOut is.
+func (s *Server) regionHome() string { return s.homeRegionOut("") }
+
+// refreshRegionNames tries one rebuild when it is due, and reports whether
+// it tried. A failed listing, and a read that is not complete (a file that
+// would not read or parse), is a failed rebuild (spec §3.2): the old map
+// stays, before the first success every label is its code, and the next
+// try is at the floor. A partial read is never folded: a missing file can
+// change which AWS region wins a code's vote.
+func (s *Server) refreshRegionNames(ctx context.Context, gens scopeGens, now time.Time) bool {
+ if s.cfg.Releases == nil {
+ return false
+ }
+ var gen uint64
+ var genOK bool
+ if gens != nil {
+ gen, genOK = gens.Gen(regionNamesScope)
+ }
+ st := &s.labelNames
+ if !st.due(now, gen, genOK) {
+ return false
+ }
+ snap, err := edgesfile.ReadSnapshot(ctx, s.cfg.Releases)
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ st.tryAt = now
+ switch {
+ case err != nil:
+ log.Printf("console: region names: listing %s: %v; labels keep the names read %s", edgesfile.Prefix, err, readWhen(st))
+ st.lastOK = false
+ return true
+ case !snap.Complete:
+ log.Printf("console: region names: an edges file under %s would not read or parse; labels keep the names read %s", edgesfile.Prefix, readWhen(st))
+ st.lastOK = false
+ return true
+ }
+ st.names = regionlabel.NamesFrom(snap, s.regionHome())
+ st.read, st.lastOK = true, true
+ st.readAt, st.gen, st.genKnown = now, gen, genOK
+ st.backstop = regionNamesBackstop()
+ return true
+}
+
+// readWhen says when the held names were read, for the two log lines.
+func readWhen(st *regionNamesState) string {
+ if !st.read {
+ return "never (labels are codes until a read succeeds)"
+ }
+ return "at " + st.readAt.UTC().Format(time.RFC3339)
+}
+
+// RunRegionNames keeps the map: a try at start, then a due check every
+// minute (no request unless due). watch is the record view's change watch,
+// nil when the index is not armed (the backstop alone).
+func (s *Server) RunRegionNames(ctx context.Context, watch *release.ChangeWatch) {
+ var gens scopeGens
+ if watch != nil {
+ gens = watch
+ }
+ for {
+ rctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout)
+ s.refreshRegionNames(rctx, gens, time.Now())
+ cancel()
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(regionNamesTick):
+ }
+ }
+}
+
+// LoadRegionNames is one refresh now, for callers outside this package that
+// need the map before they serve (the CLI's end-to-end tests). It reads
+// only when a read is due.
+func (s *Server) LoadRegionNames(ctx context.Context) bool {
+ return s.refreshRegionNames(ctx, nil, time.Now())
+}
diff --git a/internal/console/regionnames_test.go b/internal/console/regionnames_test.go
new file mode 100644
index 000000000..1827a4056
--- /dev/null
+++ b/internal/console/regionnames_test.go
@@ -0,0 +1,229 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/regionlabel"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// edgesCountStore counts the edges reads, and can refuse the listing or the
+// GET of one file.
+type edgesCountStore struct {
+ release.Store
+ mu sync.Mutex
+ lists, gets int
+ refuse bool // the listing fails
+ failGet string // a key whose GET fails
+}
+
+func (c *edgesCountStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if strings.HasPrefix(prefix, edgesfile.Prefix) {
+ c.mu.Lock()
+ c.lists++
+ refuse := c.refuse
+ c.mu.Unlock()
+ if refuse {
+ return nil, errors.New("listing refused")
+ }
+ }
+ return c.Store.List(ctx, prefix)
+}
+
+func (c *edgesCountStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if strings.HasPrefix(key, edgesfile.Prefix) {
+ c.mu.Lock()
+ c.gets++
+ fail := c.failGet == key
+ c.mu.Unlock()
+ if fail {
+ return nil, "", errors.New("GET refused")
+ }
+ }
+ return c.Store.Get(ctx, key)
+}
+
+func (c *edgesCountStore) counts() (lists, gets int) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.lists, c.gets
+}
+
+// fakeGens is a change index whose generation the test moves. It records
+// the scopes it was asked for.
+type fakeGens struct {
+ mu sync.Mutex
+ gen uint64
+ ok bool
+ scopes map[string]int
+}
+
+func (f *fakeGens) Gen(scope string) (uint64, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.scopes == nil {
+ f.scopes = map[string]int{}
+ }
+ f.scopes[scope]++
+ return f.gen, f.ok
+}
+
+// putRegionEdges writes control/edges/<box>.json as a box publishes it: a
+// dial address, its AWS region and its placement code, no hosts.
+func putRegionEdges(t *testing.T, s release.Store, box, placement, aws string) {
+ t.Helper()
+ body := fmt.Sprintf(`{"v":1,"box":%q,"eip":"192.0.2.10","region":%q,"placement":%q,"hosts":{}}`, box, aws, placement)
+ if _, err := s.Put(context.Background(), edgesfile.Key(box), []byte(body), ""); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestRegionNamesSchedule(t *testing.T) {
+ t0 := time.Date(2026, 10, 25, 9, 0, 0, 0, time.UTC)
+ var st regionNamesState
+ if !st.due(t0, 0, false) {
+ t.Fatal("the first read is due at once")
+ }
+ st.tryAt, st.readAt, st.read, st.lastOK, st.backstop = t0, t0, true, true, 30*time.Minute
+ st.gen, st.genKnown = 4, true
+ for _, c := range []struct {
+ name string
+ at time.Duration
+ gen uint64
+ ok bool
+ want bool
+ }{
+ {"quiet, before the backstop", 29 * time.Minute, 4, true, false},
+ {"quiet, at the backstop", 30 * time.Minute, 4, true, true},
+ {"edges moved, inside the floor", 9 * time.Minute, 5, true, false},
+ {"edges moved, at the floor", 10 * time.Minute, 5, true, true},
+ {"watch unusable: the backstop alone", 20 * time.Minute, 0, false, false},
+ } {
+ if got := st.due(t0.Add(c.at), c.gen, c.ok); got != c.want {
+ t.Errorf("%s: due = %v, want %v", c.name, got, c.want)
+ }
+ }
+ st.lastOK = false
+ if st.due(t0.Add(9*time.Minute), 4, true) || !st.due(t0.Add(10*time.Minute), 4, true) {
+ t.Fatal("a failed read is retried at the 10-minute floor, not sooner and not later")
+ }
+ for i := 0; i < 1000; i++ {
+ if b := regionNamesBackstop(); b < 27*time.Minute || b > 33*time.Minute {
+ t.Fatalf("backstop %s is outside 30 minutes ±10%%", b)
+ }
+ }
+}
+
+// TestRegionNamesKeepTheOldMapOnFailure: Review Focus 2, and spec §3.2:
+// a refused listing, a file that will not read and a file that will not
+// parse are each a failed rebuild, the first read included.
+func TestRegionNamesKeepTheOldMapOnFailure(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.HomeRegion = "ie"
+ cs := &edgesCountStore{Store: fx.rel}
+ fx.srv.cfg.Releases = cs
+ ctx, t0 := context.Background(), time.Now()
+ label := func(code string) string {
+ return regionlabel.ForCode(code, fx.srv.regionHome(), fx.srv.regionNames()).Text
+ }
+ putRegionEdges(t, fx.rel, "box-uk", "uk", "eu-west-2")
+ putRegionEdges(t, fx.rel, "box-au", "au", "ap-southeast-2")
+
+ // The first read, with one file refusing its GET: incomplete, so codes.
+ cs.failGet = edgesfile.Key("box-au")
+ if !fx.srv.refreshRegionNames(ctx, nil, t0) {
+ t.Fatal("the first read was not tried")
+ }
+ if label("uk") != "uk" || label("au") != "au" {
+ t.Fatalf("after an incomplete first read: %q, %q; want the codes", label("uk"), label("au"))
+ }
+ // Retried at the floor, not before; a malformed file is incomplete too.
+ cs.failGet = ""
+ if _, err := fx.rel.Put(ctx, edgesfile.Key("box-bad"), []byte("{not json"), ""); err != nil {
+ t.Fatal(err)
+ }
+ if fx.srv.refreshRegionNames(ctx, nil, t0.Add(9*time.Minute)) {
+ t.Fatal("a failed read is retried at the floor, not after 9 minutes")
+ }
+ if !fx.srv.refreshRegionNames(ctx, nil, t0.Add(10*time.Minute)) || label("uk") != "uk" {
+ t.Fatalf("a malformed file must keep the codes: %q", label("uk"))
+ }
+ // A complete read takes.
+ if err := fx.rel.Delete(ctx, edgesfile.Key("box-bad")); err != nil {
+ t.Fatal(err)
+ }
+ if !fx.srv.refreshRegionNames(ctx, nil, t0.Add(20*time.Minute)) || label("uk") != "London (uk)" || label("au") != "Sydney (au)" {
+ t.Fatalf("after a complete read: %q, %q", label("uk"), label("au"))
+ }
+ // A later refused listing, then a later refused GET, keep that map.
+ cs.refuse = true
+ fx.srv.refreshRegionNames(ctx, nil, t0.Add(2*time.Hour))
+ cs.refuse, cs.failGet = false, edgesfile.Key("box-uk")
+ fx.srv.refreshRegionNames(ctx, nil, t0.Add(3*time.Hour))
+ if label("uk") != "London (uk)" || label("au") != "Sydney (au)" {
+ t.Fatalf("a failed rebuild changed the map: %q, %q", label("uk"), label("au"))
+ }
+}
+
+// TestRegionNamesRequestBudget is §7's schedule: a quiet day, a busy day,
+// the scope asked for, and a generation change reaching the labels at the
+// floor and not before.
+func TestRegionNamesRequestBudget(t *testing.T) {
+ ctx := context.Background()
+ day := func(gens *fakeGens, bump bool) (lists, gets int) {
+ fx := newConsoleFixture(t)
+ cs := &edgesCountStore{Store: fx.rel}
+ fx.srv.cfg.Releases = cs
+ putRegionEdges(t, fx.rel, "box-ie", "", "eu-west-1")
+ putRegionEdges(t, fx.rel, "box-uk", "uk", "eu-west-2")
+ t0 := time.Now()
+ for m := 0; m < 24*60; m++ {
+ if bump {
+ gens.mu.Lock()
+ gens.gen++
+ gens.mu.Unlock()
+ }
+ fx.srv.refreshRegionNames(ctx, gens, t0.Add(time.Duration(m)*time.Minute))
+ }
+ return cs.counts()
+ }
+ quiet := &fakeGens{gen: 1, ok: true}
+ if lists, gets := day(quiet, false); lists < 44 || lists > 54 || gets != 2*lists {
+ t.Fatalf("a quiet day: %d listings and %d GETs, want 44 to 54 listings (48 with no jitter), two GETs each", lists, gets)
+ }
+ if len(quiet.scopes) != 1 || quiet.scopes[regionNamesScope] == 0 || regionNamesScope != "control/edges" {
+ t.Fatalf("the map asked the index for %v, want control/edges alone", quiet.scopes)
+ }
+ // Busy: the generation moves every minute, so a read every 10 minutes:
+ // 144, and never the backstop's 48.
+ if lists, gets := day(&fakeGens{ok: true}, true); lists < 140 || lists > 145 || gets != 2*lists {
+ t.Fatalf("a busy day: %d listings and %d GETs, want 140 to 145 listings, two GETs each", lists, gets)
+ }
+
+ // A generation change reaches the labels at the floor.
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.HomeRegion = "ie"
+ putRegionEdges(t, fx.rel, "box-uk", "uk", "eu-west-2")
+ gens := &fakeGens{gen: 7, ok: true}
+ t0 := time.Now()
+ fx.srv.refreshRegionNames(ctx, gens, t0)
+ putRegionEdges(t, fx.rel, "box-au", "au", "ap-southeast-2")
+ gens.mu.Lock()
+ gens.gen = 8
+ gens.mu.Unlock()
+ fx.srv.refreshRegionNames(ctx, gens, t0.Add(9*time.Minute))
+ if got := regionlabel.ForCode("au", "ie", fx.srv.regionNames()).Text; got != "au" {
+ t.Fatalf("inside the floor the new box is already read: %q", got)
+ }
+ fx.srv.refreshRegionNames(ctx, gens, t0.Add(10*time.Minute))
+ if got := regionlabel.ForCode("au", "ie", fx.srv.regionNames()).Text; got != "Sydney (au)" {
+ t.Fatalf("at the floor after a generation change: %q, want Sydney (au)", got)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 37df0eaa8..9f70f6dee 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1238,6 +1238,10 @@ type Server struct {
// (remoteinstances.go), held for boxReportTTL so the app pages ask the
// bucket at most once a minute however many people browse.
boxReports boxReportCache
+ // labelNames is the region name map the labels read (regionnames.go),
+ // rebuilt from one edges read at most every 10 minutes. The zero value
+ // is "nothing read yet": every label is its code.
+ labelNames regionNamesState
// retireBeforeDeleteHook, when set, runs in the canary retire between
// the follower check and the final record comparison. Tests only.
retireBeforeDeleteHook func()