console: the hostname-history activation window (Task 5)
Nearest-region never-reuse merge B, plan Task 5 (#404). The @mode object carries the window's facts (HostsState: from, roster, examined, closed; additive over merge A's mode-only body). begin (operators; refused with C11 under claims or Phase 1) opens the window from incomplete or invalidated; cancel returns to the mode begin started from (the accepted deviation: never from invalidated to incomplete). While it is open, data-kind creates get S8 and offline move starts and stages, move requests and placement get S7, each at its door after the caller gate. Admitted creates, moves and placements are counted until their handlers return; status adds that count and, in the window, the records whose move has not ended. The console reads the mode once at start, before serving. carlos system hosts-used begin and cancel print the approved B1-B3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 files changed,
+987
−121
cmd/console/main.go+8 −0docs/superpowers/notes/census-proposal-nearest-region-b.md+23 −0internal/console/apiinstancemove.go+18 −0internal/console/apiinstancemove_offline.go+18 −0internal/console/apiinstances.go+12 −0internal/console/apisidecars.go+9 −0internal/console/authcli.go+3 −0internal/console/claim_invariant_fixtures_test.go+12 −0internal/console/claim_invariant_test.go+2 −0internal/console/fleets.go+8 −0internal/console/hostsused.go+137 −80internal/console/hostsused_window.go+228 −0internal/console/hostsused_window_test.go+229 −0internal/console/hostsused_writers_test.go+6 −11internal/console/svcroutes_test.go+4 −2internal/console/testdata/claim-routes.txt+2 −0internal/provision/hostsused.go+46 −17internal/provision/hostsused_test.go+33 −0internal/provision/nearest_region_b_census_test.go+56 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv+12 −0system_hostsused.go+65 −9system_hostsused_test.go+54 −1
CI cancelled — superseded by a newer push — run details
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 4999eb450..af33302af 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -556,6 +556,14 @@ func serve() { |
| if err != nil { |
| log.Fatal(err) |
| } |
| + // The hostname history's mode, read once before the console serves |
| + // (nearest-region never-reuse spec §3a): one GET per start. Bounded, and |
| + // a failure is left for the first door that needs it, which refuses. |
| + func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + srv.LoadHostsMode(ctx) |
| + }() |
| // 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 |
diff --git a/docs/superpowers/notes/census-proposal-nearest-region-b.md b/docs/superpowers/notes/census-proposal-nearest-region-b.md| new file mode 100644 |
| index 000000000..089a38be6 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-nearest-region-b.md |
| @@ -0,0 +1,23 @@ |
| +# Census approval: nearest-region-b |
| + |
| +Ruling `census-ruling-nearest-region-b`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `cmd/console/main.go` `serve` | body | unchanged (3) | reads the hostname history mode once after NewServer (srv.LoadHostsMode, one GET of control/hosts-used/@mode in the deployment bucket through the console store, 20 s bound, logged on failure); nothing else changed; no root read added | |
| +| `internal/console/apiinstancemove.go` `Server.handleAPIInstanceMoveRequest` | body | unchanged (8) | admits through the hostname history (admitMoveOrPlace, an in-process mode check and count) after its operator gate and refuses with S7 while the window is open; every read and write after it unchanged; no read added | |
| +| `internal/console/fleets.go` `Server.placeAppTarget` | body | unchanged (7) | admits through the hostname history (admitMoveOrPlace) first and refuses with S7 while the window is open; every check, read and write after it unchanged; no read added | |
| + |
| +Envelopes re-pinned: `.`, `cmd/console`, `internal/console`, `internal/provision`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `cmd/console/main.go` `serve`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): Task 0 starts the lifetimes cutover watch, Task 3 the lifetime recovery pass and Task 5 the incarnation migration pass (off unless CARLOS_LIFETIMES_MIGRATE=1) beside the other claim workers; the same three data path literals move; no privileged reader is added;rev3=census-ruling-plans-6-checkout;basis=reads CARLOS_BILLING and the billing variables (billingConfig, a pure env parse plus the operator-configured CARLOS_PRICE_BOOK file through plans.LoadPriceBook, its own decision row) and fatals on a bad one; records the book version and digest in the console database (Store.NotePriceBook) and starts one more claim worker, StartBillingSyncPass, which returns at once with billing off; the same three /data literals; no read added;rev3=census-ruling-console-perf-1;basis=one perf.Recorder made before the stores: the deployment store (openStore(rec)) and the seed data store are wrapped by console.TimeS3Store so their S3 HTTP requests are timed and counted into it, and cfg.Perf carries it to NewServer; no read added, the three read sites unchanged;rev3=census-ruling-instance-egress-sizes-328-329;basis=main's body as of the merge of origin/main 5bba4bc1 (console perf plan 1's recorder and timed stores, under census-ruling-console-perf-1) plus #328/#329 plan 1 Task 8 and plan 2 Task 10: the server config gains PolicyLease from policyLeaseFor (the production leaser when CARLOS_DEPLOYMENT_BUCKET is set, nil otherwise, an env check only); a goroutine waits for SIGTERM or Interrupt, releases the app policy writer lease (srv.ReleasePolicyWriter) and exits; one more claim worker starts, StartEgressReport (the fleet-address report). The same three /data literals, offsets moved; no read added.;rev3=census-ruling-region-labels;basis=armChangeIndex also returns the change watch it builds, and serve starts the region name map loop (Server.RunRegionNames) with it: one control/edges/ LIST and a GET per box at start, then at most every 10 minutes on a control/edges generation change, else every 30 (±10%); the same three /data literals; no read added to serve itself |
| +- `internal/console/apiinstancemove.go` `Server.handleAPIInstanceMoveRequest`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-2a;basis=the console (cmd/console serve under console.service, user carlos-console): main's body with two refusals added before any write, both no room in the destination (H27): roomIn before the placement checks and moveRoomCheck's through selectMoveBoxes; read sites unchanged, offsets moved |
| +- `internal/console/fleets.go` `Server.placeAppTarget`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): the place's seed rule reads through placeSeedBlock with the context's judge, so a record its slot no longer vouches for neither blocks the place nor is stamped (SetRecordRegion under the same judge); unjudged before the cutover; read sites unchanged, offsets moved |
| + |
| +Seal: `798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c` → `d88dd686e93895ae62543e2b50750f05e99e8fbe592d2a67117f0ceb8985ad23`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go| index 5a51c6cb9..c78881270 100644 |
| --- a/internal/console/apiinstancemove.go |
| +++ b/internal/console/apiinstancemove.go |
| @@ -413,6 +413,15 @@ func (s *Server) legacyHandleAPIInstanceMoveRequest(w http.ResponseWriter, r *ht |
| if !ok { |
| return |
| } |
| + // The hostname history's admission (hostsused.go): no move is admitted |
| + // while the activation window is open (S7); an admitted one is counted |
| + // until this handler returns. |
| + done, ref := s.admitMoveOrPlace(r.Context()) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + defer done() |
| if s.refuseSeedMove(w, rec) { |
| return |
| } |
| @@ -569,6 +578,15 @@ func (s *Server) handleAPIInstanceMoveRequest(w http.ResponseWriter, r *http.Req |
| if !ok { |
| return |
| } |
| + // The hostname history's admission (hostsused.go): no move is admitted |
| + // while the activation window is open (S7); an admitted one is counted |
| + // until this handler returns. |
| + done, ref := s.admitMoveOrPlace(r.Context()) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + defer done() |
| if s.refuseSeedMove(w, rec) { |
| return |
| } |
diff --git a/internal/console/apiinstancemove_offline.go b/internal/console/apiinstancemove_offline.go| index 21c2341c7..f57573f7f 100644 |
| --- a/internal/console/apiinstancemove_offline.go |
| +++ b/internal/console/apiinstancemove_offline.go |
| @@ -620,6 +620,15 @@ func (s *Server) handleAPIInstanceOfflineStart(w http.ResponseWriter, r *http.Re |
| if !ok { |
| return |
| } |
| + // The hostname history's admission (hostsused.go): no move is admitted |
| + // while the activation window is open (S7); an admitted one is counted |
| + // until this handler returns. |
| + done, ref := s.admitMoveOrPlace(r.Context()) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + defer done() |
| to, fleet, ok := s.offlineBeginChecks(w, r, d) |
| if !ok { |
| return |
| @@ -658,6 +667,15 @@ func (s *Server) handleAPIInstanceOfflineStage(w http.ResponseWriter, r *http.Re |
| if !ok { |
| return |
| } |
| + // The hostname history's admission (hostsused.go): no move is admitted |
| + // while the activation window is open (S7); an admitted one is counted |
| + // until this handler returns. |
| + done, ref := s.admitMoveOrPlace(r.Context()) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + defer done() |
| to, fleet, ok := s.offlineBeginChecks(w, r, d) |
| if !ok { |
| return |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index ab11b4593..3adbd89a7 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1700,6 +1700,18 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| if s.refuseMemberUpstreams(w, p, rec.Addrs, nil) { |
| return |
| } |
| + // The hostname history's admission (hostsused.go): a data-kind create |
| + // is refused while the activation window is open (S8) or the history is |
| + // invalidated (S5), and is otherwise counted until this handler returns, |
| + // which is what the window's drain waits on. Exempt kinds pass. |
| + if rec.DataKind() { |
| + done, ref := s.admitDataCreate(r.Context(), rec.Host) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + defer done() |
| + } |
| // THE STORE IS PROVISIONED BEFORE THE RECORD IS WRITTEN, and a failure |
| // here means no record at all (issue #412, spec §7). This ordering is |
| // the load-bearing decision of the feature, so it is argued here rather |
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go| index 9916a4a65..915dd9605 100644 |
| --- a/internal/console/apisidecars.go |
| +++ b/internal/console/apisidecars.go |
| @@ -345,6 +345,15 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| } |
| + // The hostname history's admission (hostsused.go): a sidecar is always |
| + // a data kind. Refused while the window is open (S8) or the history is |
| + // invalidated (S5), and otherwise counted until this handler returns. |
| + done, ref := s.admitDataCreate(r.Context(), rec.Host) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + defer done() |
| // The leftover-replica rail (#199, createleftovers.go): a sidecar's host |
| // is derived from its name, so a name reused after a delete lands on the |
| // deleted sidecar's replica. Refused, after every validation above. |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index da8dde151..d0f55cdaa 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1074,6 +1074,9 @@ func (s *Server) registerCLIRoutes() { |
| // The hostname history's status (nearest-region never-reuse, plan Task |
| // 4, hostsused.go): apiSystemRoller, read-only. |
| s.cliRoute("GET /api/cli/system/hosts-used/status", svcrole.Set{}, s.handleAPIHostsUsedStatus) |
| + // The activation window (hostsused_window.go): apiSystemRoller. |
| + s.cliRoute("POST /api/cli/system/hosts-used/begin", svcrole.Set{}, s.handleAPIHostsUsedBegin) |
| + s.cliRoute("POST /api/cli/system/hosts-used/cancel", svcrole.Set{}, s.handleAPIHostsUsedCancel) |
| s.cliRoute("GET /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests) |
| s.cliRoute("POST /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests) |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 01acb8f1a..c1be65413 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1567,6 +1567,18 @@ var claimFixtures = map[string]claimFixture{ |
| // host claims: a claim console answers its 409 after the operator check |
| // and before it reads or writes anything. It names no app; the app here |
| // is the world's, whose foreign run proves nothing app-scoped moved. |
| + "route POST /api/cli/system/hosts-used/begin": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/begin", ""), |
| + status: http.StatusConflict, |
| + msg: msgHostsClaimsOn, |
| + }}, |
| + "route POST /api/cli/system/hosts-used/cancel": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/cancel", ""), |
| + status: http.StatusConflict, |
| + msg: msgHostsClaimsOn, |
| + }}, |
| "route POST /api/cli/system/lifetimes/cutover": {refused: &claimRefusalFixture{ |
| apps: claimRefs("bab/titogo"), |
| do: claimRefusedAPI(http.MethodPost, "/api/cli/system/lifetimes/cutover", ""), |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index f4921d5e1..6c8b5f6c4 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -115,6 +115,8 @@ var claimUnsupported = map[string]string{ |
| "no operation gates both, so every transfer is refused", |
| claimMoveResolveUnavailableMsg: "the operator's door out of a stuck move (CARLOS_MOVES_PHASE1) has only its gate until " + |
| "the Moves resolution body lands; it answers this sentence and writes nothing", |
| + msgHostsClaimsOn: "the hostname history is bound to claims off and Phase 1 moves off (nearest-region never-reuse spec §1); " + |
| + "the window doors refuse after their operator check and before they read or write anything", |
| msgLifetimesClaimsOn: "instance lifetimes are the claims-off console's protocol (self-serve moves plan 1); " + |
| "the cutover door refuses after its operator check and before it reads or writes anything", |
| claimDBReadResidencyMsg: "a forwarded db read needs the root signer, which a host-claim console never uses for it " + |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index 206269f4c..c912a1e98 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -568,6 +568,14 @@ const placeInstancesFailed = "could not update this app's instances — try agai |
| // refuses the whole request rather than silently doing the routes-only |
| // half. |
| func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target string) (status int, errMsg string) { |
| + // The hostname history's admission (hostsused.go): no placement while |
| + // the activation window is open (S7); an admitted one is counted until |
| + // it returns. |
| + done, ref := s.admitMoveOrPlace(ctx) |
| + if ref != nil { |
| + return ref.Status, ref.Msg |
| + } |
| + defer done() |
| // A temporary app stays on the shared fleet at its own platform address |
| // (spec §4, ruling 5, Task 6 review fix): placement would move its |
| // already-provisioned estate onto a fleet an automatic purge never |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index b3fd81990..a597c6c04 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -6,7 +6,6 @@ import ( |
| "log" |
| "net/http" |
| "os" |
| - "strings" |
| "sync" |
| "time" |
| @@ -37,38 +36,156 @@ func msgHostUnchecked(host string) string { |
| } |
| const ( |
| - msgHostsInvalidated = "New instances can't be created right now. Try again later." |
| - msgHostsActivating = "New instances can't be created during maintenance. Try again in a few minutes." |
| + msgHostsInvalidated = "New instances can't be created right now. Try again later." // S5 |
| + msgHostsActivating = "New instances can't be created during maintenance. Try again in a few minutes." // S8 |
| + msgHostsMovesPaused = "Moves and placement are paused for maintenance. Try again later." // S7 |
| ) |
| // hostsHistory is the process's copy of control/hosts-used/@mode. One |
| -// console process serves a deployment (spec §3a), so the mode is read once |
| -// per process and changed only by this process's own doors (Task 5). |
| +// console process serves a deployment (spec §3a): the state is read once, |
| +// before the first door needs it, and changed only by this process's own |
| +// doors (hostsTransition), in the store and here together. |
| type hostsHistory struct { |
| - mu sync.Mutex |
| - mode string // "" until read |
| + mu sync.Mutex |
| + state provision.HostsState // Mode "" until read |
| + etag string |
| + // admitted is the data-kind creates, moves and placements admitted and |
| + // still inside their handlers: the window's in-process drain count. |
| + admitted int |
| } |
| -// hostsMode is the history mode: read from the control store the first time |
| -// it is needed, then held. A failed read is not held, so the next caller |
| -// reads again, and it is an error, never a default: the caller refuses. |
| -// A console with no control store has no records to write, and reads |
| -// incomplete. |
| +// reset forgets the state, so the next caller reads the store again. A |
| +// console start, as far as the mode is concerned (tests use it to restart). |
| +func (h *hostsHistory) reset() { |
| + h.mu.Lock() |
| + h.state, h.etag = provision.HostsState{}, "" |
| + h.mu.Unlock() |
| +} |
| + |
| +// loadHostsLocked reads the state if it has not been read. A failed read is |
| +// not held: the next caller reads again, and the caller refuses, never |
| +// defaulting. A console with no control store writes no records and reads |
| +// incomplete. The caller holds s.hosts.mu. |
| +func (s *Server) loadHostsLocked(ctx context.Context) error { |
| + if s.hosts.state.Mode != "" { |
| + return nil |
| + } |
| + if s.cfg.Releases == nil { |
| + s.hosts.state = provision.HostsState{Mode: provision.HostsModeIncomplete} |
| + return nil |
| + } |
| + st, etag, err := provision.ReadHostsState(ctx, s.cfg.Releases) |
| + if err != nil { |
| + return err |
| + } |
| + s.hosts.state, s.hosts.etag = st, etag |
| + return nil |
| +} |
| + |
| +// hostsMode is the history mode, read the first time it is needed. |
| func (s *Server) hostsMode(ctx context.Context) (string, error) { |
| + st, err := s.hostsState(ctx) |
| + return st.Mode, err |
| +} |
| + |
| +// hostsState is a copy of the whole state, read the first time it is needed. |
| +func (s *Server) hostsState(ctx context.Context) (provision.HostsState, error) { |
| s.hosts.mu.Lock() |
| defer s.hosts.mu.Unlock() |
| - if s.hosts.mode != "" { |
| - return s.hosts.mode, nil |
| + if err := s.loadHostsLocked(ctx); err != nil { |
| + return provision.HostsState{}, err |
| } |
| - if s.cfg.Releases == nil { |
| - return provision.HostsModeIncomplete, nil |
| + return s.hosts.state, nil |
| +} |
| + |
| +// LoadHostsMode reads the history's state at console start, before the |
| +// console serves (spec §3a). A failure is logged and left for the first door |
| +// to read again, which refuses until it can. |
| +func (s *Server) LoadHostsMode(ctx context.Context) { |
| + if _, err := s.hostsMode(ctx); err != nil { |
| + log.Printf("console: hosts used: read the mode at start: %v (the first door that needs it reads it again)", err) |
| + } |
| +} |
| + |
| +// hostsTransition changes the state under the lock: next sees the current |
| +// state and answers the new one, or a refusal. The new state is written on |
| +// the ETag this process holds, then held. A conflict (another writer) drops |
| +// the held state, so the next caller reads the store again. |
| +func (s *Server) hostsTransition(ctx context.Context, next func(cur provision.HostsState) (provision.HostsState, *doorRefusal)) (provision.HostsState, *doorRefusal, error) { |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + if err := s.loadHostsLocked(ctx); err != nil { |
| + return provision.HostsState{}, nil, err |
| } |
| - mode, _, err := provision.ReadHostsMode(ctx, s.cfg.Releases) |
| + st, ref := next(s.hosts.state) |
| + if ref != nil { |
| + return s.hosts.state, ref, nil |
| + } |
| + st.At = time.Now().UTC() |
| + etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, st, s.hosts.etag) |
| if err != nil { |
| - return "", err |
| + if errors.Is(err, release.ErrCASConflict) { |
| + s.hosts.state, s.hosts.etag = provision.HostsState{}, "" |
| + } |
| + return provision.HostsState{}, nil, err |
| } |
| - s.hosts.mode = mode |
| - return mode, nil |
| + s.hosts.state, s.hosts.etag = st, etag |
| + return st, nil, nil |
| +} |
| + |
| +// admit counts one admitted request until its done is called. |
| +func (s *Server) admitLocked() func() { |
| + s.hosts.admitted++ |
| + var once sync.Once |
| + return func() { |
| + once.Do(func() { |
| + s.hosts.mu.Lock() |
| + s.hosts.admitted-- |
| + s.hosts.mu.Unlock() |
| + }) |
| + } |
| +} |
| + |
| +// admitDataCreate is a data-kind create door's admission (spec §3a): S8 |
| +// while the window is open, S5 once invalidated, and otherwise a count the |
| +// window's drain waits on, held until done. An unreadable mode refuses with |
| +// S2 for host, as the mark would. |
| +func (s *Server) admitDataCreate(ctx context.Context, host string) (done func(), ref *doorRefusal) { |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + if err := s.loadHostsLocked(ctx); err != nil { |
| + log.Printf("console: hosts used: read the mode to admit a create of %s: %v", host, err) |
| + return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(host)} |
| + } |
| + switch s.hosts.state.Mode { |
| + case provision.HostsModeActivating: |
| + return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsActivating} |
| + case provision.HostsModeInvalidated: |
| + return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated} |
| + } |
| + return s.admitLocked(), nil |
| +} |
| + |
| +// admitMoveOrPlace is a move or placement door's admission: S7 while the |
| +// window is open, otherwise counted until done, as a create is. |
| +func (s *Server) admitMoveOrPlace(ctx context.Context) (done func(), ref *doorRefusal) { |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + if err := s.loadHostsLocked(ctx); err != nil { |
| + log.Printf("console: hosts used: read the mode to admit a move or placement: %v", err) |
| + return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsMovesPaused} |
| + } |
| + if s.hosts.state.Mode == provision.HostsModeActivating { |
| + return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsMovesPaused} |
| + } |
| + return s.admitLocked(), nil |
| +} |
| + |
| +// hostsAdmitted is the in-process drain count. |
| +func (s *Server) hostsAdmitted() int { |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + return s.hosts.admitted |
| } |
| // hostsUsedError carries a mark refusal out of a create core that answers |
| @@ -182,63 +299,3 @@ func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarR |
| } |
| return provision.CreateSidecarRecord(ctx, s.cfg.Releases, rec) |
| } |
| - |
| -// hostsUsedStatus is GET /api/cli/system/hosts-used/status (plan Task 4). |
| -// InflightCreates and UnfinishedMoves are null until the activation window |
| -// (Task 5) counts them: a zero there would claim a drain this console |
| -// cannot see yet. |
| -type hostsUsedStatus struct { |
| - Mode string `json:"mode"` |
| - Marks int `json:"marks"` |
| - InflightCreates *int `json:"inflight_creates"` |
| - PendingAllocations int `json:"pending_allocations"` |
| - PendingRetirements int `json:"pending_retirements"` |
| - UnfinishedMoves *int `json:"unfinished_moves"` |
| -} |
| - |
| -// handleAPIHostsUsedStatus answers the history's mode and how many |
| -// hostnames it holds, counted by listing the prefix (a page per 1,000 |
| -// keys; an operator action, never polled), with the console's pending |
| -// lifetime rows. apiSystemRoller, like the other system doors. It writes |
| -// nothing. |
| -func (s *Server) handleAPIHostsUsedStatus(w http.ResponseWriter, r *http.Request) { |
| - if _, _, ok := s.apiSystemRoller(w, r); !ok { |
| - return |
| - } |
| - if !s.systemBucket(w) { |
| - return |
| - } |
| - ctx := r.Context() |
| - mode, err := s.hostsMode(ctx) |
| - if err != nil { |
| - log.Printf("console: hosts used status: read the mode: %v", err) |
| - jsonError(w, http.StatusBadGateway, "could not read the hostname history's mode. Try again.") |
| - return |
| - } |
| - keys, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix) |
| - if err != nil { |
| - log.Printf("console: hosts used status: list the marks: %v", err) |
| - jsonError(w, http.StatusBadGateway, "could not list the hostname history. Try again.") |
| - return |
| - } |
| - out := hostsUsedStatus{Mode: mode} |
| - for _, k := range keys { |
| - if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k { |
| - out.Marks++ |
| - } |
| - } |
| - allocs, err := s.store.PendingAllocations() |
| - if err != nil { |
| - log.Printf("console: hosts used status: pending allocations: %v", err) |
| - jsonError(w, http.StatusBadGateway, "could not read the console's pending creates. Try again.") |
| - return |
| - } |
| - rets, err := s.store.PendingRetirements() |
| - if err != nil { |
| - log.Printf("console: hosts used status: pending retirements: %v", err) |
| - jsonError(w, http.StatusBadGateway, "could not read the console's pending deletes. Try again.") |
| - return |
| - } |
| - out.PendingAllocations, out.PendingRetirements = len(allocs), len(rets) |
| - writeJSON(w, http.StatusOK, out) |
| -} |
diff --git a/internal/console/hostsused_window.go b/internal/console/hostsused_window.go| new file mode 100644 |
| index 000000000..ce1f9b5bf |
| --- /dev/null |
| +++ b/internal/console/hostsused_window.go |
| @@ -0,0 +1,228 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "log" |
| + "net/http" |
| + "os" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// The activation window (nearest-region never-reuse, spec §3a, plan Task 5) |
| +// and the history's status door (Task 4). begin opens the window: data-kind |
| +// creates (S8), move admissions and placement (S7) are refused while the |
| +// work admitted before it drains. status reports what is left. cancel |
| +// returns to the mode begin started from. Operators only (apiSystemRoller). |
| + |
| +// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse-b.md). |
| +const ( |
| + msgHostsAlreadyComplete = "The hostname history is already complete." // C1 |
| + msgHostsWindowOpen = "A maintenance window is already open." // C2 |
| + msgHostsNoWindow = "No maintenance window is open. Start one with carlos system hosts-used begin." // C3 |
| + msgHostsClaimsOn = "This console runs host claims or live moves, so the hostname history can't be completed." // C11 |
| +) |
| + |
| +// hostsUsedStatus is what the status, begin and cancel doors answer. |
| +// UnfinishedMoves is counted only while the window is open (it reads every |
| +// record), and is null otherwise. |
| +type hostsUsedStatus struct { |
| + Mode string `json:"mode"` |
| + Marks int `json:"marks"` |
| + InflightCreates *int `json:"inflight_creates"` |
| + PendingAllocations int `json:"pending_allocations"` |
| + PendingRetirements int `json:"pending_retirements"` |
| + UnfinishedMoves *int `json:"unfinished_moves"` |
| +} |
| + |
| +// hostsStatusFailure is a status read that failed: the log line's cause |
| +// and the door's diagnostic. |
| +type hostsStatusFailure struct { |
| + msg string |
| + err error |
| +} |
| + |
| +// hostsStatus reads the history's status: the mode, the marks counted by |
| +// listing the prefix (a page per 1,000 keys), the in-process admissions, |
| +// the console's pending lifetime rows and, while the window is open, the |
| +// records whose move has not ended (one apps/ listing and a GET per record). |
| +// An operator action, never polled. |
| +func (s *Server) hostsStatus(ctx context.Context) (hostsUsedStatus, *hostsStatusFailure) { |
| + st, err := s.hostsState(ctx) |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not read the hostname history's mode. Try again.", err} |
| + } |
| + keys, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix) |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not list the hostname history. Try again.", err} |
| + } |
| + out := hostsUsedStatus{Mode: st.Mode} |
| + for _, k := range keys { |
| + if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k { |
| + out.Marks++ |
| + } |
| + } |
| + admitted := s.hostsAdmitted() |
| + out.InflightCreates = &admitted |
| + allocs, err := s.store.PendingAllocations() |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not read the console's pending creates. Try again.", err} |
| + } |
| + rets, err := s.store.PendingRetirements() |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not read the console's pending deletes. Try again.", err} |
| + } |
| + out.PendingAllocations, out.PendingRetirements = len(allocs), len(rets) |
| + if st.Mode == provision.HostsModeActivating { |
| + n, err := s.unfinishedMoves(ctx) |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not read the instance records. Try again.", err} |
| + } |
| + out.UnfinishedMoves = &n |
| + } |
| + return out, nil |
| +} |
| + |
| +// unfinishedMoves counts the records under apps/ whose move has not ended: |
| +// Move is present only between a move's start and its terminal flip |
| +// (provision.Record.Move). A record body that does not decode drives no |
| +// move and is logged, not counted. |
| +func (s *Server) unfinishedMoves(ctx context.Context) (int, error) { |
| + keys, err := s.cfg.Releases.List(ctx, "apps/") |
| + if err != nil { |
| + return 0, err |
| + } |
| + n := 0 |
| + for _, k := range keys { |
| + if !provision.IsRecordKey(k) { |
| + continue |
| + } |
| + raw, _, err := s.cfg.Releases.Get(ctx, k) |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue // deleted since the listing |
| + } |
| + return 0, err |
| + } |
| + var body struct { |
| + Move json.RawMessage `json:"move"` |
| + } |
| + if err := json.Unmarshal(raw, &body); err != nil { |
| + log.Printf("console: hosts used: %s does not decode, so it drives no move: %v", k, err) |
| + continue |
| + } |
| + if len(body.Move) > 0 && string(body.Move) != "null" { |
| + n++ |
| + } |
| + } |
| + return n, nil |
| +} |
| + |
| +func (s *Server) writeHostsStatus(w http.ResponseWriter, ctx context.Context) { |
| + out, fail := s.hostsStatus(ctx) |
| + if fail != nil { |
| + log.Printf("console: hosts used status: %s (%v)", fail.msg, fail.err) |
| + jsonError(w, http.StatusBadGateway, fail.msg) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
| + |
| +// handleAPIHostsUsedStatus is GET /api/cli/system/hosts-used/status. It |
| +// writes nothing. |
| +func (s *Server) handleAPIHostsUsedStatus(w http.ResponseWriter, r *http.Request) { |
| + if _, _, ok := s.apiSystemRoller(w, r); !ok { |
| + return |
| + } |
| + if !s.systemBucket(w) { |
| + return |
| + } |
| + s.writeHostsStatus(w, r.Context()) |
| +} |
| + |
| +// hostsWriteFailed answers a mode write that failed. |
| +func hostsWriteFailed(w http.ResponseWriter, what string, err error) { |
| + log.Printf("console: hosts used %s: write the mode: %v", what, err) |
| + jsonError(w, http.StatusBadGateway, "could not write the hostname history's mode. Try again.") |
| +} |
| + |
| +// handleAPIHostsUsedBegin is POST /api/cli/system/hosts-used/begin: open the |
| +// window from incomplete, or from invalidated for a re-inventory. |
| +func (s *Server) handleAPIHostsUsedBegin(w http.ResponseWriter, r *http.Request) { |
| + addr, _, ok := s.apiSystemRoller(w, r) |
| + if !ok { |
| + return |
| + } |
| + if !s.systemBucket(w) { |
| + return |
| + } |
| + // The history is bound to claims off and Phase 1 off (spec §1): complete |
| + // refuses either, so the window is not opened for nothing. |
| + if s.cfg.HostClaim || s.cfg.MovesEnabled { |
| + jsonError(w, http.StatusConflict, msgHostsClaimsOn) |
| + return |
| + } |
| + ctx := r.Context() |
| + _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + switch cur.Mode { |
| + case provision.HostsModeActive: |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsAlreadyComplete} |
| + case provision.HostsModeActivating: |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsWindowOpen} |
| + } |
| + return provision.HostsState{Mode: provision.HostsModeActivating, From: cur.Mode}, nil |
| + }) |
| + switch { |
| + case err != nil: |
| + hostsWriteFailed(w, "begin", err) |
| + return |
| + case ref != nil: |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + log.Printf("console: hosts used: %s opened the maintenance window", addr) |
| + s.writeHostsStatus(w, ctx) |
| +} |
| + |
| +// handleAPIHostsUsedCancel is POST /api/cli/system/hosts-used/cancel: close |
| +// the window, back to the mode begin started from. A window opened from |
| +// invalidated goes back to invalidated, never to incomplete (an accepted |
| +// deviation from spec §3a item 5): cancelling a re-inventory never turns the |
| +// refusals off. |
| +func (s *Server) handleAPIHostsUsedCancel(w http.ResponseWriter, r *http.Request) { |
| + addr, _, ok := s.apiSystemRoller(w, r) |
| + if !ok { |
| + return |
| + } |
| + if !s.systemBucket(w) { |
| + return |
| + } |
| + if s.cfg.HostClaim || s.cfg.MovesEnabled { |
| + jsonError(w, http.StatusConflict, msgHostsClaimsOn) |
| + return |
| + } |
| + ctx := r.Context() |
| + _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + if cur.Mode != provision.HostsModeActivating { |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsNoWindow} |
| + } |
| + back := provision.HostsModeIncomplete |
| + if cur.From == provision.HostsModeInvalidated { |
| + back = provision.HostsModeInvalidated |
| + } |
| + return provision.HostsState{Mode: back}, nil |
| + }) |
| + switch { |
| + case err != nil: |
| + hostsWriteFailed(w, "cancel", err) |
| + return |
| + case ref != nil: |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + log.Printf("console: hosts used: %s closed the maintenance window", addr) |
| + s.writeHostsStatus(w, ctx) |
| +} |
diff --git a/internal/console/hostsused_window_test.go b/internal/console/hostsused_window_test.go| new file mode 100644 |
| index 000000000..f6375346d |
| --- /dev/null |
| +++ b/internal/console/hostsused_window_test.go |
| @@ -0,0 +1,229 @@ |
| +package console |
| + |
| +// The activation window (nearest-region never-reuse plan, Task 5; spec |
| +// §3a): begin stops data-kind creates, move admissions and placement, the |
| +// work admitted before it drains and is counted, and cancel returns to the |
| +// mode begin started from. Through the real doors. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +const ( |
| + hostsUsedBeginURL = "/api/cli/system/hosts-used/begin" |
| + hostsUsedCancelURL = "/api/cli/system/hosts-used/cancel" |
| +) |
| + |
| +// hostsDoor calls a hosts-used system door as token and decodes its JSON. |
| +func hostsDoor(t *testing.T, fx *consoleFixture, method, path, token, body string) (int, map[string]any) { |
| + t.Helper() |
| + code, _, out := rawReq(t, method, fx.ts.URL+path, token, body) |
| + var m map[string]any |
| + _ = json.Unmarshal([]byte(out), &m) |
| + if m == nil { |
| + m = map[string]any{"raw": out} |
| + } |
| + return code, m |
| +} |
| + |
| +func begin(t *testing.T, l lifetimesFx) map[string]any { |
| + t.Helper() |
| + code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`) |
| + if code != http.StatusOK || st["mode"] != provision.HostsModeActivating { |
| + t.Fatalf("begin = %d %v", code, st) |
| + } |
| + return st |
| +} |
| + |
| +func statusOf(t *testing.T, l lifetimesFx) map[string]any { |
| + t.Helper() |
| + code, st := hostsDoor(t, l.fx, http.MethodGet, hostsUsedStatusURL, l.operator, "") |
| + if code != http.StatusOK { |
| + t.Fatalf("status = %d %v", code, st) |
| + } |
| + return st |
| +} |
| + |
| +func createAs(t *testing.T, l lifetimesFx, body string) (int, string) { |
| + t.Helper() |
| + code, _, out := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, body) |
| + return code, out |
| +} |
| + |
| +func TestBeginIsOperatorOnly(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + for _, path := range []string{hostsUsedBeginURL, hostsUsedCancelURL} { |
| + if code, _ := hostsDoor(t, l.fx, http.MethodPost, path, l.member, `{}`); code != http.StatusNotFound { |
| + t.Fatalf("a member's %s = %d, want 404", path, code) |
| + } |
| + } |
| + if st := statusOf(t, l); st["mode"] != provision.HostsModeIncomplete { |
| + t.Fatalf("mode after refused doors = %v", st["mode"]) |
| + } |
| +} |
| + |
| +func TestBeginStopsAdmissions(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + const one = "one.shop.example.com" |
| + if code, out := createAs(t, l, `{"host":"`+one+`"}`); code != http.StatusCreated { |
| + t.Fatalf("create before begin = %d %s", code, out) |
| + } |
| + begin(t, l) |
| + code, out := createAs(t, l, `{"host":"two.shop.example.com"}`) |
| + if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsActivating { |
| + t.Fatalf("data-kind create in the window = %d %s, want 503 S8", code, out) |
| + } |
| + if raw, _ := rawOf(t, l.fx.rel, ltApp, "two.shop.example.com"); raw != nil { |
| + t.Fatal("a record was written in the window") |
| + } |
| + if code, out := createAs(t, l, `{"host":"site.shop.example.com","kind":"static"}`); code != http.StatusCreated { |
| + t.Fatalf("static create in the window = %d %s, want 201", code, out) |
| + } |
| + for _, c := range []struct{ name, path, body string }{ |
| + {"offline start", "/api/cli/apps/bab/" + ltApp + "/instances/" + one + "/move/offline", `{"to":"uk"}`}, |
| + {"offline stage", "/api/cli/apps/bab/" + ltApp + "/instances/" + one + "/move/offline/stage", `{"to":"uk"}`}, |
| + {"move", "/api/cli/apps/bab/" + ltApp + "/instances/" + one + "/move", `{"to":"uk"}`}, |
| + {"place", "/api/cli/apps/bab/" + ltApp + "/place", `{"target":""}`}, |
| + } { |
| + code, _, out := rawReq(t, http.MethodPost, l.fx.ts.URL+c.path, l.operator, c.body) |
| + if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsMovesPaused { |
| + t.Errorf("%s in the window = %d %s, want 503 S7", c.name, code, out) |
| + } |
| + } |
| + // The window stays open across a refused admission. |
| + if st := statusOf(t, l); st["mode"] != provision.HostsModeActivating { |
| + t.Fatalf("mode = %v", st["mode"]) |
| + } |
| +} |
| + |
| +func TestSidecarCreateRefusedInTheWindow(t *testing.T) { |
| + fx := leftoverFixture(t, "code-window-sidecar") |
| + forceHostsMode(t, fx.srv, provision.HostsModeActivating) |
| + code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"ie"}`) |
| + if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsActivating { |
| + t.Fatalf("sidecar create in the window = %d %s, want 503 S8", code, out) |
| + } |
| + forceHostsMode(t, fx.srv, provision.HostsModeInvalidated) |
| + code, _, out = rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"ie"}`) |
| + if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated { |
| + t.Fatalf("sidecar create invalidated = %d %s, want 503 S5", code, out) |
| + } |
| +} |
| + |
| +// TestDrainWaitsForAdmittedMove: a record whose Move is not terminal keeps |
| +// unfinished_moves at 1 until the move ends. |
| +func TestDrainWaitsForAdmittedMove(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + const host = "moving.shop.example.com" |
| + rec := provision.Record{Schema: 1, Host: host, Slug: "moving", App: ltApp, Account: "bab", Channel: "stable", |
| + CreatedAt: time.Now().UTC(), Move: &provision.MoveState{ID: "mv_abcdefghijklmnopqrstuvwxyz", To: "uk", State: "requested", RequestedAt: time.Now().UTC()}} |
| + if err := provision.CreateRecord(context.Background(), l.fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st := statusOf(t, l); st["unfinished_moves"] != nil { |
| + t.Fatalf("unfinished_moves outside the window = %v, want null", st["unfinished_moves"]) |
| + } |
| + begin(t, l) |
| + if st := statusOf(t, l); st["unfinished_moves"] != float64(1) { |
| + t.Fatalf("unfinished_moves = %v, want 1", st["unfinished_moves"]) |
| + } |
| + got, etag, err := provision.GetRecordETag(context.Background(), l.fx.rel, "bab", ltApp, host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got.Move = nil |
| + if err := provision.UpdateRecord(context.Background(), l.fx.rel, *got, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st := statusOf(t, l); st["unfinished_moves"] != float64(0) { |
| + t.Fatalf("unfinished_moves after the move ended = %v, want 0", st["unfinished_moves"]) |
| + } |
| +} |
| + |
| +// TestDrainCountsInflightCreate: a create admitted before begin and still in |
| +// its handler is counted until the handler returns, and it cannot persist |
| +// once the window is open. |
| +func TestDrainCountsInflightCreate(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + bucket := <Store{Store: l.fx.rel} |
| + l.fx.srv.cfg.Releases = bucket |
| + const host = "slow.shop.example.com" |
| + markGate, markHook := pauseNth(t, "put", provision.HostsUsedKey(host), 1) |
| + bucket.setHook(markHook) |
| + done := make(chan struct{}) |
| + var code int |
| + var out string |
| + go func() { |
| + defer close(done) |
| + code, _, out = rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, `{"host":"`+host+`"}`) |
| + }() |
| + <-markGate.entered |
| + bucket.setHook(nil) |
| + begin(t, l) |
| + if st := statusOf(t, l); st["inflight_creates"] != float64(1) { |
| + t.Fatalf("inflight_creates = %v, want 1", st["inflight_creates"]) |
| + } |
| + markGate.open() |
| + <-done |
| + if code != http.StatusCreated { |
| + t.Fatalf("the in-flight create = %d %s, want it to finish", code, out) |
| + } |
| + if st := statusOf(t, l); st["inflight_creates"] != float64(0) { |
| + t.Fatalf("inflight_creates after the handler returned = %v, want 0", st["inflight_creates"]) |
| + } |
| +} |
| + |
| +func TestActivatingSurvivesRestart(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + begin(t, l) |
| + srv, err := NewServer(l.fx.srv.cfg, l.fx.st) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mode, err := srv.hostsMode(context.Background()) |
| + if err != nil || mode != provision.HostsModeActivating { |
| + t.Fatalf("the restarted console's mode = %q %v, want activating", mode, err) |
| + } |
| + if done, ref := srv.admitDataCreate(context.Background(), "x.shop.example.com"); ref == nil || ref.Msg != msgHostsActivating { |
| + if done != nil { |
| + done() |
| + } |
| + t.Fatalf("the restarted console admitted a data-kind create: %+v", ref) |
| + } |
| +} |
| + |
| +func TestCancelReturnsToIncomplete(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + if code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`); code != http.StatusConflict || st["error"] != msgHostsNoWindow { |
| + t.Fatalf("cancel with no window = %d %v, want 409 C3", code, st) |
| + } |
| + begin(t, l) |
| + if code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`); code != http.StatusConflict || st["error"] != msgHostsWindowOpen { |
| + t.Fatalf("a second begin = %d %v, want 409 C2", code, st) |
| + } |
| + code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`) |
| + if code != http.StatusOK || st["mode"] != provision.HostsModeIncomplete { |
| + t.Fatalf("cancel = %d %v", code, st) |
| + } |
| + if code, out := createAs(t, l, `{"host":"after.shop.example.com"}`); code != http.StatusCreated { |
| + t.Fatalf("create after cancel = %d %s", code, out) |
| + } |
| + // A window opened from invalidated goes back to invalidated (accepted |
| + // deviation, spec §3a item 5). |
| + forceHostsMode(t, l.fx.srv, provision.HostsModeInvalidated) |
| + begin(t, l) |
| + code, st = hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`) |
| + if code != http.StatusOK || st["mode"] != provision.HostsModeInvalidated { |
| + t.Fatalf("cancel of a re-inventory = %d %v, want invalidated", code, st) |
| + } |
| + forceHostsMode(t, l.fx.srv, provision.HostsModeActive) |
| + if code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`); code != http.StatusConflict || st["error"] != msgHostsAlreadyComplete { |
| + t.Fatalf("begin when active = %d %v, want 409 C1", code, st) |
| + } |
| +} |
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go| index 2996de63e..9ad0a684e 100644 |
| --- a/internal/console/hostsused_writers_test.go |
| +++ b/internal/console/hostsused_writers_test.go |
| @@ -176,9 +176,7 @@ func forceHostsMode(t *testing.T, srv *Server, mode string) { |
| if _, err := provision.WriteHostsMode(ctx, srv.cfg.Releases, mode, etag); err != nil { |
| t.Fatal(err) |
| } |
| - srv.hosts.mu.Lock() |
| - srv.hosts.mode = "" |
| - srv.hosts.mu.Unlock() |
| + srv.hosts.reset() |
| if got, err := srv.hostsMode(ctx); err != nil || got != mode { |
| t.Fatalf("hostsMode = %q %v, want %q", got, err, mode) |
| } |
| @@ -296,9 +294,7 @@ func TestMarkErrorRefusesInIncomplete(t *testing.T) { |
| // TestModeReadErrorRefuses: a mode that cannot be read is never a default. |
| func TestModeReadErrorRefuses(t *testing.T) { |
| eachMarkDoor(t, func(t *testing.T, c markCase) { |
| - c.fx.srv.hosts.mu.Lock() |
| - c.fx.srv.hosts.mode = "" |
| - c.fx.srv.hosts.mu.Unlock() |
| + c.fx.srv.hosts.reset() |
| c.bucket.setHook(failNth("get", provision.HostsModeKey, 1, true)) |
| code, out := c.create(t) |
| c.bucket.setHook(nil) |
| @@ -564,15 +560,14 @@ func TestHostsUsedStatusDoor(t *testing.T) { |
| if code != http.StatusOK || st["mode"] != provision.HostsModeIncomplete || st["marks"] != float64(0) { |
| t.Fatalf("empty status = %d %v", code, st) |
| } |
| - for _, k := range []string{"pending_allocations", "pending_retirements"} { |
| + for _, k := range []string{"pending_allocations", "pending_retirements", "inflight_creates"} { |
| if st[k] != float64(0) { |
| t.Fatalf("%s = %v, want 0", k, st[k]) |
| } |
| } |
| - for _, k := range []string{"inflight_creates", "unfinished_moves"} { |
| - if v, ok := st[k]; !ok || v != nil { |
| - t.Fatalf("%s = %v (present %v), want null until the activation window exists", k, v, ok) |
| - } |
| + // Moves are counted only while the window is open (Task 5). |
| + if v, ok := st["unfinished_moves"]; !ok || v != nil { |
| + t.Fatalf("unfinished_moves = %v (present %v), want null outside the window", v, ok) |
| } |
| for _, host := range []string{"a.shop.example.com", "b.shop.example.com"} { |
| if code, out := (ltOn{lifetimesFx: l}).create(t, host); code != http.StatusCreated { |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index d3ed03c36..9e6b20a4a 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -294,6 +294,8 @@ var closedDoors = []string{ |
| // The hostname history's status (nearest-region never-reuse): an |
| // operator's deployment-wide view, the same cut. |
| "GET /api/cli/system/hosts-used/status", |
| + "POST /api/cli/system/hosts-used/begin", |
| + "POST /api/cli/system/hosts-used/cancel", |
| // `carlos channels resign`: the console signs digests a person has |
| // confirmed. A credential never confirms on a person's behalf. |
| "POST /api/cli/apps/{account}/{app}/channels/resign", |
| @@ -1103,8 +1105,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 67 { |
| - t.Errorf("walked %d closed doors, want all %d (and 67 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)", |
| + if seen != len(closedDoors) || seen != 69 { |
| + t.Errorf("walked %d closed doors, want all %d (and 69 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status and its two window doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)", |
| seen, len(closedDoors)) |
| } |
| } |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 908a5fda2..af22e6caa 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -267,6 +267,8 @@ route POST /api/cli/services/{account}/{name}/rotate |
| route POST /api/cli/system/activation/cancel |
| route POST /api/cli/system/antivirus |
| route POST /api/cli/system/antivirus/rotate-webhook-key |
| +route POST /api/cli/system/hosts-used/begin |
| +route POST /api/cli/system/hosts-used/cancel |
| route POST /api/cli/system/layout |
| route POST /api/cli/system/legacy-routes |
| route POST /api/cli/system/lifetimes/cutover |
diff --git a/internal/provision/hostsused.go b/internal/provision/hostsused.go| index 14469660f..492e3d013 100644 |
| --- a/internal/provision/hostsused.go |
| +++ b/internal/provision/hostsused.go |
| @@ -123,43 +123,72 @@ func validHostsMode(m string) bool { |
| return false |
| } |
| -type hostsModeBody struct { |
| +// HostsState is the @mode object: the mode, and the facts that go with it. |
| +// A merge-A body carries the mode alone, and still reads. |
| +type HostsState struct { |
| Mode string `json:"mode"` |
| + // From is the mode an open window (activating) returns to on cancel: |
| + // incomplete, or invalidated for a re-inventory. |
| + From string `json:"from,omitempty"` |
| + // Roster is the targets fixed when the window opened ("box:<box>", |
| + // "bucket:<bucket>"), which complete needs listings for. |
| + Roster []string `json:"roster,omitempty"` |
| + // Examined is the regions, pools and fleets complete examined |
| + // ("region:<code>", "pool:<name>", "fleet:<name>"). A data-kind create |
| + // anywhere else is refused once active. |
| + Examined []string `json:"examined,omitempty"` |
| + // Closed is the fleets closed instead of scanned ("fleet:<name>"), |
| + // which take no data-kind create. |
| + Closed []string `json:"closed,omitempty"` |
| + // Reason says why the history was invalidated. |
| + Reason string `json:"reason,omitempty"` |
| + At time.Time `json:"at,omitempty"` |
| } |
| -// ReadHostsMode reads @mode. Absent is (incomplete, "", nil). A body that |
| -// does not name a known mode is an error, never a default. |
| -func ReadHostsMode(ctx context.Context, s release.Store) (mode, etag string, err error) { |
| +// ReadHostsState reads @mode. Absent is {Mode: incomplete} with no ETag. A |
| +// body that does not name a known mode is an error, never a default. |
| +func ReadHostsState(ctx context.Context, s release.Store) (HostsState, string, error) { |
| raw, etag, err := s.Get(ctx, HostsModeKey) |
| if errors.Is(err, os.ErrNotExist) { |
| - return HostsModeIncomplete, "", nil |
| + return HostsState{Mode: HostsModeIncomplete}, "", nil |
| } |
| if err != nil { |
| - return "", "", err |
| + return HostsState{}, "", err |
| } |
| - var b hostsModeBody |
| - if err := json.Unmarshal(raw, &b); err != nil { |
| - return "", "", fmt.Errorf("provision: hosts used: %s: %w", HostsModeKey, err) |
| + var st HostsState |
| + if err := json.Unmarshal(raw, &st); err != nil { |
| + return HostsState{}, "", fmt.Errorf("provision: hosts used: %s: %w", HostsModeKey, err) |
| } |
| - if !validHostsMode(b.Mode) { |
| - return "", "", fmt.Errorf("provision: hosts used: %s names no known mode (%q)", HostsModeKey, b.Mode) |
| + if !validHostsMode(st.Mode) { |
| + return HostsState{}, "", fmt.Errorf("provision: hosts used: %s names no known mode (%q)", HostsModeKey, st.Mode) |
| } |
| - return b.Mode, etag, nil |
| + return st, etag, nil |
| } |
| -// WriteHostsMode writes @mode on ifMatch ("" is create-only, as Store.Put) |
| +// WriteHostsState writes @mode on ifMatch ("" is create-only, as Store.Put) |
| // and returns the new ETag. A lost race is release.ErrCASConflict. |
| -func WriteHostsMode(ctx context.Context, s release.Store, mode, ifMatch string) (string, error) { |
| - if !validHostsMode(mode) { |
| - return "", fmt.Errorf("provision: hosts used: unknown mode %q", mode) |
| +func WriteHostsState(ctx context.Context, s release.Store, st HostsState, ifMatch string) (string, error) { |
| + if !validHostsMode(st.Mode) { |
| + return "", fmt.Errorf("provision: hosts used: unknown mode %q", st.Mode) |
| } |
| - body, err := json.Marshal(hostsModeBody{Mode: mode}) |
| + body, err := json.Marshal(st) |
| if err != nil { |
| return "", err |
| } |
| return s.Put(ctx, HostsModeKey, body, ifMatch) |
| } |
| +// ReadHostsMode reads @mode's mode alone (ReadHostsState). |
| +func ReadHostsMode(ctx context.Context, s release.Store) (mode, etag string, err error) { |
| + st, etag, err := ReadHostsState(ctx, s) |
| + return st.Mode, etag, err |
| +} |
| + |
| +// WriteHostsMode writes a state carrying the mode alone (WriteHostsState). |
| +func WriteHostsMode(ctx context.Context, s release.Store, mode, ifMatch string) (string, error) { |
| + return WriteHostsState(ctx, s, HostsState{Mode: mode}, ifMatch) |
| +} |
| + |
| // HostsFloor is the oldest console and CLI build allowed to write records |
| // once the history is active (spec §4). |
| type HostsFloor struct { |
diff --git a/internal/provision/hostsused_test.go b/internal/provision/hostsused_test.go| index 0a67f51ca..f34160f4a 100644 |
| --- a/internal/provision/hostsused_test.go |
| +++ b/internal/provision/hostsused_test.go |
| @@ -276,3 +276,36 @@ func mustDecodeKind(t *testing.T, raw string) string { |
| } |
| return rec.Kind |
| } |
| + |
| +// TestHostsStateRoundTrips: the mode object carries the window's facts |
| +// beside the mode (merge B), and a merge-A body, mode alone, still reads. |
| +func TestHostsStateRoundTrips(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + ctx := context.Background() |
| + st, etag, err := ReadHostsState(ctx, s) |
| + if err != nil || st.Mode != HostsModeIncomplete || etag != "" { |
| + t.Fatalf("empty = %+v %q %v", st, etag, err) |
| + } |
| + if _, err := s.Put(ctx, HostsModeKey, []byte(`{"mode":"incomplete"}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, etag, err = ReadHostsState(ctx, s) |
| + if err != nil || st.Mode != HostsModeIncomplete || etag == "" { |
| + t.Fatalf("merge-A body = %+v %q %v", st, etag, err) |
| + } |
| + want := HostsState{Mode: HostsModeActivating, From: HostsModeInvalidated, Roster: []string{"box:a", "bucket:b"}, |
| + Closed: []string{"fleet:f"}, Examined: []string{"region:uk"}, Reason: "r"} |
| + if _, err := WriteHostsState(ctx, s, want, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, _, err := ReadHostsState(ctx, s) |
| + if err != nil || got.Mode != want.Mode || got.From != want.From || len(got.Roster) != 2 || got.Closed[0] != "fleet:f" || got.Examined[0] != "region:uk" || got.Reason != "r" { |
| + t.Fatalf("round trip = %+v %v", got, err) |
| + } |
| + if mode, _, err := ReadHostsMode(ctx, s); err != nil || mode != HostsModeActivating { |
| + t.Fatalf("ReadHostsMode = %q %v", mode, err) |
| + } |
| + if _, err := WriteHostsState(ctx, s, HostsState{Mode: "sideways"}, ""); err == nil { |
| + t.Fatal("an unknown mode was written") |
| + } |
| +} |
diff --git a/internal/provision/nearest_region_b_census_test.go b/internal/provision/nearest_region_b_census_test.go| new file mode 100644 |
| index 000000000..43aa893af |
| --- /dev/null |
| +++ b/internal/provision/nearest_region_b_census_test.go |
| @@ -0,0 +1,56 @@ |
| +package provision |
| + |
| +// Record-write census entries for nearest-region never-reuse merge B (branch |
| +// nearest-region-b, plan docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md |
| +// Tasks 5-10 and 13), layered on nearestRegionAWriteCensusInventory (main's |
| +// newest at 70d37672). Reviewed by the branch author; the census approval |
| +// is recorded on #280 with the root-read card |
| +// (docs/superpowers/notes/census-proposal-nearest-region-b.md). |
| +// - WriteHostsState (provision), new: the one Put of control/hosts-used/@mode, |
| +// the state with its window facts. No record key or body: nonrecord. |
| +// WriteHostsMode now writes through it and leaves the inventory. |
| +// - Server.unfinishedMoves (console), new: lists apps/ and reads each |
| +// record key (IsRecordKey) to count moves not ended. Reads only: key-site. |
| +// - Server.handleAPIInstanceMoveRequest, Server.placeAppTarget, re-pinned: |
| +// each admits through the hostname history (admitMoveOrPlace) before |
| +// anything else and is refused while the window is open. Their write |
| +// sites are unchanged: still record-writer. |
| +// - Server.registerCLIRoutes, re-pinned: the window's doors. Same |
| +// literals: still key-site. |
| +func nearestRegionBWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), nearestRegionAWriteCensusInventory()...) |
| + for _, r := range []struct{ file, unit string }{ |
| + {"internal/provision/hostsused.go", "WriteHostsMode"}, |
| + } { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.file && e.Unit == r.unit { |
| + entries = append(entries[:i], entries[i+1:]...) |
| + found = true |
| + break |
| + } |
| + } |
| + if !found { |
| + panic("nearest-region-b removal of an unlisted unit " + r.file + ":" + r.unit) |
| + } |
| + } |
| + replacements := []censusEntry{ |
| + {"internal/provision/hostsused.go", "WriteHostsState", "nonrecord", "sel:Put", "5f1b95198e45dedc9715d73a57bfa57cb1305d364895cd981375e0ed3610c8da"}, |
| + {"internal/console/hostsused_window.go", "Server.unfinishedMoves", "key-site", "key:IsRecordKey", "797c355d9aa71c432fc3953673198df46fb1f3d3597ac65390c2e71af2344428"}, |
| + {"internal/console/apiinstancemove.go", "Server.handleAPIInstanceMoveRequest", "record-writer", "key:SetRecordMove,lit:instances", "7366c131cf6643449687eac2e56e55b5b55c51434b00123c339bb66067f3d413"}, |
| + {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "e9fe8c1b6cddba8902c269f2358ab3394edbb78d8fe9cab57c3ba5918d1e29e0"}, |
| + {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "a2c16f07a2b685cf6de7a90e1b1ad9a07224d2a76245a9dd1c9bca508ccbff8e"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index e3496027a..624e61fc6 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := nearestRegionAWriteCensusInventory() |
| + inventory := nearestRegionBWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 83161f11f..536b8e6c1 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -59,3 +59,4 @@ plan14-root-reads-region-labels-decisions.tsv b265c2ae74edbaca766d33e085d31a8e7c |
| plan14-root-reads-region-labels.tsv d1e00cfb29d88b7a8e4998b641164e539067a6e1e9e4f52524255343c0c5f9f7 |
| plan14-root-reads-app-region-set.tsv 798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c |
| plan14-root-reads-nearest-region-a.tsv 798a1ee3d8c8b775f963b9ae1dbc45e18628fa0c1e63404f46606601766ad66c |
| +plan14-root-reads-nearest-region-b.tsv d88dd686e93895ae62543e2b50750f05e99e8fbe592d2a67117f0ceb8985ad23 |
diff --git a/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv b/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv| new file mode 100644 |
| index 000000000..f35b81247 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv |
| @@ -0,0 +1,12 @@ |
| +# Census overlay nearest-region-b, written by census-propose (#369). census-ruling-nearest-region-b, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-nearest-region-b.md. |
| +# 3 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 6b1771a662a6acd2d107076c94fd8ee10ec6afe389e8d70cdcbb7df99bba396f cmd/console/main.go serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): Task 0 starts the lifetimes cutover watch, Task 3 the lifetime recovery pass and Task 5 the incarnation migration pass (off unless CARLOS_LIFETIMES_MIGRATE=1) beside the other claim workers; the same three data path literals move; no privileged reader is added;rev3=census-ruling-plans-6-checkout;basis=reads CARLOS_BILLING and the billing variables (billingConfig, a pure env parse plus the operator-configured CARLOS_PRICE_BOOK file through plans.LoadPriceBook, its own decision row) and fatals on a bad one; records the book version and digest in the console database (Store.NotePriceBook) and starts one more claim worker, StartBillingSyncPass, which returns at once with billing off; the same three /data literals; no read added;rev3=census-ruling-console-perf-1;basis=one perf.Recorder made before the stores: the deployment store (openStore(rec)) and the seed data store are wrapped by console.TimeS3Store so their S3 HTTP requests are timed and counted into it, and cfg.Perf carries it to NewServer; no read added, the three read sites unchanged;rev3=census-ruling-instance-egress-sizes-328-329;basis=main's body as of the merge of origin/main 5bba4bc1 (console perf plan 1's recorder and timed stores, under census-ruling-console-perf-1) plus #328/#329 plan 1 Task 8 and plan 2 Task 10: the server config gains PolicyLease from policyLeaseFor (the production leaser when CARLOS_DEPLOYMENT_BUCKET is set, nil otherwise, an env check only); a goroutine waits for SIGTERM or Interrupt, releases the app policy writer lease (srv.ReleasePolicyWriter) and exits; one more claim worker starts, StartEgressReport (the fleet-address report). The same three /data literals, offsets moved; no read added.;rev3=census-ruling-region-labels;basis=armChangeIndex also returns the change watch it builds, and serve starts the region name map loop (Server.RunRegionNames) with it: one control/edges/ LIST and a GET per box at start, then at most every 10 minutes on a control/edges generation change, else every 30 (±10%); the same three /data literals; no read added to serve itself;rev3=census-ruling-nearest-region-b;basis=reads the hostname history mode once after NewServer (srv.LoadHostsMode, one GET of control/hosts-used/@mode in the deployment bucket through the console store, 20 s bound, logged on failure); nothing else changed; no root read added data-literal@5597,data-literal@6899,data-literal@7136 57bf4903fe25076fd5294bfd7c4bcf630a3b6c5125f1a781d0ca5d27537dff09 |
| +@legacy 826b8c8a97ba8eb20832a150cc2d642c3e18f6e4e637eb31f9bf82d1cfb267cc internal/console/apiinstancemove.go Server.handleAPIInstanceMoveRequest legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-2a;basis=the console (cmd/console serve under console.service, user carlos-console): main's body with two refusals added before any write, both no room in the destination (H27): roomIn before the placement checks and moveRoomCheck's through selectMoveBoxes; read sites unchanged, offsets moved;rev3=census-ruling-nearest-region-b;basis=admits through the hostname history (admitMoveOrPlace, an in-process mode check and count) after its operator gate and refuses with S7 while the window is open; every read and write after it unchanged; no read added file:Exec@10378,file:Exec@10555,file:Exec@10706,file:Exec@11706,file:Exec@9299,file:Exec@9387,file:Read@10097,file:Read@7785 7366c131cf6643449687eac2e56e55b5b55c51434b00123c339bb66067f3d413 |
| +@legacy faeed92e47a51bca2325e7be65c5ba07b8286ce557e92033d0d8b6f3bd013eda internal/console/fleets.go Server.placeAppTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): the place's seed rule reads through placeSeedBlock with the context's judge, so a record its slot no longer vouches for neither blocks the place nor is stamped (SetRecordRegion under the same judge); unjudged before the cutover; read sites unchanged, offsets moved;rev3=census-ruling-nearest-region-b;basis=admits through the hostname history (admitMoveOrPlace) first and refuses with S7 while the window is open; every check, read and write after it unchanged; no read added registry:Account@1668,registry:Account@4545,registry:App@4572,registry:Host@4633,registry:Host@4743,whole:Fleet@1656,whole:Route@4531 e9fe8c1b6cddba8902c269f2358ab3394edbb78d8fe9cab57c3ba5918d1e29e0 |
| +cmd/console/main.go serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): Task 0 starts the lifetimes cutover watch, Task 3 the lifetime recovery pass and Task 5 the incarnation migration pass (off unless CARLOS_LIFETIMES_MIGRATE=1) beside the other claim workers; the same three data path literals move; no privileged reader is added;rev3=census-ruling-plans-6-checkout;basis=reads CARLOS_BILLING and the billing variables (billingConfig, a pure env parse plus the operator-configured CARLOS_PRICE_BOOK file through plans.LoadPriceBook, its own decision row) and fatals on a bad one; records the book version and digest in the console database (Store.NotePriceBook) and starts one more claim worker, StartBillingSyncPass, which returns at once with billing off; the same three /data literals; no read added;rev3=census-ruling-console-perf-1;basis=one perf.Recorder made before the stores: the deployment store (openStore(rec)) and the seed data store are wrapped by console.TimeS3Store so their S3 HTTP requests are timed and counted into it, and cfg.Perf carries it to NewServer; no read added, the three read sites unchanged;rev3=census-ruling-instance-egress-sizes-328-329;basis=main's body as of the merge of origin/main 5bba4bc1 (console perf plan 1's recorder and timed stores, under census-ruling-console-perf-1) plus #328/#329 plan 1 Task 8 and plan 2 Task 10: the server config gains PolicyLease from policyLeaseFor (the production leaser when CARLOS_DEPLOYMENT_BUCKET is set, nil otherwise, an env check only); a goroutine waits for SIGTERM or Interrupt, releases the app policy writer lease (srv.ReleasePolicyWriter) and exits; one more claim worker starts, StartEgressReport (the fleet-address report). The same three /data literals, offsets moved; no read added.;rev3=census-ruling-region-labels;basis=armChangeIndex also returns the change watch it builds, and serve starts the region name map loop (Server.RunRegionNames) with it: one control/edges/ LIST and a GET per box at start, then at most every 10 minutes on a control/edges generation change, else every 30 (±10%); the same three /data literals; no read added to serve itself;rev3=census-ruling-nearest-region-b;basis=reads the hostname history mode once after NewServer (srv.LoadHostsMode, one GET of control/hosts-used/@mode in the deployment bucket through the console store, 20 s bound, logged on failure); nothing else changed; no root read added data-literal@5597,data-literal@6899,data-literal@7136 57bf4903fe25076fd5294bfd7c4bcf630a3b6c5125f1a781d0ca5d27537dff09 |
| +internal/console/apiinstancemove.go Server.handleAPIInstanceMoveRequest legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-2a;basis=the console (cmd/console serve under console.service, user carlos-console): main's body with two refusals added before any write, both no room in the destination (H27): roomIn before the placement checks and moveRoomCheck's through selectMoveBoxes; read sites unchanged, offsets moved;rev3=census-ruling-nearest-region-b;basis=admits through the hostname history (admitMoveOrPlace, an in-process mode check and count) after its operator gate and refuses with S7 while the window is open; every read and write after it unchanged; no read added file:Exec@10378,file:Exec@10555,file:Exec@10706,file:Exec@11706,file:Exec@9299,file:Exec@9387,file:Read@10097,file:Read@7785 7366c131cf6643449687eac2e56e55b5b55c51434b00123c339bb66067f3d413 |
| +internal/console/fleets.go Server.placeAppTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the console (cmd/console serve under console.service, user carlos-console): the place's seed rule reads through placeSeedBlock with the context's judge, so a record its slot no longer vouches for neither blocks the place nor is stamped (SetRecordRegion under the same judge); unjudged before the cutover; read sites unchanged, offsets moved;rev3=census-ruling-nearest-region-b;basis=admits through the hostname history (admitMoveOrPlace) first and refuses with S7 while the window is open; every check, read and write after it unchanged; no read added registry:Account@1668,registry:Account@4545,registry:App@4572,registry:Host@4633,registry:Host@4743,whole:Fleet@1656,whole:Route@4531 e9fe8c1b6cddba8902c269f2358ab3394edbb78d8fe9cab57c3ba5918d1e29e0 |
| +@coverage . c00683250b62e51873c55fe96823403edd8dd25755b7f803127887a155f2c15e |
| +@coverage cmd/console 3c3c42ddc7e872147890fbe92368f1e1a1b7c0a20a4ea87450d14503d8d50fa8 |
| +@coverage internal/console cfe2313b347d2b1fcf69bcc2bf34435b01bcb347effb28e5f855e0c79c3ffe88 |
| +@coverage internal/provision 5d5186ecf10968c16d5335570a2b731d5bb7e5c3472b301a3e196eb902f5dbed |
diff --git a/system_hostsused.go b/system_hostsused.go| index 776862681..31eada3ae 100644 |
| --- a/system_hostsused.go |
| +++ b/system_hostsused.go |
| @@ -46,8 +46,8 @@ func systemHostsUsedStatus(ctx context.Context, get roleGet) (hostsUsedStatusVie |
| return st, nil |
| } |
| -// hostsUsedModeLine says what each mode means for a create. Drafts: the |
| -// copy review of these lines comes with merge B. |
| +// hostsUsedModeLine says what each mode means for a create. The approved |
| +// strings: docs/superpowers/notes/copy/nearest-region-never-reuse-b.md. |
| func hostsUsedModeLine(mode string) string { |
| switch mode { |
| case "incomplete": |
| @@ -66,7 +66,7 @@ func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) { |
| fmt.Fprintln(w, hostsUsedModeLine(st.Mode)) |
| fmt.Fprintf(w, "hostnames recorded: %d\n", st.Marks) |
| if st.InflightCreates != nil { |
| - fmt.Fprintf(w, "create requests in progress: %d\n", *st.InflightCreates) |
| + fmt.Fprintf(w, "create and placement requests in progress: %d\n", *st.InflightCreates) |
| } |
| fmt.Fprintf(w, "instance creates still settling: %d\n", st.PendingAllocations) |
| fmt.Fprintf(w, "instance deletes still settling: %d\n", st.PendingRetirements) |
| @@ -75,13 +75,55 @@ func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) { |
| } |
| } |
| -// runSystemHostsUsedVerb is `carlos system hosts-used status`. |
| +// systemHostsUsedPost calls one of the window's POST doors, which answer |
| +// the status as the status door does. |
| +func systemHostsUsedPost(ctx context.Context, post rolePost, verb string, body any) (hostsUsedStatusView, error) { |
| + status, raw, err := post(ctx, "/api/cli/system/hosts-used/"+verb, body) |
| + if err != nil { |
| + return hostsUsedStatusView{}, err |
| + } |
| + if status != http.StatusOK { |
| + return hostsUsedStatusView{}, apiErrorFromBody(status, raw) |
| + } |
| + var st hostsUsedStatusView |
| + if err := json.Unmarshal(raw, &st); err != nil { |
| + return hostsUsedStatusView{}, fmt.Errorf("unreadable response: %w", err) |
| + } |
| + return st, nil |
| +} |
| + |
| +// The approved command output (B1-B3). |
| +const ( |
| + hostsUsedBeginLine = "maintenance window open. new instances, moves and placement changes are paused until you complete or cancel it" |
| + hostsUsedBeginNext = "run carlos system hosts-used status until every count is 0, then scan every target and import the listings" |
| + hostsUsedCancelLine = "maintenance window closed. nothing was recorded" |
| +) |
| + |
| +// printHostsUsedBegin and printHostsUsedCancel are the two verbs' output. |
| +func printHostsUsedBegin(w io.Writer, st hostsUsedStatusView) { |
| + fmt.Fprintln(w, hostsUsedBeginLine) |
| + fmt.Fprintln(w, hostsUsedBeginNext) |
| +} |
| + |
| +func printHostsUsedCancel(w io.Writer, st hostsUsedStatusView) { |
| + fmt.Fprintln(w, hostsUsedCancelLine) |
| + fmt.Fprintln(w, hostsUsedModeLine(st.Mode)) |
| +} |
| + |
| +// runSystemHostsUsedVerb is `carlos system hosts-used <verb>`. |
| func runSystemHostsUsedVerb(rest []string) { |
| - if len(rest) == 0 || rest[0] != "status" { |
| + if len(rest) == 0 { |
| systemUsage() |
| os.Exit(2) |
| } |
| - fs := flag.NewFlagSet("system hosts-used status", flag.ExitOnError) |
| + verb := rest[0] |
| + switch verb { |
| + case "status", "begin", "cancel": |
| + default: |
| + systemUsage() |
| + os.Exit(2) |
| + } |
| + fs := flag.NewFlagSet("system hosts-used "+verb, flag.ExitOnError) |
| consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)") |
| fs.Parse(rest[1:]) |
| if fs.NArg() != 0 { |
| @@ -90,9 +132,23 @@ func runSystemHostsUsedVerb(rest []string) { |
| } |
| sess := requireDeployAPISession(*consoleFlag) |
| printUsing(stdout, sess) |
| - st, err := systemHostsUsedStatus(context.Background(), sess.getJSON) |
| + ctx := context.Background() |
| + var st hostsUsedStatusView |
| + var err error |
| + if verb == "status" { |
| + st, err = systemHostsUsedStatus(ctx, sess.getJSON) |
| + } else { |
| + st, err = systemHostsUsedPost(ctx, sess.postJSON, verb, map[string]string{}) |
| + } |
| if err != nil { |
| - log.Fatalf("carlos system hosts-used status: %v", err) |
| + log.Fatalf("carlos system hosts-used %s: %v", verb, err) |
| + } |
| + switch verb { |
| + case "status": |
| + printHostsUsedStatus(stdout, st) |
| + case "begin": |
| + printHostsUsedBegin(stdout, st) |
| + case "cancel": |
| + printHostsUsedCancel(stdout, st) |
| } |
| - printHostsUsedStatus(stdout, st) |
| } |
diff --git a/system_hostsused_test.go b/system_hostsused_test.go| index 1a3610138..a1f7d7b76 100644 |
| --- a/system_hostsused_test.go |
| +++ b/system_hostsused_test.go |
| @@ -50,7 +50,7 @@ func TestSystemHostsUsedStatusCLI(t *testing.T) { |
| printHostsUsedStatus(&out, st) |
| want = "mode: activating. new instances, moves and placement changes are paused\n" + |
| "hostnames recorded: 3\n" + |
| - "create requests in progress: 2\n" + |
| + "create and placement requests in progress: 2\n" + |
| "instance creates still settling: 0\n" + |
| "instance deletes still settling: 0\n" + |
| "moves not finished: 1\n" |
| @@ -136,3 +136,56 @@ func TestSystemHostsUsedStatusThroughTheBinary(t *testing.T) { |
| t.Fatalf("a refused status exited %v:\n%s", err, out) |
| } |
| } |
| + |
| +// TestSystemHostsUsedWindowVerbsThroughTheBinary: begin and cancel, built, |
| +// POST their doors with the saved token and print the approved lines. |
| +func TestSystemHostsUsedWindowVerbsThroughTheBinary(t *testing.T) { |
| + bin := buildCarlos(t) |
| + var mu sync.Mutex |
| + var asked []string |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("POST /api/cli/system/hosts-used/begin", func(w http.ResponseWriter, r *http.Request) { |
| + mu.Lock() |
| + asked = append(asked, "begin "+r.Header.Get("Authorization")) |
| + mu.Unlock() |
| + w.Header().Set("Content-Type", "application/json") |
| + w.Write([]byte(`{"mode":"activating","marks":3,"inflight_creates":1,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":0}`)) |
| + }) |
| + mux.HandleFunc("POST /api/cli/system/hosts-used/cancel", func(w http.ResponseWriter, r *http.Request) { |
| + mu.Lock() |
| + asked = append(asked, "cancel "+r.Header.Get("Authorization")) |
| + mu.Unlock() |
| + w.Header().Set("Content-Type", "application/json") |
| + w.Write([]byte(`{"mode":"invalidated","marks":3,"inflight_creates":0,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":null}`)) |
| + }) |
| + ts := httptest.NewServer(mux) |
| + t.Cleanup(ts.Close) |
| + credPath := filepath.Join(t.TempDir(), "credentials") |
| + if err := os.WriteFile(credPath, []byte(`{"version":1,"credentials":[{"console":"`+ts.URL+`","address":"paul@keymail.dev","token":"tok-operator"}]}`), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + run := func(verb string) string { |
| + cmd := exec.Command(bin, "system", "hosts-used", verb) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+credPath) |
| + cmd.Dir = t.TempDir() |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("%s: %v\n%s", verb, err, out) |
| + } |
| + return string(out) |
| + } |
| + out := run("begin") |
| + if !strings.Contains(out, "maintenance window open. new instances, moves and placement changes are paused until you complete or cancel it\n") || |
| + !strings.Contains(out, "run carlos system hosts-used status until every count is 0, then scan every target and import the listings\n") { |
| + t.Fatalf("begin printed:\n%s", out) |
| + } |
| + out = run("cancel") |
| + if !strings.Contains(out, "maintenance window closed. nothing was recorded\nmode: invalidated. new instances are refused until a fresh inventory completes\n") { |
| + t.Fatalf("cancel printed:\n%s", out) |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if len(asked) != 2 || asked[0] != "begin Bearer tok-operator" || asked[1] != "cancel Bearer tok-operator" { |
| + t.Fatalf("asked %v", asked) |
| + } |
| +} |