Regional domains (#447) Task 1: placements GET and CLI read
GET /api/cli/apps/{account}/{app}/domains/{host}/placements answers, for
an alias claim this app holds, the region, target, readiness and serving
boxes (EIP, AWS region, release, counted) from one edges snapshot joined
with the box heartbeats. Registered with the per-host read's roles and
team scope; every not-found shape answers that door's 404 bytes; an
unreadable snapshot is 503 RD-22. Every claim is single mode here.
carlos domains placements --app <a> <hostname> prints RD-6/RD-7, the RD-5
table (ADDRESSES lists counted boxes only), each not-ready region's reason
and RD-8. release.RegionalDomainsFloor is v0.31.0, provisional.
Route inventories (team doors, legacy pin exemptions, claim route census,
claim read fixture and probe) gain the new door.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+723
−2
apimode.go+48 −0domains_cli.go+101 −0domains_cli_test.go+117 −0internal/console/apiplacements.go+208 −0internal/console/apiplacements_test.go+216 −0internal/console/authcli.go+4 −0internal/console/claim_invariant_fixtures_test.go+4 −0internal/console/claim_invariant_probes_read_test.go+7 −2internal/console/svcroutes_test.go+5 −0internal/console/teamdoors_test.go+3 −0internal/console/testdata/claim-routes.txt+1 −0internal/release/layoutintent.go+9 −0
Intent
Attributed to this commit: 40.1 g CO₂e (1,443,546 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on regional-domains-447, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/apimode.go b/apimode.go| index 4b3f49744..68d21cd71 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -4657,6 +4657,54 @@ func (s *apiSession) domainPaths(ctx context.Context, a apiAcct, app, host strin |
| return res.Paths, nil |
| } |
| +// apiPlacementBox is one box serving a placement's target |
| +// (internal/console/apiplacements.go placementBox). Counted: the box counts |
| +// toward the region's readiness. |
| +type apiPlacementBox struct { |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + AWSRegion string `json:"aws_region"` |
| + Release string `json:"release"` |
| + Counted bool `json:"counted"` |
| +} |
| + |
| +// apiPlacement is one region's entry of the placements GET. |
| +type apiPlacement struct { |
| + Region string `json:"region"` |
| + Target string `json:"target"` |
| + Ready bool `json:"ready"` |
| + Reason string `json:"reason"` |
| + Boxes []apiPlacementBox `json:"boxes"` |
| +} |
| + |
| +// apiPlacements is the placements GET's body (#447). |
| +type apiPlacements struct { |
| + Host string `json:"host"` |
| + Mode string `json:"mode"` |
| + Route string `json:"route"` |
| + Wildcard bool `json:"wildcard"` |
| + Catchall bool `json:"catchall"` |
| + Placements []apiPlacement `json:"placements"` |
| +} |
| + |
| +// domainPlacements reads one hostname's placements: per region, the |
| +// instance that serves it, the boxes serving that instance and whether the |
| +// region is ready. |
| +func (s *apiSession) domainPlacements(ctx context.Context, a apiAcct, app, host string) (apiPlacements, error) { |
| + status, body, err := s.getJSON(ctx, apiPath(a, app, "/domains/"+url.PathEscape(host)+"/placements")) |
| + if err != nil { |
| + return apiPlacements{}, err |
| + } |
| + if status != http.StatusOK { |
| + return apiPlacements{}, apiErrorFromBody(status, body) |
| + } |
| + var res apiPlacements |
| + if err := json.Unmarshal(body, &res); err != nil { |
| + return apiPlacements{}, fmt.Errorf("domains placements: unreadable response: %w", err) |
| + } |
| + return res, nil |
| +} |
| + |
| // shipTimeout bounds ship's own context — generous on purpose. The console |
| // gives itself up to 10 minutes to read the request body and 2 minutes to |
| // store it (internal/console/apicli.go), well past the 30s absolute Timeout |
diff --git a/domains_cli.go b/domains_cli.go| index 7fa80e256..c488d7ede 100644 |
| --- a/domains_cli.go |
| +++ b/domains_cli.go |
| @@ -77,6 +77,9 @@ const domainsListUsage = `usage: carlos domains list --app <a> [--account <a>] [ |
| const domainsPathsUsage = `usage: carlos domains paths --app <a> [--account <a>] [--account-id <id>] [--console <origin>] <hostname> |
| ` |
| +const domainsPlacementsUsage = `usage: carlos domains placements --app <a> [--account <a>] [--account-id <id>] [--console <origin>] <hostname> |
| +` |
| + |
| // runDomains dispatches the domains sub-verbs. attach/detach/list are |
| // positional words, not flags, and must never reach fs.Parse — the same |
| // shape runInstances uses for its own sub-verbs. |
| @@ -98,6 +101,9 @@ func runDomains(args []string) { |
| case "paths": |
| runDomainsPaths(args[1:]) |
| return |
| + case "placements": |
| + runDomainsPlacements(args[1:]) |
| + return |
| } |
| } |
| log.Fatal(domainsUsage) |
| @@ -459,6 +465,101 @@ func runDomainsPaths(args []string) { |
| mutedf(stdout, "(published desired state; \"carlos routes --app %s\" shows which of these a box is actually serving)", app2) |
| } |
| +// runDomainsPlacements prints one hostname's placements (#447): per region, |
| +// the instance that serves it, whether the region is ready, and the |
| +// addresses of the boxes that count toward that, which are the addresses to |
| +// point DNS at. Read only; --set comes with the regional claim. |
| +func runDomainsPlacements(args []string) { |
| + fs := flag.NewFlagSet("domains placements", flag.ExitOnError) |
| + app := appFlag(fs, "app the hostname belongs to") |
| + consoleFlag := consoleOption(fs, "console to read through (default: the only logged-in one)") |
| + acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)") |
| + acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account") |
| + fs.Usage = flagUsage(fs, domainsPlacementsUsage) |
| + fs.Parse(args) |
| + host := strings.TrimSpace(fs.Arg(0)) |
| + if host == "" || fs.NArg() > 1 { |
| + log.Fatal(domainsPlacementsUsage) |
| + } |
| + sess := requireAPISession("placements", *consoleFlag) |
| + printUsing(stdout, sess) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + app2 := resolvedApp(sess, acct, *app, domainsPlacementsUsage) |
| + pl, err := sess.domainPlacements(context.Background(), acct, app2, host) |
| + if err != nil { |
| + log.Fatalf("domains placements: %v", err) |
| + } |
| + printPlacements(pl) |
| +} |
| + |
| +// printPlacements prints the placements GET: the claim's mode line (RD-6 or |
| +// RD-7), the table (RD-5), each region that is not ready with its reason |
| +// (RD-9 to RD-14), then the DNS line (RD-8) when any region is ready. |
| +func printPlacements(pl apiPlacements) { |
| + if pl.Mode == "regional" { |
| + fmt.Fprintln(stdout, fmt.Sprintf("%s is a regional domain. each region serves it from its own instance.", pl.Host)) |
| + } else { |
| + fmt.Fprintln(stdout, fmt.Sprintf("%s is served from %s.", pl.Host, pl.Route)) |
| + } |
| + w := newTable(stdout) |
| + fmt.Fprintln(w, "REGION\tINSTANCE\tREADY\tADDRESSES") |
| + anyReady := false |
| + for _, p := range pl.Placements { |
| + ready := "no" |
| + if p.Ready { |
| + ready, anyReady = "yes", true |
| + } |
| + // Only the boxes that count: a listed box that does not count is |
| + // not an address to point DNS at. |
| + var addrs []string |
| + for _, b := range p.Boxes { |
| + if b.Counted && b.EIP != "" { |
| + addrs = append(addrs, b.EIP) |
| + } |
| + } |
| + addresses := strings.Join(addrs, ",") |
| + if addresses == "" { |
| + addresses = "-" |
| + } |
| + fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", orDash(p.Region), p.Target, ready, addresses) |
| + } |
| + w.Flush() |
| + for _, p := range pl.Placements { |
| + if p.Ready { |
| + continue |
| + } |
| + why := placementReason(p) |
| + if p.Region != "" { |
| + why = p.Region + ": " + why |
| + } |
| + fmt.Fprintln(stdout, why) |
| + } |
| + if anyReady { |
| + fmt.Fprintln(stdout, fmt.Sprintf("point DNS for %s at the addresses of the ready regions, with latency-based routing.", pl.Host)) |
| + } |
| +} |
| + |
| +// placementReason is the sentence for a not-ready placement's reason. A |
| +// reason this CLI does not know (a newer console) prints as the console |
| +// sent it. |
| +func placementReason(p apiPlacement) string { |
| + switch p.Reason { |
| + case "no-serving-box": |
| + return fmt.Sprintf("no server in this region serves %s yet.", p.Target) |
| + case "below-floor": |
| + return "the servers here run a release too old for regional domains." |
| + case "no-address": |
| + return "no fixed address is published for this region." |
| + case "evidence-incomplete": |
| + return "not every server has reported. try again in a few minutes." |
| + case "settling": |
| + return "waiting for every server to report since the domain was created. this takes up to five minutes." |
| + case "route-collision": |
| + return "another route uses this hostname, so no region is ready." |
| + } |
| + return p.Reason |
| +} |
| + |
| // printDomainRecords prints the records the member must create, grouped by |
| // alternative. Nothing is printed when the door sent none — a pointing |
| // hostname has nothing left to do, and an older console sends no records at |
diff --git a/domains_cli_test.go b/domains_cli_test.go| index 9f086f78f..b842db0a4 100644 |
| --- a/domains_cli_test.go |
| +++ b/domains_cli_test.go |
| @@ -278,6 +278,10 @@ type fakeDomainsConsole struct { |
| // predating path routing sends. |
| paths map[string]string |
| lastPathsPath string |
| + // placements is what the placements GET answers, and |
| + // lastPlacementsPath records the URL it was asked for. |
| + placements map[string]any |
| + lastPlacementsPath string |
| } |
| func newFakeDomainsConsole(t *testing.T) *fakeDomainsConsole { |
| @@ -306,6 +310,9 @@ func newFakeDomainsConsole(t *testing.T) *fakeDomainsConsole { |
| case r.Method == http.MethodDelete: |
| fc.lastDetachPath = r.URL.Path |
| json.NewEncoder(w).Encode(map[string]any{"host": "x", "removed": fc.detachRemoved}) |
| + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/placements"): |
| + fc.lastPlacementsPath = r.URL.Path |
| + json.NewEncoder(w).Encode(fc.placements) |
| case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/domains/"): |
| // The per-host claim door, which carries the published prefix |
| // map. Matched BEFORE the catch-all list GET below, which would |
| @@ -791,3 +798,113 @@ func TestRunDomainsInstanceCatchall(t *testing.T) { |
| t.Fatalf("detach path = %s", fc.lastDetachPath) |
| } |
| } |
| + |
| +// TestAPISessionDomainPlacements: domainPlacements GETs the placements door |
| +// for one hostname and decodes every field, aws_region included, and an |
| +// empty boxes list as empty. |
| +func TestAPISessionDomainPlacements(t *testing.T) { |
| + var gotPath, gotMethod string |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + gotPath, gotMethod = r.URL.Path, r.Method |
| + w.Write([]byte(`{"host":"example.com","mode":"regional","route":"shop-ie.example.net","wildcard":true,"catchall":true, |
| + "placements":[ |
| + {"region":"ie","target":"shop-ie.example.net","ready":true, |
| + "boxes":[{"box":"annie","eip":"203.0.113.10","aws_region":"eu-west-1","release":"v0.31.0","counted":true}]}, |
| + {"region":"uk","target":"shop-uk.example.net","ready":false,"reason":"no-serving-box","boxes":[]}]}`)) |
| + })) |
| + defer ts.Close() |
| + s := newTestSession(ts.URL) |
| + |
| + got, err := s.domainPlacements(context.Background(), apiAcct{Seg: "bab"}, "shop", "example.com") |
| + if err != nil { |
| + t.Fatalf("domainPlacements: %v", err) |
| + } |
| + if gotPath != "/api/cli/apps/bab/shop/domains/example.com/placements" || gotMethod != http.MethodGet { |
| + t.Fatalf("request = %s %s, want GET .../shop/domains/example.com/placements", gotMethod, gotPath) |
| + } |
| + if got.Host != "example.com" || got.Mode != "regional" || got.Route != "shop-ie.example.net" || |
| + !got.Wildcard || !got.Catchall || len(got.Placements) != 2 { |
| + t.Fatalf("answer = %+v", got) |
| + } |
| + ie, uk := got.Placements[0], got.Placements[1] |
| + wantBox := apiPlacementBox{Box: "annie", EIP: "203.0.113.10", AWSRegion: "eu-west-1", Release: "v0.31.0", Counted: true} |
| + if ie.Region != "ie" || ie.Target != "shop-ie.example.net" || !ie.Ready || ie.Reason != "" || |
| + len(ie.Boxes) != 1 || ie.Boxes[0] != wantBox { |
| + t.Fatalf("ie = %+v, want ready with %+v", ie, wantBox) |
| + } |
| + if uk.Region != "uk" || uk.Ready || uk.Reason != "no-serving-box" || len(uk.Boxes) != 0 { |
| + t.Fatalf("uk = %+v, want not ready, no-serving-box, no boxes", uk) |
| + } |
| +} |
| + |
| +// TestRunDomainsPlacementsPrintsTable: a single-mode claim prints RD-7, the |
| +// RD-5 table with one ready row whose ADDRESSES are its counted boxes' EIPs, |
| +// and RD-8. |
| +func TestRunDomainsPlacementsPrintsTable(t *testing.T) { |
| + fc := domainsCLIFixture(t) |
| + fc.placements = map[string]any{ |
| + "host": "shop.example.com", "mode": "single", "route": "shop-ie.example.net", |
| + "placements": []map[string]any{{ |
| + "region": "ie", "target": "shop-ie.example.net", "ready": true, |
| + "boxes": []map[string]any{ |
| + {"box": "annie", "eip": "203.0.113.10", "aws_region": "eu-west-1", "release": "v0.30.2", "counted": true}, |
| + {"box": "betty", "eip": "203.0.113.11", "aws_region": "eu-west-1", "release": "v0.30.2", "counted": false}, |
| + }, |
| + }}, |
| + } |
| + buf := captureStdout(t) |
| + |
| + runDomains([]string{"placements", "-app", "tito", "shop.example.com"}) |
| + |
| + if !strings.HasSuffix(fc.lastPlacementsPath, "/domains/shop.example.com/placements") { |
| + t.Fatalf("asked for %q, want the placements door for shop.example.com", fc.lastPlacementsPath) |
| + } |
| + out := buf.String() |
| + for _, want := range []string{ |
| + "shop.example.com is served from shop-ie.example.net.", |
| + "point DNS for shop.example.com at the addresses of the ready regions, with latency-based routing.", |
| + } { |
| + if !strings.Contains(out, want) { |
| + t.Fatalf("stdout missing %q:\n%s", want, out) |
| + } |
| + } |
| + var header, row []string |
| + for _, line := range strings.Split(out, "\n") { |
| + f := strings.Fields(line) |
| + if len(f) > 0 && f[0] == "REGION" { |
| + header = f |
| + } |
| + if len(f) > 0 && f[0] == "ie" { |
| + row = f |
| + } |
| + } |
| + if strings.Join(header, " ") != "REGION INSTANCE READY ADDRESSES" { |
| + t.Fatalf("header = %q:\n%s", header, out) |
| + } |
| + if strings.Join(row, " ") != "ie shop-ie.example.net yes 203.0.113.10" { |
| + t.Fatalf("row = %q, want betty (not counted) left out of ADDRESSES:\n%s", row, out) |
| + } |
| +} |
| + |
| +// TestRunDomainsPlacementsPrintsTheReason: a region that is not ready says |
| +// why, and with no ready region there is no DNS line. |
| +func TestRunDomainsPlacementsPrintsTheReason(t *testing.T) { |
| + fc := domainsCLIFixture(t) |
| + fc.placements = map[string]any{ |
| + "host": "shop.example.com", "mode": "single", "route": "shop-ie.example.net", |
| + "placements": []map[string]any{{ |
| + "region": "", "target": "shop-ie.example.net", "ready": false, "reason": "no-serving-box", "boxes": []any{}, |
| + }}, |
| + } |
| + buf := captureStdout(t) |
| + |
| + runDomains([]string{"placements", "-app", "tito", "shop.example.com"}) |
| + |
| + out := buf.String() |
| + if !strings.Contains(out, "no server in this region serves shop-ie.example.net yet.") { |
| + t.Fatalf("stdout missing the no-serving-box sentence:\n%s", out) |
| + } |
| + if strings.Contains(out, "point DNS") { |
| + t.Fatalf("stdout tells the member to point DNS with no ready region:\n%s", out) |
| + } |
| +} |
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go| new file mode 100644 |
| index 000000000..17b414cbe |
| --- /dev/null |
| +++ b/internal/console/apiplacements.go |
| @@ -0,0 +1,208 @@ |
| +package console |
| + |
| +// The placements door (#447, spec §6.5): for one alias claim, which boxes |
| +// serve its target in each region, the addresses they answer on and whether |
| +// the region is ready for DNS. Read only in this task; the PUT that makes a |
| +// claim regional, and the regional rules of the view, come later. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "log" |
| + "net/http" |
| + "os" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The reasons a placement is not ready. JSON values, not copy: the CLI maps |
| +// each to its own sentence (RD-9 to RD-14). |
| +const ( |
| + reasonNoServingBox = "no-serving-box" |
| + reasonBelowFloor = "below-floor" |
| + reasonNoAddress = "no-address" |
| + reasonEvidenceIncomplete = "evidence-incomplete" |
| + reasonSettling = "settling" |
| + reasonRouteCollision = "route-collision" |
| +) |
| + |
| +// placementsUnreadableMsg (RD-22, draft) is the 503 when the console cannot |
| +// read the boxes' edges files or heartbeats. |
| +const placementsUnreadableMsg = "could not check every server just now. try again in a few minutes." |
| + |
| +// placementsAnswer is the GET body. |
| +type placementsAnswer struct { |
| + Host string `json:"host"` |
| + Mode string `json:"mode"` // "single" | "regional" |
| + Route string `json:"route"` |
| + Wildcard bool `json:"wildcard"` |
| + Catchall bool `json:"catchall"` |
| + Placements []placementState `json:"placements"` |
| +} |
| + |
| +// placementState is one region's entry. |
| +type placementState struct { |
| + Region string `json:"region"` // homeRegionOut of the code |
| + Target string `json:"target"` |
| + Ready bool `json:"ready"` |
| + Reason string `json:"reason,omitempty"` |
| + Boxes []placementBox `json:"boxes"` // never null |
| +} |
| + |
| +// placementBox is one box serving the target. Counted says whether it |
| +// counts toward the region's readiness, so a reader can tell a listed box |
| +// that does not count (no address; for a regional claim, below the floor) |
| +// from one that does. |
| +type placementBox struct { |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + AWSRegion string `json:"aws_region"` // the edges file's region |
| + Release string `json:"release"` // heartbeat metrics.release |
| + Counted bool `json:"counted"` |
| +} |
| + |
| +// handleAPIDomainPlacementsGet answers GET .../domains/{host}/placements. |
| +// Registered with the roles and team scope of GET .../domains/{host}, and |
| +// every way this app does not hold an alias claim on host answers that |
| +// door's not-found bytes, so neither door is an existence oracle. |
| +func (s *Server) handleAPIDomainPlacementsGet(w http.ResponseWriter, r *http.Request) { |
| + _, acct, app, ok := s.domainsGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + host, ok := domains.NormalizeAliasHost(r.PathValue("host")) |
| + if !ok { |
| + jsonError(w, http.StatusNotFound, "no such hostname") |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| + defer cancel() |
| + c, err := domains.GetClaim(ctx, s.cfg.Releases, host) |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + log.Printf("console: api domain placements %s/%s %s: %v", acct.Sqid, app, host, err) |
| + jsonError(w, http.StatusBadGateway, "could not read the hostname") |
| + return |
| + } |
| + if err != nil || c == nil || c.Account != acct.Sqid || c.App != app || c.Instances { |
| + jsonError(w, http.StatusNotFound, "no such hostname") |
| + return |
| + } |
| + now := time.Now() |
| + var ( |
| + snap edgesfile.Snapshot |
| + snapErr error |
| + boxes []status.Box |
| + complete bool |
| + boxesErr error |
| + ) |
| + runConcurrently( |
| + func() { snap, snapErr = readEdgesSnapshotConcurrently(ctx, s.cfg.Releases) }, |
| + func() { boxes, complete, boxesErr = s.loadBoxes(ctx, s.cfg.Releases, "") }, |
| + ) |
| + // A failed heartbeat load leaves every box's liveness unknown, which |
| + // would read as "nothing serves": the same 503 as a failed edges read. |
| + if err := errors.Join(snapErr, boxesErr); err != nil { |
| + log.Printf("console: api domain placements %s/%s %s: %v", acct.Sqid, app, host, err) |
| + jsonError(w, http.StatusServiceUnavailable, placementsUnreadableMsg) |
| + return |
| + } |
| + snap = edgesfile.JoinLive(snap, boxes, complete, nil, now) |
| + writeJSON(w, http.StatusOK, s.placementsView(*c, snap, boxes, now)) |
| +} |
| + |
| +// placementsView is the GET body from one claim and one joined snapshot. Pure. |
| +// |
| +// Every claim is single mode until the regional claim lands (Task 2), and |
| +// Task 9 adds the regional rules. Single mode has one entry, the route's: |
| +// every fresh box publishing the target under home is listed, whatever its |
| +// placement, and counts when it publishes an address. The regional floor |
| +// does not apply to a single-mode claim, which every release serves. |
| +func (s *Server) placementsView(c domains.Claim, snap edgesfile.Snapshot, boxes []status.Box, now time.Time) placementsAnswer { |
| + target := c.Route |
| + if target == "" { |
| + // A first-route claim: the hostname is its own route. |
| + target = c.Host |
| + } |
| + serving := servingFiles(snap, target, func(edgesfile.PlacementView) bool { return true }) |
| + heartbeats := freshHeartbeats(boxes, now) |
| + p := placementState{Target: target, Boxes: []placementBox{}} |
| + if len(serving) > 0 { |
| + p.Region = s.homeRegionOut(serving[0].Placement) |
| + } |
| + for _, f := range serving { |
| + hb, fresh := heartbeats[f.Box] |
| + b := placementBox{Box: f.Box, EIP: f.EIP, AWSRegion: f.Region, |
| + Counted: fresh && f.EIP != ""} |
| + if hb.Metrics != nil { |
| + b.Release = hb.Metrics.Release |
| + } |
| + p.Ready = p.Ready || b.Counted |
| + p.Boxes = append(p.Boxes, b) |
| + } |
| + switch { |
| + case p.Ready: |
| + case len(serving) == 0: |
| + p.Reason = reasonNoServingBox |
| + default: |
| + p.Reason = reasonNoAddress |
| + } |
| + return placementsAnswer{Host: c.Host, Mode: "single", Route: target, |
| + Wildcard: c.Wildcard, Catchall: c.Catchall, Placements: []placementState{p}} |
| +} |
| + |
| +// freshHeartbeats is each box's heartbeat by label, fresh ones only. |
| +func freshHeartbeats(boxes []status.Box, now time.Time) map[string]status.Box { |
| + out := make(map[string]status.Box, len(boxes)) |
| + for _, b := range boxes { |
| + if !status.BoxStale(b, now, status.SnapshotPeriod) { |
| + out[b.Label] = b |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// servingBoxes: fresh files whose Placement == code and whose Hosts[target] |
| +// decodes (edgesfile.Host) with Role == edgesfile.RoleHome, sorted by Box. |
| +func servingBoxes(snap edgesfile.Snapshot, code, target string) []edgesfile.PlacementView { |
| + return servingFiles(snap, target, func(f edgesfile.PlacementView) bool { return f.Placement == code }) |
| +} |
| + |
| +// servingFiles is servingBoxes with the placement test given: fresh files |
| +// keep(f) admits that publish target under home, sorted by Box. |
| +func servingFiles(snap edgesfile.Snapshot, target string, keep func(edgesfile.PlacementView) bool) []edgesfile.PlacementView { |
| + var out []edgesfile.PlacementView |
| + for _, f := range snap.Files { |
| + if !f.Fresh || !keep(f) { |
| + continue |
| + } |
| + raw, ok := f.Hosts[target] |
| + if !ok { |
| + continue |
| + } |
| + var h edgesfile.Host |
| + if err := json.Unmarshal(raw, &h); err != nil || h.Role != edgesfile.RoleHome { |
| + continue |
| + } |
| + out = append(out, f) |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].Box < out[j].Box }) |
| + return out |
| +} |
| + |
| +// boxAtRegionalFloor reports whether a box's heartbeat names a platform |
| +// release that parses at or above release.RegionalDomainsFloor, the first |
| +// release that reads a regional claim. Missing or unparseable is false. |
| +// It mirrors boxAtRootfsFloor (rootfs.go). |
| +func boxAtRegionalFloor(b status.Box) bool { |
| + if b.Metrics == nil { |
| + return false |
| + } |
| + v, ok := release.ParseReleaseVersion(b.Metrics.Release) |
| + return ok && v.Compare(release.RegionalDomainsFloor) >= 0 |
| +} |
diff --git a/internal/console/apiplacements_test.go b/internal/console/apiplacements_test.go| new file mode 100644 |
| index 000000000..ac0d51e32 |
| --- /dev/null |
| +++ b/internal/console/apiplacements_test.go |
| @@ -0,0 +1,216 @@ |
| +package console |
| + |
| +// The placements GET (apiplacements.go, #447 Task 1): for one alias claim, |
| +// which boxes serve its target, at which addresses, and whether the region |
| +// is ready for DNS. Every test goes through the real console server, the |
| +// real claim writer, real heartbeats (status.WriteBox) and edges files in |
| +// the shape a box publishes them. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// placementsURL is the placements GET for host on app shop. |
| +func placementsURL(fx *consoleFixture, app, host string) string { |
| + return domainsURL(fx, fx.sqid, app) + "/" + host + "/placements" |
| +} |
| + |
| +// putServingEdges writes box's edges file publishing route under home, as |
| +// the box's own edges writer does: v1, its EIP, the AWS region, its |
| +// placement code and the route's host entry. |
| +func putServingEdges(t *testing.T, fx *consoleFixture, box, eip, placement, route string) { |
| + t.Helper() |
| + hosts := map[string]edgesfile.Host{} |
| + if route != "" { |
| + hosts[route] = edgesfile.Host{Role: edgesfile.RoleHome} |
| + } |
| + body, err := json.Marshal(map[string]any{"v": 1, "box": box, "eip": eip, "region": "eu-west-1", |
| + "placement": placement, "hosts": hosts}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + putFixtureObject(t, fx.rel, edgesfile.Key(box), body) |
| +} |
| + |
| +// attachShopClaim writes the alias claim host -> route for account/app |
| +// through the real claim writer. |
| +func attachShopClaim(t *testing.T, fx *consoleFixture, account, app, host, route string) { |
| + t.Helper() |
| + if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{ |
| + Host: host, Account: account, App: app, Route: route, |
| + CreatedAt: time.Now().UTC().Format(time.RFC3339), |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +type placementsResp struct { |
| + Host string `json:"host"` |
| + Mode string `json:"mode"` |
| + Route string `json:"route"` |
| + Placements []struct { |
| + Region string `json:"region"` |
| + Target string `json:"target"` |
| + Ready bool `json:"ready"` |
| + Reason string `json:"reason"` |
| + Boxes json.RawMessage `json:"boxes"` |
| + } `json:"placements"` |
| +} |
| + |
| +type placementsBoxResp struct { |
| + Box string `json:"box"` |
| + EIP string `json:"eip"` |
| + AWSRegion string `json:"aws_region"` |
| + Release string `json:"release"` |
| + Counted bool `json:"counted"` |
| +} |
| + |
| +func getPlacements(t *testing.T, fx *consoleFixture, token, host string) placementsResp { |
| + t.Helper() |
| + code, _, out := rawReq(t, http.MethodGet, placementsURL(fx, "shop", host), token, "") |
| + if code != http.StatusOK { |
| + t.Fatalf("placements GET %s = %d %s, want 200", host, code, out) |
| + } |
| + var got placementsResp |
| + if err := json.Unmarshal([]byte(out), &got); err != nil { |
| + t.Fatalf("placements body %s: %v", out, err) |
| + } |
| + if len(got.Placements) != 1 { |
| + t.Fatalf("placements = %s, want one entry for a single-mode claim", out) |
| + } |
| + return got |
| +} |
| + |
| +func TestPlacementsGetSingleModeReadiness(t *testing.T) { |
| + fx, token, _ := rootfsDoorWorldToken(t, "code-placements-single") |
| + fx.srv.cfg.HomeRegion = "ie" |
| + now := time.Now() |
| + attachShopClaim(t, fx, fx.sqid, "shop", "shop.example.com", "shop-ie.example.net") |
| + writeFleetBoxOn(t, fx, "", "annie", "eu-west-1", true, now, "v0.30.2") |
| + putServingEdges(t, fx, "annie", "203.0.113.10", "", "shop-ie.example.net") |
| + // betty names the route too, but its heartbeat is an hour old: a retired |
| + // box's file is never a serving box. |
| + writeFleetBoxOn(t, fx, "", "betty", "eu-west-1", true, now.Add(-time.Hour), "v0.30.2") |
| + putServingEdges(t, fx, "betty", "203.0.113.11", "", "shop-ie.example.net") |
| + |
| + got := getPlacements(t, fx, token, "shop.example.com") |
| + if got.Host != "shop.example.com" || got.Mode != "single" || got.Route != "shop-ie.example.net" { |
| + t.Fatalf("answer = %+v, want single mode for shop.example.com -> shop-ie.example.net", got) |
| + } |
| + p := got.Placements[0] |
| + if p.Region != "ie" || p.Target != "shop-ie.example.net" || !p.Ready || p.Reason != "" { |
| + t.Fatalf("placement = %+v, want ie, shop-ie.example.net, ready", p) |
| + } |
| + var boxes []placementsBoxResp |
| + if err := json.Unmarshal(p.Boxes, &boxes); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := placementsBoxResp{Box: "annie", EIP: "203.0.113.10", AWSRegion: "eu-west-1", Release: "v0.30.2", Counted: true} |
| + if len(boxes) != 1 || boxes[0] != want { |
| + t.Fatalf("boxes = %+v, want [%+v] (betty's heartbeat is stale)", boxes, want) |
| + } |
| + |
| + // annie publishes no address: it still serves, but nothing counts. |
| + putServingEdges(t, fx, "annie", "", "", "shop-ie.example.net") |
| + got = getPlacements(t, fx, token, "shop.example.com") |
| + p = got.Placements[0] |
| + if p.Ready || p.Reason != reasonNoAddress { |
| + t.Fatalf("placement = %+v, want not ready, %q", p, reasonNoAddress) |
| + } |
| + boxes = nil |
| + if err := json.Unmarshal(p.Boxes, &boxes); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(boxes) != 1 || boxes[0].Box != "annie" || boxes[0].Counted { |
| + t.Fatalf("boxes = %+v, want annie listed and not counted", boxes) |
| + } |
| + |
| + // Nothing serves the route at all. |
| + putServingEdges(t, fx, "annie", "203.0.113.10", "", "") |
| + putServingEdges(t, fx, "betty", "203.0.113.11", "", "") |
| + got = getPlacements(t, fx, token, "shop.example.com") |
| + p = got.Placements[0] |
| + if p.Ready || p.Reason != reasonNoServingBox || p.Region != "" || p.Target != "shop-ie.example.net" { |
| + t.Fatalf("placement = %+v, want not ready, %q, no region", p, reasonNoServingBox) |
| + } |
| + if string(p.Boxes) != "[]" { |
| + t.Fatalf("boxes = %s, want [] (never null)", p.Boxes) |
| + } |
| +} |
| + |
| +// A first-route claim (no Route) targets the host itself. |
| +func TestPlacementsGetFirstRouteClaimTargetsItsHost(t *testing.T) { |
| + fx, token, _ := rootfsDoorWorldToken(t, "code-placements-first") |
| + attachShopClaim(t, fx, fx.sqid, "shop", "shop.example.com", "") |
| + got := getPlacements(t, fx, token, "shop.example.com") |
| + if got.Route != "shop.example.com" || got.Placements[0].Target != "shop.example.com" || |
| + got.Placements[0].Reason != reasonNoServingBox { |
| + t.Fatalf("answer = %+v, want the host as its own target", got) |
| + } |
| +} |
| + |
| +// Every not-found shape answers the bytes the per-host GET gives a hostname |
| +// nobody claimed, so this door is no existence oracle either. |
| +func TestPlacementsGetAnswersTheFamilyNotFound(t *testing.T) { |
| + fx, token, _ := rootfsDoorWorldToken(t, "code-placements-404") |
| + ctx := context.Background() |
| + attachShopClaim(t, fx, "zzz", "shop", "theirs.example.com", "theirs.example.net") |
| + attachShopClaim(t, fx, fx.sqid, "kass", "kass.example.com", "kass.example.net") |
| + // An instance catch-all this app holds: the per-host GET answers it, |
| + // the placements GET does not. |
| + body, err := json.Marshal(domains.Claim{Schema: 1, Host: "*.example.com", Account: fx.sqid, App: "shop", Instances: true}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, domains.ClaimKey("*.example.com"), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + wantCode, _, wantBody := rawReq(t, http.MethodGet, domainGetURL(fx, fx.sqid, "shop", "nobody.example.com"), token, "") |
| + if wantCode != http.StatusNotFound { |
| + t.Fatalf("baseline GET = %d %s, want 404", wantCode, wantBody) |
| + } |
| + for _, host := range []string{"theirs.example.com", "kass.example.com", "*.example.com", "nobody.example.com"} { |
| + code, _, out := rawReq(t, http.MethodGet, placementsURL(fx, "shop", host), token, "") |
| + if code != wantCode || out != wantBody { |
| + t.Errorf("placements %s = %d %q, want %d %q", host, code, out, wantCode, wantBody) |
| + } |
| + } |
| +} |
| + |
| +func TestPlacementsGetUnreadableSnapshot(t *testing.T) { |
| + fx, token, _ := rootfsDoorWorldToken(t, "code-placements-503") |
| + attachShopClaim(t, fx, fx.sqid, "shop", "shop.example.com", "shop-ie.example.net") |
| + fx.srv.cfg.Releases = assetEdgesFailStore{Store: fx.rel} |
| + code, _, out := rawReq(t, http.MethodGet, placementsURL(fx, "shop", "shop.example.com"), token, "") |
| + if code != http.StatusServiceUnavailable { |
| + t.Fatalf("placements GET = %d %s, want 503", code, out) |
| + } |
| + var e struct { |
| + Error string `json:"error"` |
| + } |
| + if err := json.Unmarshal([]byte(out), &e); err != nil || e.Error != placementsUnreadableMsg { |
| + t.Fatalf("body = %s, want the RD-22 sentence", out) |
| + } |
| +} |
| + |
| +// boxAtRegionalFloor reads the heartbeat's release against the floor; |
| +// missing or unparseable is below. |
| +func TestBoxAtRegionalFloor(t *testing.T) { |
| + for rel, want := range map[string]bool{"v0.30.2": false, "v0.31.0": true, "v0.31.4": true, "v1.0.0": true, "": false, "dev": false} { |
| + if got := boxAtRegionalFloor(status.Box{Metrics: &status.BoxMetrics{Release: rel}}); got != want { |
| + t.Errorf("boxAtRegionalFloor(%q) = %v, want %v", rel, got, want) |
| + } |
| + } |
| + if boxAtRegionalFloor(status.Box{}) { |
| + t.Error("a heartbeat with no metrics is at the floor") |
| + } |
| +} |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index ceb8daa3b..82aa50d94 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -864,6 +864,10 @@ func (s *Server) registerCLIRoutes() { |
| // discloses strictly less (one hostname the caller already owns), so it |
| // cannot need a role the list does not. |
| s.cliScopedRoute("GET /api/cli/apps/{account}/{app}/domains/{host}", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainHost, s.handleAPIDomainGet) |
| + // The placements read (#447, apiplacements.go): which boxes serve the |
| + // claim's target, where, and whether it is ready. The per-host read's |
| + // roles and team scope exactly; it discloses no more about the claim. |
| + s.cliScopedRoute("GET /api/cli/apps/{account}/{app}/domains/{host}/placements", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainHost, s.handleAPIDomainPlacementsGet) |
| s.cliScopedRoute("POST /api/cli/apps/{account}/{app}/domains", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainBody, s.handleAPIDomainAttach) |
| s.cliScopedRoute("DELETE /api/cli/apps/{account}/{app}/domains/{host}", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainHost, s.handleAPIDomainDetach) |
| // The prefix-map publish (path-based routing): replace the WHOLE map of |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 774ece49b..a41f844a2 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -829,6 +829,10 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level}": claimRead("serves exact LTX versions through lease.VersionedStore reads only"), |
| "route GET /api/cli/apps/{account}/{app}/domains": claimRead("lists domain claims"), |
| "route GET /api/cli/apps/{account}/{app}/domains/{host}": claimRead("reads one domain claim and its DNS status"), |
| + |
| + // The placements read (#447). |
| + "route GET /api/cli/apps/{account}/{app}/domains/{host}/placements": claimRead("reads one domain claim, the edges files and the box heartbeats"), |
| + |
| "route GET /api/cli/apps/{account}/{app}/door-keys": claimRead("lists door keys"), |
| "route GET /api/cli/apps/{account}/{app}/edge-refs/{code}": claimRead("reads one edge record and the mesh key to verify the code"), |
| "route GET /api/cli/apps/{account}/{app}/email": claimRead("reads the email record"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index b4529b1bd..d47cbfe41 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -202,8 +202,13 @@ var claimReadProbes = map[string]claimProbe{ |
| "/api/cli/apps/bab/titogo/db/"+claimDBHost+"/ltx/0", `"files"`, `"handle"`, `"min_txid":1`), |
| "route GET /api/cli/apps/{account}/{app}/domains": claimAPIRead(claimWorldAlias, "/api/cli/apps/bab/titogo/domains", "tickets.example.com"), |
| "route GET /api/cli/apps/{account}/{app}/domains/{host}": claimAPIRead(claimWorldAlias, "/api/cli/apps/bab/titogo/domains/tickets.example.com", "tickets.example.com"), |
| - "route GET /api/cli/apps/{account}/{app}/door-keys": claimAPIRead(claimWorldDoorKey, "/api/cli/apps/bab/titogo/door-keys", `"label":"router"`), |
| - "route GET /api/cli/apps/{account}/{app}/policy": claimAPIRead(claimWorldPolicy, "/api/cli/apps/bab/titogo/policy", `"default_size":"small"`), |
| + |
| + // The placements read (#447). |
| + "route GET /api/cli/apps/{account}/{app}/domains/{host}/placements": claimAPIRead(claimWorldAlias, |
| + "/api/cli/apps/bab/titogo/domains/tickets.example.com/placements", `"mode":"single"`), |
| + |
| + "route GET /api/cli/apps/{account}/{app}/door-keys": claimAPIRead(claimWorldDoorKey, "/api/cli/apps/bab/titogo/door-keys", `"label":"router"`), |
| + "route GET /api/cli/apps/{account}/{app}/policy": claimAPIRead(claimWorldPolicy, "/api/cli/apps/bab/titogo/policy", `"default_size":"small"`), |
| "route GET /api/cli/apps/{account}/{app}/email": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.emailDeclared(t) }, |
| "/api/cli/apps/bab/titogo/email", claimMailDomain), |
| "route GET /api/cli/apps/{account}/{app}/email/events": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.emailProvisioned(t) }, |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 320dde688..5f2c843e8 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -676,6 +676,11 @@ var exemptFromLegacyPin = map[string]bool{ |
| // published, which the instance list and GET .../instances/{host} the |
| // role already reaches carry most of. |
| "GET /api/cli/apps/{account}/{app}/assets": true, |
| + // The placements read (#447) stands on GET .../domains/{host}'s |
| + // footing: the same claim, plus which boxes serve its route and their |
| + // public addresses, which DNS for the route already shows. It did not |
| + // exist before service principals. |
| + "GET /api/cli/apps/{account}/{app}/domains/{host}/placements": true, |
| } |
| // TestInstanceRoleMatchesTodaysAppTokenReach is the compatibility pin of spec |
diff --git a/internal/console/teamdoors_test.go b/internal/console/teamdoors_test.go| index a0fd29055..aaf771069 100644 |
| --- a/internal/console/teamdoors_test.go |
| +++ b/internal/console/teamdoors_test.go |
| @@ -50,6 +50,9 @@ var teamDoors = []string{ |
| "POST /api/cli/apps/{account}/{app}/restart/scope", |
| "GET /api/cli/apps/{account}/{app}/domains", |
| "GET /api/cli/apps/{account}/{app}/domains/{host}", |
| + // The placements read (#447) is the per-host read's twin: same roles, |
| + // same team scope. |
| + "GET /api/cli/apps/{account}/{app}/domains/{host}/placements", |
| "POST /api/cli/apps/{account}/{app}/domains", |
| "DELETE /api/cli/apps/{account}/{app}/domains/{host}", |
| } |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 67a46d5c7..90c592ebb 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -53,6 +53,7 @@ route GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level} |
| route GET /api/cli/apps/{account}/{app}/db/{host}/ltx/{level}/{span} |
| route GET /api/cli/apps/{account}/{app}/domains |
| route GET /api/cli/apps/{account}/{app}/domains/{host} |
| +route GET /api/cli/apps/{account}/{app}/domains/{host}/placements |
| route GET /api/cli/apps/{account}/{app}/door-keys |
| route GET /api/cli/apps/{account}/{app}/edge-refs/{code} |
| route GET /api/cli/apps/{account}/{app}/email |
diff --git a/internal/release/layoutintent.go b/internal/release/layoutintent.go| index dfcf68a74..cd28e1b62 100644 |
| --- a/internal/release/layoutintent.go |
| +++ b/internal/release/layoutintent.go |
| @@ -246,6 +246,15 @@ var RootfsLifecycleFloor = SemVer{Major: 0, Minor: 29, Patch: 0} |
| // TestTeamEnvironmentFloorIsPinned pins it. |
| var TeamEnvironmentFloor = SemVer{Major: 0, Minor: 30, Patch: 0} |
| +// RegionalDomainsFloor is the first platform release that reads a regional |
| +// custom-domain claim (#447): a box below it serves such a claim as an |
| +// ordinary alias of its route, so the placements GET counts a box toward a |
| +// regional claim's readiness only at or above it (console/apiplacements.go, |
| +// boxAtRegionalFloor). Single-mode claims ignore it. |
| +// |
| +// RegionalDomainsFloor: provisional until Task 12 pins it. |
| +var RegionalDomainsFloor = SemVer{Major: 0, Minor: 31, Patch: 0} |
| + |
| // RootfsFloorOverrideFlag is the override's flag name, on `carlos system |
| // update`, `carlos system rollback` and `carlos system apply`. |
| const RootfsFloorOverrideFlag = "allow-below-rootfs-floor" |