console: app pages show instances on other boxes
Every app page and the account app list drew their instance rows from the console box's own registry, so an instance whose route lives on another box (a region move, an instance created in another region) was invisible: "No instances yet", no metrics, a 404 on its page. Assemble (through Server.assembleApps) now adds a row for each of the account's bucket instance records whose host the console box's registry does not have. Records come from the change-index record view's latest Complete snapshot when armed (no requests), else from the bucket. Live state for those rows (version, database size, DNS and certificate, custom domains, awake) comes from the box reports, read once per minute console-wide (pageBoxReports) and joined only for hosts this account's records name, never from a report whose rollout names another tenant. Metrics flow through unchanged: the remote hosts reach the allowlist via Detail.Routes. Also: the instance page finds remote hosts and takes their aliases from the box report; channelHosts (the canary-retire guard) counts instance and sidecar records read strictly and live, and fails closed; the Fleet tab counts apps from records; carlos instances list takes remote health from the box reports; the review banner's "no instances" and "not deploying" claims count remote rows. Local rows stay authoritative for their hosts. Tests: two boxes and one bucket, instances created through the console's create door, minted by each box's reconcile pass and reported by CollectBox/WriteBox, pages driven through the HTTP server.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+1,279
−25
internal/console/accountfleet.go+36 −1internal/console/apiinstances.go+45 −2internal/console/instancepage.go+5 −1internal/console/overview.go+10 −3internal/console/overview_test.go+3 −0internal/console/remoteinstances.go+324 −0internal/console/remoteinstances_test.go+701 −0internal/console/server.go+82 −17internal/console/view.go+73 −1
CI failed — run details
diff --git a/internal/console/accountfleet.go b/internal/console/accountfleet.go| index ab2dd6327..75d9a0ce4 100644 |
| --- a/internal/console/accountfleet.go |
| +++ b/internal/console/accountfleet.go |
| @@ -144,9 +144,44 @@ func (s *Server) assembleAccountFleet(ctx context.Context, acct *Account) (card |
| platformApps[rt.App] = true |
| } |
| } |
| + // The console box's registry holds only the routes on this box. An |
| + // app whose instances run on the shared fleet's other boxes is |
| + // counted from its instance records, the same rule: a record not |
| + // placed on a customer fleet runs on the shared fleet. Records are |
| + // read per app of THIS account, under its own prefix, so nothing of |
| + // another account's can be counted. |
| + known := true |
| + if apps, err := s.store.AppsIn(acct.ID); err != nil { |
| + log.Printf("console: account fleet %s: apps: %v", acct.Sqid, err) |
| + known = false |
| + } else { |
| + for _, app := range apps { |
| + if platformApps[app] { |
| + continue |
| + } |
| + recs, err := s.pageRecords(ctx, acct.Sqid, app) |
| + if err != nil { |
| + log.Printf("console: account fleet %s: records of %s: %v", acct.Sqid, app, err) |
| + known = false |
| + continue |
| + } |
| + for _, rec := range recs { |
| + if rec.Account != acct.Sqid || rec.App != app { |
| + continue |
| + } |
| + if _, placed := registry.FleetPlacement(rec.Region); !placed { |
| + platformApps[app] = true |
| + break |
| + } |
| + } |
| + } |
| + } |
| + if !known && warn == "" { |
| + warn = "Could not read where your apps are running." |
| + } |
| card.PlatformApps = len(platformApps) |
| card.Active = card.PlatformApps > 0 |
| - card.PlacementKnown = true |
| + card.PlacementKnown = known |
| } |
| rows, err := reg.ListFleets() |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 41cba2081..411259815 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -282,7 +282,42 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma |
| unitByHost[rec.Host] = rt.Unit |
| } |
| } |
| - for h, word := range s.healthByHost(ctx, routeFor) { |
| + // A record whose route is on another box has no row here. Its health |
| + // comes from the box that reports it, the same join the app pages make |
| + // (remoteinstances.go): picked only for this record's own account and |
| + // app, so another tenant's report never answers for it. A record no box |
| + // reports stays "Setting up". |
| + var awake map[string]bool |
| + if s.cfg.Releases != nil { |
| + var reports fleetReports |
| + loaded := false |
| + for _, rec := range recs { |
| + if _, local := byHost[rec.Host]; local { |
| + continue |
| + } |
| + if !loaded { |
| + boxes, complete := s.pageBoxReports(ctx) |
| + reports, loaded = foldFleetReports(boxes, complete, time.Now()), true |
| + } |
| + rep := reports.pick(rec.Host, rec.Account, rec.App) |
| + if rep == nil { |
| + continue |
| + } |
| + kind := rec.Kind |
| + if kind == "" { |
| + kind = "instance" |
| + } |
| + routeFor[rec.Host] = registry.Route{Host: rec.Host, Kind: kind, Status: "ready", |
| + Hibernate: rec.HibernateOrDefault(), Provisioned: true} |
| + if rep.tenantKnown && rep.awake { |
| + if awake == nil { |
| + awake = map[string]bool{} |
| + } |
| + awake[rec.Host] = true |
| + } |
| + } |
| + } |
| + for h, word := range s.healthByHostAwake(ctx, routeFor, awake) { |
| out[h] = word |
| } |
| return out |
| @@ -301,6 +336,14 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma |
| // own app. The scoping lives in each caller, beside the reason that |
| // caller's rows are the caller's to see. |
| func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry.Route) map[string]string { |
| + return s.healthByHostAwake(ctx, routeFor, nil) |
| +} |
| + |
| +// healthByHostAwake is healthByHost where awake names hosts whose box |
| +// reports their process awake (an instance on another box, joined from its |
| +// box report): those read as reporting even when the sweep has no sample |
| +// yet, as the Running tab reads them. |
| +func (s *Server) healthByHostAwake(ctx context.Context, routeFor map[string]registry.Route, awake map[string]bool) map[string]string { |
| out := make(map[string]string, len(routeFor)) |
| hosts := make([]string, 0, len(routeFor)) |
| unitByHost := map[string]string{} |
| @@ -330,7 +373,7 @@ func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry. |
| if status == "" { |
| status = "ready" // registry contract: empty status means ready |
| } |
| - out[h] = healthWord(rt.Kind, status, rt.Hibernate, rep[h], |
| + out[h] = healthWord(rt.Kind, status, rt.Hibernate, rep[h] || awake[h], |
| expectsReadings(rt.Provisioned, rt.Unit, rt.Backing)) |
| } |
| return out |
diff --git a/internal/console/instancepage.go b/internal/console/instancepage.go| index 34067fe19..0a6fceda7 100644 |
| --- a/internal/console/instancepage.go |
| +++ b/internal/console/instancepage.go |
| @@ -294,7 +294,11 @@ func (s *Server) handleAppInstance(w http.ResponseWriter, r *http.Request) { |
| // the Installed and Serving facts above come from one reading. |
| detail.Updates = s.updatesPage(r.Context(), acct, p.AppName, host, detail, join.update(host, acct.Sqid, p.AppName), p.Role == RoleOwner) |
| } |
| - if reg, err := openRegistry(s.cfg.Registry); err == nil { |
| + if selected.remote { |
| + // An instance on another box: its custom domains are that box's |
| + // alias rows, from the one report the row joined (remoteinstances.go). |
| + detail.Aliases = append(detail.Aliases, selected.aliases...) |
| + } else if reg, err := openRegistry(s.cfg.Registry); err == nil { |
| if aliases, err := reg.ListAliases(); err == nil { |
| for _, alias := range aliases { |
| if alias.Host == host && alias.Account == acct.Sqid && alias.App == p.AppName { |
diff --git a/internal/console/overview.go b/internal/console/overview.go| index 03db7eba9..b0dd5dc17 100644 |
| --- a/internal/console/overview.go |
| +++ b/internal/console/overview.go |
| @@ -127,7 +127,14 @@ func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, ver |
| if rt.Account != acct || rt.Platform { |
| continue |
| } |
| - if n := dbJoin.dbSize(rt.Host); n != nil { |
| + // A remote row carries the size from the one box report it joined |
| + // (remoteinstances.go: never a report naming another tenant); the |
| + // host-keyed join has no tenant to check. |
| + n := dbJoin.dbSize(rt.Host) |
| + if rt.remote { |
| + n = rt.dbBytes |
| + } |
| + if n != nil { |
| if st.DBSizeSum == nil { |
| st.DBSizeSum = new(int64) |
| } |
| @@ -140,7 +147,7 @@ func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, ver |
| st.InstanceTotal++ |
| if rt.Kind == "instance" { |
| st.InstanceExpected++ |
| - if reporting[rt.Host] { |
| + if reporting[rt.Host] || rt.boxAwake { |
| st.InstanceReporting++ |
| } else if rt.Hibernate { |
| st.InstanceAsleep++ |
| @@ -261,7 +268,7 @@ func assembleInstanceRows(view *AppView, acct *Account, metrics []InstanceMetric |
| Hibernate: rt.Hibernate, |
| Metrics: byHost[rt.Host], |
| Restartable: rt.Restartable, |
| - HealthWord: healthWord(rt.Kind, status, rt.Hibernate, byHost[rt.Host].Reporting(), |
| + HealthWord: healthWord(rt.Kind, status, rt.Hibernate, byHost[rt.Host].Reporting() || rt.boxAwake, |
| expectsReadings(rt.Provisioned, rt.Unit, rt.Backing)), |
| }) |
| } |
diff --git a/internal/console/overview_test.go b/internal/console/overview_test.go| index fece75e74..42abeaab0 100644 |
| --- a/internal/console/overview_test.go |
| +++ b/internal/console/overview_test.go |
| @@ -753,6 +753,9 @@ func TestAppOverviewDatabaseTileRenders(t *testing.T) { |
| if err := status.WriteBox(context.Background(), fx.rel, box); err != nil { |
| t.Fatal(err) |
| } |
| + // The pages share a minute-old read of the box reports |
| + // (pageBoxReports); a new report shows once that read ages out. |
| + fx.srv.boxReports.expire() |
| _, _, body = get(t, c, fx.u("/apps/kass")) |
| if !strings.Contains(body, "3.0 MB") || !strings.Contains(body, "on disk, including copies that are asleep") { |
| t.Fatalf("sized app: want 3.0 MB on the Database tile in:\n%s", body) |
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go| new file mode 100644 |
| index 000000000..22178ebb3 |
| --- /dev/null |
| +++ b/internal/console/remoteinstances.go |
| @@ -0,0 +1,324 @@ |
| +package console |
| + |
| +// Instances on other boxes (docs/superpowers/notes/console-remote-instances.md). |
| +// |
| +// The app pages used to draw every instance row from the console box's own |
| +// registry, so an instance whose route lives on another box (a region move, |
| +// an instance created in another region) was invisible: "No instances yet", |
| +// no metrics, a 404 on its page. The account's bucket instance records are |
| +// the region-neutral list, and every box's status report says what it serves. |
| +// This file joins the two into extra RouteView rows for Assemble. |
| +// |
| +// Two reads, neither of them new polling: |
| +// |
| +// - Records come from the change-index record view's latest Complete |
| +// snapshot when the console has one armed (zero requests), else from the |
| +// bucket, which is the read the Logs and Settings tabs already make. |
| +// - Box reports (status/boxes/*.json) come from one console-wide read held |
| +// for boxReportTTL. Boxes rewrite them every status.SnapshotPeriod (five |
| +// minutes), so a minute's cache loses nothing. |
| +// |
| +// The tenant boundary is the record: a remote row exists only for a host |
| +// that a record under apps/<this account>/<this app>/ names. The box maps |
| +// are keyed by host and carry no tenant, so they are joined only for those |
| +// hosts, and a box whose rollout report names another tenant for the host |
| +// is not joined at all (the R18 rule boxJoin.rollout applies). |
| + |
| +import ( |
| + "context" |
| + "log" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// boxReportTTL is how long a page view's read of the box reports serves |
| +// every later page view. boxReportFailTTL is the shorter hold for a read |
| +// that failed, so a bucket hiccup costs the pages a few seconds of |
| +// "can't tell" rather than a minute, without every view retrying at once. |
| +const ( |
| + boxReportTTL = 60 * time.Second |
| + boxReportFailTTL = 10 * time.Second |
| +) |
| + |
| +// boxReportCache is the console-wide read of status/boxes/. One load at a |
| +// time (mu is held across it), so a burst of page views costs one read. |
| +type boxReportCache struct { |
| + mu sync.Mutex |
| + at time.Time |
| + valid bool |
| + failed bool |
| + boxes []status.Box |
| + complete bool |
| + // now is the cache's clock; nil is time.Now. Tests set it. |
| + now func() time.Time |
| +} |
| + |
| +func (c *boxReportCache) clock() time.Time { |
| + if c.now != nil { |
| + return c.now() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// pageBoxReports returns every box's report, from the cache when it is |
| +// young enough, and whether the read saw every box (status.LoadBoxesComplete). |
| +// The load runs on its own bounded context, detached from the request's |
| +// cancellation, so one closed browser tab cannot fail the read for the |
| +// views queued behind it. The snapshots are shared and must not be changed. |
| +func (s *Server) pageBoxReports(ctx context.Context) ([]status.Box, bool) { |
| + if s.cfg.Releases == nil { |
| + return nil, false |
| + } |
| + c := &s.boxReports |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + now := c.clock() |
| + ttl := boxReportTTL |
| + if c.failed { |
| + ttl = boxReportFailTTL |
| + } |
| + if c.valid && now.Sub(c.at) < ttl { |
| + return c.boxes, c.complete |
| + } |
| + loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), instanceStoreTimeout) |
| + defer cancel() |
| + boxes, complete, err := status.LoadBoxesComplete(loadCtx, s.cfg.Releases) |
| + if err != nil { |
| + log.Printf("console: box reports for the app pages: %v", err) |
| + boxes, complete = nil, false |
| + } |
| + c.at, c.valid, c.failed, c.boxes, c.complete = now, true, err != nil, boxes, complete |
| + return boxes, complete |
| +} |
| + |
| +// hostReport is one fresh box's word about one host it serves. |
| +type hostReport struct { |
| + box string |
| + at time.Time |
| + // version is the box's registry Version for the host (RouteVersions), |
| + // the same column a local row's Version reads. |
| + version string |
| + dbBytes *int64 |
| + // reading is the host's own DNS and certificate reading (an Aliases |
| + // entry whose Route is the host itself), nil when the box has none. |
| + reading *status.AliasReading |
| + // aliases are the custom domains this box routes to the host. |
| + aliases []string |
| + // tenantKnown is whether the box's rollout report names the host's |
| + // account and app; awake is only meaningful when it does. |
| + tenantKnown bool |
| + account, app string |
| + awake bool |
| +} |
| + |
| +// fleetReports is every fresh box's word about every host, folded once per |
| +// page view from the cached reports. |
| +type fleetReports struct { |
| + byHost map[string][]hostReport |
| + // complete is whether every box's report was read. Only a complete read |
| + // can say "no box serves this host". |
| + complete bool |
| +} |
| + |
| +// foldFleetReports folds the box reports a page has into per-host reports. |
| +// Stale boxes are left out under the fleet's one staleness rule |
| +// (status.BoxStale), as every other box join does. |
| +func foldFleetReports(boxes []status.Box, complete bool, now time.Time) fleetReports { |
| + f := fleetReports{byHost: map[string][]hostReport{}, complete: complete} |
| + for _, b := range boxes { |
| + m := b.Metrics |
| + if m == nil || status.BoxStale(b, now, status.SnapshotPeriod) { |
| + continue |
| + } |
| + reps := map[string]*hostReport{} |
| + get := func(host string) *hostReport { |
| + r := reps[host] |
| + if r == nil { |
| + r = &hostReport{box: b.Label, at: b.GeneratedAt} |
| + reps[host] = r |
| + } |
| + return r |
| + } |
| + for host, v := range m.RouteVersions { |
| + get(host).version = v |
| + } |
| + for host := range m.RouteServing { |
| + get(host) |
| + } |
| + for host, n := range m.RouteDBBytes { |
| + get(host).dbBytes = &n |
| + } |
| + if m.Rollout != nil { |
| + for host, hr := range m.Rollout.Hosts { |
| + r := get(host) |
| + r.tenantKnown, r.account, r.app = true, hr.Account, hr.App |
| + r.awake = hr.Awake && !hr.Transient |
| + } |
| + } |
| + for name, reading := range m.Aliases { |
| + reading := reading |
| + if reading.Route == name { |
| + get(name).reading = &reading |
| + continue |
| + } |
| + if reading.Route != "" { |
| + r := get(reading.Route) |
| + r.aliases = append(r.aliases, name) |
| + } |
| + } |
| + for host, r := range reps { |
| + sort.Strings(r.aliases) |
| + f.byHost[host] = append(f.byHost[host], *r) |
| + } |
| + } |
| + return f |
| +} |
| + |
| +// pick is the one box report a remote row of acct/app joins for host, or |
| +// nil. A report whose rollout names another tenant is never joined: a fresh |
| +// snapshot may predate the host changing hands. Among the rest, a report |
| +// that names this tenant beats one that names none (an older box), then the |
| +// freshest wins, then the lower box label, so the choice is stable. Two |
| +// boxes reporting one host is a move in flight; the page shows one row. |
| +func (f fleetReports) pick(host, acct, app string) *hostReport { |
| + var best *hostReport |
| + for i := range f.byHost[host] { |
| + r := &f.byHost[host][i] |
| + if r.tenantKnown && (r.account != acct || r.app != app) { |
| + continue |
| + } |
| + if best == nil || betterReport(r, best) { |
| + best = r |
| + } |
| + } |
| + return best |
| +} |
| + |
| +func betterReport(a, b *hostReport) bool { |
| + if a.tenantKnown != b.tenantKnown { |
| + return a.tenantKnown |
| + } |
| + if !a.at.Equal(b.at) { |
| + return a.at.After(b.at) |
| + } |
| + return a.box < b.box |
| +} |
| + |
| +// remoteRows is what Assemble needs to add the account's instances on other |
| +// boxes: a record reader already scoped to the viewed account, and the |
| +// folded box reports. |
| +type remoteRows struct { |
| + records func(app string) ([]provision.Record, error) |
| + reports fleetReports |
| +} |
| + |
| +// remoteRoute folds one record that has no row in the console box's registry |
| +// into a RouteView and its parallel DomainView. |
| +// |
| +// Status: "ready" when a fresh box reports the host; "pending" (Setting up) |
| +// when every box was read and none does, which is a record whose route has |
| +// not been minted anywhere; "" (unknown) otherwise. A record placed on a |
| +// customer fleet is never "pending": fleet boxes report elsewhere, so the |
| +// platform's reports cannot vouch for its absence. |
| +// |
| +// Unit and Caps are deliberately empty. Unit feeds the metrics allowlist |
| +// (appResourceMetrics), and the metrics boundary for a remote row is the |
| +// host's own carlos-exec@ and carlos-app@ units and nothing a record names. |
| +// Restartable is false: the browser restart door acts on the console box's |
| +// registry only. |
| +func remoteRoute(rec provision.Record, rep *hostReport, complete bool, acct string, dns DNSTargets) (RouteView, DomainView) { |
| + kind := rec.Kind |
| + if kind == "" { |
| + kind = "instance" |
| + } |
| + ch := rec.Channel |
| + if ch == "" { |
| + ch = "stable" |
| + } |
| + _, fleetPlaced := registry.FleetPlacement(rec.Region) |
| + rv := RouteView{ |
| + Host: rec.Host, Kind: kind, Channel: ch, |
| + Hibernate: rec.HibernateOrDefault(), |
| + Account: acct, |
| + Environment: rec.Environment, |
| + Provisioned: true, |
| + remote: true, |
| + } |
| + typ := "custom" |
| + if strings.HasPrefix(ch, "canary/") { |
| + typ += " · " + ch |
| + } |
| + dv := DomainView{Domain: rec.Host, Type: typ} |
| + switch { |
| + case rep != nil: |
| + rv.Status = "ready" |
| + rv.Version = rep.version |
| + rv.box = rep.box |
| + rv.dbBytes = rep.dbBytes |
| + rv.aliases = rep.aliases |
| + if rep.tenantKnown && rep.awake { |
| + rv.boxAwake = true |
| + } |
| + if rd := rep.reading; rd != nil { |
| + dv.DNS = rd.DNSStatus |
| + if rd.CertExpiresAt > 0 { |
| + dv.TLS = "ready · renews " + time.Unix(rd.CertExpiresAt, 0).UTC().Format("2006-01-02") |
| + } |
| + // domainView's rule: guidance only for a reading that says the |
| + // member's record is missing or wrong. No reading is not that. |
| + if rd.DNSStatus != "" && rd.DNSStatus != "pointing" && rd.DNSStatus != "unresolved" { |
| + dv.Guidance = domainGuidance(rec.Host, dns) |
| + } |
| + } |
| + case complete && !fleetPlaced: |
| + rv.Status = "pending" |
| + } |
| + return rv, dv |
| +} |
| + |
| +// pageRecords reads acct/app's instance records for a page view. With the |
| +// record view armed and its latest snapshot Complete it reads the snapshot |
| +// and makes no request: the run and seed sweeps keep it within a pass of the |
| +// bucket, and a page view does not refresh it. Otherwise it reads the bucket |
| +// (one LIST plus a GET per record), the read the Logs tab always made. |
| +func (s *Server) pageRecords(ctx context.Context, acct, app string) ([]provision.Record, error) { |
| + if s.cfg.Releases == nil { |
| + return nil, nil |
| + } |
| + store := s.cfg.Releases |
| + if v := s.recordView; v != nil { |
| + if sn := v.Snapshot(); sn != nil && sn.Complete { |
| + store = sn.Store(s.cfg.Releases) |
| + } |
| + } |
| + recs, _, err := provision.ListRecords(ctx, store, acct, app, instanceListMax) |
| + return recs, err |
| +} |
| + |
| +// remoteSource builds Assemble's remote input for one page view of acct. |
| +func (s *Server) remoteSource(ctx context.Context, acct string) *remoteRows { |
| + if s.cfg.Releases == nil { |
| + return nil |
| + } |
| + boxes, complete := s.pageBoxReports(ctx) |
| + return &remoteRows{ |
| + records: func(app string) ([]provision.Record, error) { |
| + rctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| + defer cancel() |
| + return s.pageRecords(rctx, acct, app) |
| + }, |
| + reports: foldFleetReports(boxes, complete, time.Now()), |
| + } |
| +} |
| + |
| +// assembleApps is Assemble for a page view: the console box's registry rows |
| +// plus the account's instances on other boxes. |
| +func (s *Server) assembleApps(ctx context.Context, acct string, apps []string) ([]AppView, error) { |
| + return assemble(ctx, s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct, apps, s.dnsTargets(), s.remoteSource(ctx, acct)) |
| +} |
diff --git a/internal/console/remoteinstances_test.go b/internal/console/remoteinstances_test.go| new file mode 100644 |
| index 000000000..8b6b4120f |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_test.go |
| @@ -0,0 +1,701 @@ |
| +package console |
| + |
| +// Instances on other boxes, end to end (remoteinstances.go). Two boxes and |
| +// one bucket: box A is the console's own box (the fixture's registry), box B |
| +// is a second region with its own registry. Instances are created through |
| +// the console's real create door, minted by each box's real reconcile pass, |
| +// and reported by each box's real status snapshot (status.CollectBox over |
| +// the box's own registry, written with status.WriteBox) and a metrics chunk |
| +// in the shape the box's sweep writes. The pages are driven through the real |
| +// HTTP server with a real session. |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// expire ages the page views' shared box-report read out, as a minute |
| +// passing would. |
| +func (c *boxReportCache) expire() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.valid = false |
| +} |
| + |
| +// twoBoxes is the fixture: the console on box A ("ie"), a second box B |
| +// ("uk"), and an account "Shop" (paul owns it) with an app "shop". |
| +type twoBoxes struct { |
| + fx *consoleFixture |
| + sqid string |
| + token string // paul's CLI token |
| + regB *registry.Registry |
| + dataB string |
| + dataA string |
| + browser *http.Client |
| +} |
| + |
| +const ( |
| + remoteHost = "eu.shop.example.com" |
| + localHost = "ie.shop.example.com" |
| +) |
| + |
| +func shopManifest(app, domain string) provision.Manifest { |
| + return provision.Manifest{Schema: 1, App: app, Domain: domain, |
| + Pool: "shop", Channel: "stable", Regions: []string{"ie", "uk"}} |
| +} |
| + |
| +func newTwoBoxes(t *testing.T) *twoBoxes { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + const acctID int64 = 5151 |
| + sqid := accountSqid(acctID) |
| + if err := fx.st.CreateAccount(acctID, sqid, "Shop", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(acctID, "shop", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := WriteAccountManifest(ctx, fx.rel, acctID, sqid, "Shop", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, fx.rel, sqid, "shop", shopManifest("shop", "shop.example.com")); err != nil { |
| + t.Fatal(err) |
| + } |
| + shipAndPromote(t, fx, sqid, "shop", "v3", "stable") |
| + regB, err := registry.Open(filepath.Join(t.TempDir(), "registry-b.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { regB.Close() }) |
| + tb := &twoBoxes{fx: fx, sqid: sqid, regB: regB, dataA: t.TempDir(), dataB: t.TempDir()} |
| + tb.token = cliToken(t, fx, "paul@keymail.dev", "code-remote-cli") |
| + tb.browser = signInPaul(t, fx) |
| + return tb |
| +} |
| + |
| +func shipAndPromote(t *testing.T, fx *consoleFixture, sqid, app, version, channel string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + m := release.Manifest{Schema: 1, App: app, Version: version, Kind: "binary", BuiltAt: "2026-10-01T10:00:00Z", |
| + Artifacts: map[string]release.Artifact{"linux-amd64": {File: app}}} |
| + if err := release.Ship(ctx, fx.rel, sqid, m, map[string][]byte{"linux-amd64": []byte("binary " + version)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.Promote(ctx, fx.rel, fx.priv, sqid, app, channel, version); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// create runs the console's create door for host in region. |
| +func (tb *twoBoxes) create(t *testing.T, token, sqid, app, host, region, channel string) { |
| + t.Helper() |
| + body := `{"host":"` + host + `","region":"` + region + `"` |
| + if channel != "" { |
| + body += `,"channel":"` + channel + `"` |
| + } |
| + body += `}` |
| + if status, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, sqid, app), token, body); status != http.StatusCreated { |
| + t.Fatalf("create %s in %s = %d %s", host, region, status, out) |
| + } |
| +} |
| + |
| +// reconcile runs both boxes' real reconcile passes and stamps every |
| +// provisioned route's version the way the adopt pass does. |
| +func (tb *twoBoxes) reconcile(t *testing.T, version string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + regA, err := registry.Open(tb.fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, box := range []struct { |
| + reg *registry.Registry |
| + region string |
| + data string |
| + }{{regA, "ie", tb.dataA}, {tb.regB, "uk", tb.dataB}} { |
| + cfg := provision.ReconcileConfig{Region: box.region, Pools: []string{"shop"}, DataDir: box.data} |
| + if err := provision.Reconcile(ctx, tb.fx.rel, box.reg, cfg); err != nil { |
| + t.Fatalf("reconcile %s: %v", box.region, err) |
| + } |
| + routes, err := box.reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rt := range routes { |
| + if rt.Provisioned && rt.Version == "" { |
| + if err := box.reg.SetVersions(rt.Host, version, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// report writes box's status snapshot from its own registry: what the |
| +// agent's status tick does (CollectBox over the registry and its aliases), |
| +// with the rollout report naming each provisioned route's own tenant, and |
| +// a database size for each route. |
| +func report(t *testing.T, rel release.Store, reg *registry.Registry, machine, region string, at time.Time, awake map[string]bool, dbBytes int64) string { |
| + t.Helper() |
| + routes, err := reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + aliases, err := reg.ListAliases() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ro := &status.RolloutReport{Hosts: map[string]status.HostRollout{}} |
| + for _, rt := range routes { |
| + if rt.Provisioned { |
| + ro.Hosts[rt.Host] = status.HostRollout{Account: rt.Account, App: rt.App, Installed: rt.Version, Awake: awake[rt.Host]} |
| + } |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: machine, Region: region, Aliases: aliases, Rollout: ro, |
| + DBBytes: func(string) *int64 { n := dbBytes; return &n }}, at) |
| + if err := status.WriteBox(context.Background(), rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.Label |
| +} |
| + |
| +// sweep writes box's metrics chunk: one exec-child unit per host given. |
| +func sweep(t *testing.T, rel release.Store, box string, units map[string]metrics.UnitSample) { |
| + t.Helper() |
| + at := time.Now().UTC().Add(-time.Minute) |
| + if err := metrics.WriteRaw(context.Background(), rel, metrics.RawChunk{ |
| + V: 1, Box: box, Hour: metrics.HourOf(at), |
| + Samples: []metrics.Sample{{At: at, Units: units}}, |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (tb *twoBoxes) page(t *testing.T, path string) string { |
| + t.Helper() |
| + status, loc, body := get(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+path) |
| + if status != http.StatusOK { |
| + t.Fatalf("GET %s = %d -> %q\n%s", path, status, loc, body) |
| + } |
| + return body |
| +} |
| + |
| +// setUp creates the remote instance (and, with local, one on the console's |
| +// box too), mints, reports and sweeps. |
| +func (tb *twoBoxes) setUp(t *testing.T, local bool) { |
| + t.Helper() |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + if local { |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "") |
| + } |
| + tb.reconcile(t, "v3") |
| + // B's domains pass has checked the host and its certificate, and B |
| + // routes one custom domain to it: the readings its report carries. |
| + certAt := time.Date(2027, 1, 15, 0, 0, 0, 0, time.UTC).Unix() |
| + if err := tb.regB.SetDNSStatus(remoteHost, "pointing", time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.regB.SetCertExpiresAt(remoteHost, certAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.regB.UpsertAlias(registry.RouteAlias{Alias: "www.shop-store.example", Host: remoteHost, |
| + Account: tb.sqid, App: "shop", DNSStatus: "pointing", CertExpiresAt: certAt}); err != nil { |
| + t.Fatal(err) |
| + } |
| + regA, err := registry.Open(tb.fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, regA, "box-a", "ie", time.Now(), nil, 1024) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + sweep(t, tb.fx.rel, "box-b", map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.27), MemBytes: pi64(3 << 20)}, |
| + }) |
| +} |
| + |
| +// TestRemoteInstanceMintsOnlyOnItsBox pins the fixture itself: the record |
| +// becomes a route on B and not on the console's box, which is the state |
| +// every page test below relies on. |
| +func TestRemoteInstanceMintsOnlyOnItsBox(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + regA, _ := registry.Open(tb.fx.regPath) |
| + if rt, err := regA.Get(remoteHost); err != nil || rt != nil { |
| + t.Fatalf("the console's box minted the uk instance: %+v %v", rt, err) |
| + } |
| + if rt, err := tb.regB.Get(remoteHost); err != nil || rt == nil || rt.Version != "v3" { |
| + t.Fatalf("box B did not mint the uk instance: %+v %v", rt, err) |
| + } |
| +} |
| + |
| +func TestRemoteInstancePages(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + |
| + // Account home: deployed, with the instance's address. |
| + home := tb.page(t, "/") |
| + if !strings.Contains(home, remoteHost) || !strings.Contains(home, "Deployed") || strings.Contains(home, "Not deployed yet") { |
| + t.Fatalf("account home does not show the remote instance as deployed:\n%s", home) |
| + } |
| + |
| + // Overview: one instance, B's version, B's CPU and memory, B's database |
| + // size, not the empty state. |
| + ov := tb.page(t, "/apps/shop") |
| + for _, bad := range []string{"No instances yet", "Not deployed yet", "nothing running yet"} { |
| + if strings.Contains(ov, bad) { |
| + t.Fatalf("overview still says %q:\n%s", bad, ov) |
| + } |
| + } |
| + for _, want := range []string{"27%", "3.0 MB", "4.0 KB", "DNS & certs OK"} { |
| + if !strings.Contains(ov, want) { |
| + t.Fatalf("overview is missing %q:\n%s", want, ov) |
| + } |
| + } |
| + |
| + // Running: the row, Running from B's sweep, no restart button. |
| + run := tb.page(t, "/apps/shop/instances") |
| + row := instanceRow(t, run, remoteHost) |
| + if !strings.Contains(row, "Running") || !strings.Contains(row, "v3") { |
| + t.Fatalf("Running row for the remote instance = %s", row) |
| + } |
| + if strings.Contains(run, "Nothing running yet") { |
| + t.Fatalf("Running tab shows the empty state:\n%s", run) |
| + } |
| + |
| + // The instance page renders instead of a 404. |
| + inst := tb.page(t, "/apps/shop/instances/"+remoteHost) |
| + if !strings.Contains(inst, remoteHost) || !strings.Contains(inst, "www.shop-store.example") { |
| + t.Fatalf("instance page does not name its host and B's alias for it:\n%s", inst) |
| + } |
| + |
| + // Settings, Domains: the host's row with B's certificate date. |
| + set := tb.page(t, "/apps/shop/settings/domains") |
| + if !strings.Contains(set, remoteHost) || !strings.Contains(set, "renews 2027-01-15") { |
| + t.Fatalf("settings domains does not list the remote host with B's cert date:\n%s", set) |
| + } |
| + |
| + // Deployments counts it on stable at v3. |
| + dep := tb.page(t, "/apps/shop/deployments") |
| + if !strings.Contains(dep, "1 × <a href=\"/a/"+tb.sqid+"/apps/shop/releases#version-v3\"><code>v3</code>") || |
| + !strings.Contains(dep, "<td>1 <a href=\"/a/"+tb.sqid+"/apps/shop/instances?channel=stable\">") { |
| + t.Fatalf("deployments does not count the remote instance:\n%s", dep) |
| + } |
| + |
| + // Fleet tab: one app on the shared fleet. |
| + card, _, _, warn := tb.fx.srv.assembleAccountFleet(context.Background(), tb.account(t)) |
| + if card.PlatformApps != 1 || !card.PlacementKnown || warn != "" { |
| + t.Fatalf("fleet card = %+v warn %q, want 1 app on the shared fleet", card, warn) |
| + } |
| + |
| + // `carlos instances list`: the record's health comes from B, not |
| + // "Setting up". |
| + status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, "") |
| + if status != http.StatusOK || !strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| +} |
| + |
| +func (tb *twoBoxes) account(t *testing.T) *Account { |
| + t.Helper() |
| + acct, err := tb.fx.st.AccountBySqid(tb.sqid) |
| + if err != nil || acct == nil { |
| + t.Fatalf("account %s: %v", tb.sqid, err) |
| + } |
| + return acct |
| +} |
| + |
| +// TestRemoteInstanceLocalRowWins: a host with a row on the console's box is |
| +// shown once, from that row, even when another box reports it too (a move |
| +// in flight). |
| +func TestRemoteInstanceLocalRowWins(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, true) |
| + // B also reports the local host, at another version: the move-in-flight |
| + // shape. The local row's version must win, once. |
| + if err := tb.regB.Upsert(registry.Route{Host: localHost, Kind: "instance", App: "shop", Account: tb.sqid, |
| + Channel: "stable", Version: "v9", Provisioned: true, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var hosts []string |
| + for _, rt := range views[0].Routes { |
| + hosts = append(hosts, rt.Host+"@"+rt.Version) |
| + if rt.Host == localHost && rt.remote { |
| + t.Fatalf("the local host was shown from another box's report: %+v", rt) |
| + } |
| + } |
| + if got := strings.Join(hosts, ","); got != remoteHost+"@v3,"+localHost+"@v3" { |
| + t.Fatalf("rows = %s", got) |
| + } |
| + if len(views[0].Domains) != len(views[0].Routes) { |
| + t.Fatalf("Routes and Domains are no longer parallel: %d vs %d", len(views[0].Routes), len(views[0].Domains)) |
| + } |
| +} |
| + |
| +// TestRemoteInstanceCrossAccount is the tenant boundary: another account |
| +// has an app with the same name, with an instance on the same remote box, |
| +// in the same box report and the same metrics chunk. Nothing of it may |
| +// reach this account's pages: not the host, not its CPU, memory or database |
| +// size, not a count. |
| +func TestRemoteInstanceCrossAccount(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + const rivalID int64 = 6262 |
| + rival := accountSqid(rivalID) |
| + if err := tb.fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := tb.fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := WriteAccountManifest(ctx, tb.fx.rel, rivalID, rival, "Rival", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, tb.fx.rel, rival, "shop", shopManifest("shop", "rival.example.net")); err != nil { |
| + t.Fatal(err) |
| + } |
| + bob := cliToken(t, tb.fx, "bob@keymail.dev", "code-remote-bob") |
| + tb.fx.setUser("paul@keymail.dev") |
| + const rivalHost = "uk.rival.example.net" |
| + tb.create(t, bob, rival, "shop", rivalHost, "uk", "") |
| + tb.setUp(t, false) |
| + // B's report now carries both tenants; the sweep both units. |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 9216) |
| + sweep(t, tb.fx.rel, "box-b", map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.27), MemBytes: pi64(3 << 20)}, |
| + "carlos-exec@" + rivalHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + if rt, _ := tb.regB.Get(rivalHost); rt == nil { |
| + t.Fatal("fixture: box B did not mint the rival's instance") |
| + } |
| + for _, path := range []string{"/", "/apps/shop", "/apps/shop/instances", "/apps/shop/deployments", |
| + "/apps/shop/settings", "/apps/shop/releases", "/apps/shop/logs"} { |
| + body := tb.page(t, path) |
| + for _, bad := range []string{rivalHost, "66%", "7.0 MB", "rival.example.net"} { |
| + if strings.Contains(body, bad) { |
| + t.Fatalf("%s leaked another account's %q:\n%s", path, bad, body) |
| + } |
| + } |
| + } |
| + // The overview counts one instance and B's size for this account's |
| + // host only (9216 bytes each: one host is 9.0 KB, two would be 18 KB). |
| + ov := tb.page(t, "/apps/shop") |
| + if !strings.Contains(ov, "9.0 KB") || strings.Contains(ov, "18 KB") { |
| + t.Fatalf("overview database size is not this account's alone:\n%s", ov) |
| + } |
| + if status, _, _ := get(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/shop/instances/"+rivalHost); status != http.StatusNotFound { |
| + t.Fatalf("instance page for another account's host = %d, want 404", status) |
| + } |
| + // And the other way round: bob's pages show his host, not paul's. |
| + c, _ := signInAs(t, tb.fx, "bob@keymail.dev", "code-remote-bob-web") |
| + _, _, body := get(t, c, tb.fx.ts.URL+"/a/"+rival+"/apps/shop/instances") |
| + if !strings.Contains(body, rivalHost) || strings.Contains(body, remoteHost) || strings.Contains(body, "27%") { |
| + t.Fatalf("rival's Running tab:\n%s", body) |
| + } |
| +} |
| + |
| +// TestRemoteReportNamingAnotherTenant is R18: a fresh box report whose |
| +// rollout names another tenant for this account's host is not joined, even |
| +// though the record is this account's. |
| +func TestRemoteReportNamingAnotherTenant(t *testing.T) { |
| + now := time.Now() |
| + boxes := []status.Box{{GeneratedAt: now, Label: "b", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v7"}, |
| + RouteDBBytes: map[string]int64{"h.example.com": 77}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{ |
| + "h.example.com": {Account: "other", App: "shop", Awake: true}, |
| + }}, |
| + }}} |
| + f := foldFleetReports(boxes, true, now) |
| + if rep := f.pick("h.example.com", "mine", "shop"); rep != nil { |
| + t.Fatalf("joined a report naming another account: %+v", rep) |
| + } |
| + if rep := f.pick("h.example.com", "other", "web"); rep != nil { |
| + t.Fatalf("joined a report naming another app: %+v", rep) |
| + } |
| + if rep := f.pick("h.example.com", "other", "shop"); rep == nil || rep.version != "v7" || !rep.awake { |
| + t.Fatalf("the named tenant's own report = %+v", rep) |
| + } |
| + rv, dv := remoteRoute(provision.Record{Host: "h.example.com", App: "shop", Account: "mine"}, f.pick("h.example.com", "mine", "shop"), true, "mine", DNSTargets{}) |
| + if rv.Version != "" || rv.dbBytes != nil || rv.boxAwake || rv.Status != "pending" || dv.TLS != "" || dv.Guidance != "" { |
| + t.Fatalf("row from a refused report = %+v %+v", rv, dv) |
| + } |
| +} |
| + |
| +// TestRemoteReportStaleAndMoving: a stale box is not joined (the version is |
| +// unknown, so the page says it can't tell); with two fresh boxes reporting |
| +// one host, the report naming the tenant wins, then the freshest. |
| +func TestRemoteReportStaleAndMoving(t *testing.T) { |
| + now := time.Now() |
| + stale := status.Box{GeneratedAt: now.Add(-time.Hour), Label: "old", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v1"}}} |
| + f := foldFleetReports([]status.Box{stale}, true, now) |
| + rv, _ := remoteRoute(provision.Record{Host: "h.example.com", App: "shop", Account: "a"}, f.pick("h.example.com", "a", "shop"), f.complete, "a", DNSTargets{}) |
| + if rv.Version != "" || rv.Status != "pending" { |
| + t.Fatalf("a stale report was joined: %+v", rv) |
| + } |
| + // Incomplete read: not "Setting up", and the overview can't tell. |
| + f = foldFleetReports([]status.Box{stale}, false, now) |
| + rv, dv := remoteRoute(provision.Record{Host: "h.example.com", App: "shop", Account: "a"}, f.pick("h.example.com", "a", "shop"), f.complete, "a", DNSTargets{}) |
| + if rv.Status != "" { |
| + t.Fatalf("an incomplete read vouched for absence: %+v", rv) |
| + } |
| + view := &AppView{Routes: []RouteView{rv}, Domains: []DomainView{dv}} |
| + if st := assembleOverview(view, "a", []InstanceMetrics{}, nil, boxJoin{}); st.VerdictLabel != "Can't tell right now" { |
| + t.Fatalf("verdict with no fresh report = %q", st.VerdictLabel) |
| + } |
| + |
| + older := status.Box{GeneratedAt: now.Add(-2 * time.Minute), Label: "a", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v1"}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{"h.example.com": {Account: "a", App: "shop"}}}}} |
| + newerNoTenant := status.Box{GeneratedAt: now, Label: "b", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v2"}}} |
| + newer := status.Box{GeneratedAt: now.Add(-time.Minute), Label: "c", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v3"}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{"h.example.com": {Account: "a", App: "shop"}}}}} |
| + f = foldFleetReports([]status.Box{older, newerNoTenant, newer}, true, now) |
| + if rep := f.pick("h.example.com", "a", "shop"); rep == nil || rep.version != "v3" { |
| + t.Fatalf("move in flight picked %+v, want the freshest report naming the tenant (v3)", rep) |
| + } |
| +} |
| + |
| +// TestRemoteRecordsAccountFilter: the records reader's own scoping is not |
| +// trusted alone. A record that disagrees with the viewed account or app is |
| +// never a row (the mutation target for the account filter in addRemoteRows). |
| +func TestRemoteRecordsAccountFilter(t *testing.T) { |
| + remote := &remoteRows{records: func(string) ([]provision.Record, error) { |
| + return []provision.Record{ |
| + {Host: "mine.example.com", App: "shop", Account: "a"}, |
| + {Host: "theirs.example.com", App: "shop", Account: "b"}, |
| + {Host: "sibling.example.com", App: "web", Account: "a"}, |
| + }, nil |
| + }, reports: fleetReports{complete: true}} |
| + routes, domains := addRemoteRows(remote, "a", "shop", map[string]bool{}, nil, nil, DNSTargets{}) |
| + if len(routes) != 1 || routes[0].Host != "mine.example.com" || len(domains) != 1 { |
| + t.Fatalf("rows = %+v", routes) |
| + } |
| +} |
| + |
| +// TestRetireCanaryRefusedForRemoteFollower is the canary-retire safety |
| +// check: the only follower of canary/rc is an instance on box B, which the |
| +// console's own registry does not have. Retiring must be refused and the |
| +// pointer must survive. Then a record that will not read fails it closed. |
| +func TestRetireCanaryRefusedForRemoteFollower(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Channel != "canary/rc" { |
| + t.Fatalf("fixture: box B's follower = %+v", rt) |
| + } |
| + regA, _ := registry.Open(tb.fx.regPath) |
| + if rt, _ := regA.Get(remoteHost); rt != nil { |
| + t.Fatalf("fixture: the console's box has the follower: %+v", rt) |
| + } |
| + csrf := sessionToken(t, tb.fx, tb.browser) |
| + retire := func() (int, string, string) { |
| + return postForm(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/shop/canary/retire", |
| + url.Values{"csrf": {csrf}, "name": {"rc"}, "confirmed": {"1"}}) |
| + } |
| + status, loc, body := retire() |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("retire = %d -> %q %s", status, loc, body) |
| + } |
| + _, _, page := get(t, tb.browser, tb.fx.ts.URL+loc) |
| + if !strings.Contains(page, "still has a host ("+remoteHost+") following it") { |
| + t.Fatalf("retire was not refused for the remote follower:\n%s", page) |
| + } |
| + if _, _, err := tb.fx.rel.Get(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")); err != nil { |
| + t.Fatalf("the canary pointer is gone: %v", err) |
| + } |
| + |
| + // A record that will not parse could be a follower: fail closed. |
| + if _, err := tb.fx.rel.Put(context.Background(), provision.RecordKey(tb.sqid, "shop", "broken.shop.example.com"), []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.fx.rel.Delete(context.Background(), provision.RecordKey(tb.sqid, "shop", remoteHost)); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, _, body = retire() |
| + if status != http.StatusInternalServerError || !strings.Contains(body, "Could not verify") { |
| + t.Fatalf("retire with an unreadable record = %d %s", status, body) |
| + } |
| + if _, _, err := tb.fx.rel.Get(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")); err != nil { |
| + t.Fatalf("the canary pointer is gone after an unreadable record: %v", err) |
| + } |
| +} |
| + |
| +// TestChannelHostsCountsRemoteFollowers pins channelHosts directly: local |
| +// routes, instance records and sidecar records all count, once each. |
| +func TestChannelHostsCountsRemoteFollowers(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "stable") |
| + tb.reconcile(t, "v3") |
| + hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc") |
| + if err != nil || len(hosts) != 1 || hosts[0] != remoteHost { |
| + t.Fatalf("canary/rc followers = %v %v, want [%s]", hosts, err, remoteHost) |
| + } |
| + hosts, err = tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "stable") |
| + if err != nil || len(hosts) != 1 || hosts[0] != localHost { |
| + t.Fatalf("stable followers = %v %v, want [%s] once", hosts, err, localHost) |
| + } |
| + // A sidecar following a canary from another region counts too. |
| + if err := provision.PutSidecarManifest(context.Background(), tb.fx.rel, tb.sqid, "shop", provision.SidecarManifest{ |
| + Schema: 1, App: "shop", Pool: "shop", Channel: "stable", Regions: []string{"ie", "uk"}, Args: []string{"worker"}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, _, out := rawReq(t, http.MethodPost, tb.fx.ts.URL+"/api/cli/apps/"+tb.sqid+"/shop/sidecars", tb.token, |
| + `{"name":"bot","region":"uk","channel":"canary/side"}`); status != http.StatusCreated { |
| + t.Fatalf("sidecar create = %d %s", status, out) |
| + } |
| + hosts, err = tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/side") |
| + if err != nil || len(hosts) != 1 || hosts[0] != provision.SidecarHost("bot", "shop", tb.sqid) { |
| + t.Fatalf("canary/side followers = %v %v, want the sidecar", hosts, err) |
| + } |
| + // A failing bucket is an error, never "nobody". |
| + tb.fx.srv.cfg.Releases = remoteFailingRecordStore{tb.fx.rel} |
| + if hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); err == nil { |
| + t.Fatalf("channelHosts over a failing bucket = %v, nil error", hosts) |
| + } |
| +} |
| + |
| +type remoteFailingRecordStore struct{ release.Store } |
| + |
| +func (s remoteFailingRecordStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + if strings.Contains(prefix, "/instances/") || strings.Contains(prefix, "/sidecars/") { |
| + return nil, fmt.Errorf("boom") |
| + } |
| + return s.Store.List(ctx, prefix) |
| +} |
| + |
| +// budgetStore counts the reads the request budget is about: box reports |
| +// and instance records. |
| +type budgetStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + boxLists, boxGets, recLists, recGets int |
| +} |
| + |
| +func (c *budgetStore) note(key string, list bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + switch { |
| + case strings.HasPrefix(key, "status/boxes/") && list: |
| + c.boxLists++ |
| + case strings.HasPrefix(key, "status/boxes/"): |
| + c.boxGets++ |
| + case strings.HasPrefix(key, "apps/") && strings.Contains(key, "/instances/") && list: |
| + c.recLists++ |
| + case strings.HasPrefix(key, "apps/") && strings.Contains(key, "/instances/"): |
| + c.recGets++ |
| + } |
| +} |
| + |
| +func (c *budgetStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + c.note(prefix, true) |
| + return c.Store.List(ctx, prefix) |
| +} |
| + |
| +func (c *budgetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.note(key, false) |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *budgetStore) counts() [4]int { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return [4]int{c.boxLists, c.boxGets, c.recLists, c.recGets} |
| +} |
| + |
| +func (c *budgetStore) reset() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.boxLists, c.boxGets, c.recLists, c.recGets = 0, 0, 0, 0 |
| +} |
| + |
| +// TestRemoteInstanceRequestBudget counts store calls per page view. Armed |
| +// record view: the first Overview view reads the box reports once (one LIST |
| +// and one GET per box) and no record; a second view within a minute reads |
| +// nothing; after the minute it reads the reports once more. Every app tab |
| +// shares the one read. Unarmed: the records cost one LIST plus one GET per |
| +// record, the read the Logs tab always made. |
| +func TestRemoteInstanceRequestBudget(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + cs := &budgetStore{Store: tb.fx.rel} |
| + tb.fx.srv.cfg.Releases = cs |
| + v := provision.NewRecordView(cs, release.NewChangeWatch(cs)) |
| + if err := v.Rebuild(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if sn := v.Snapshot(); sn == nil || !sn.Complete { |
| + t.Fatal("fixture: the record view is not Complete") |
| + } |
| + tb.fx.srv.SetRecordView(v) |
| + clock := time.Now() |
| + tb.fx.srv.boxReports.now = func() time.Time { return clock } |
| + // The DNS guidance's edge-address fold reads status/boxes/ too, on its |
| + // own edgeFoldTTL cache, and predates this change; it is not part of |
| + // this budget, so it is stubbed out of the count. |
| + tb.fx.srv.foldEdgeIPs = func(context.Context) []string { return nil } |
| + cs.reset() |
| + |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [4]int{1, 2, 0, 0} { |
| + t.Fatalf("first armed overview: box LIST/GET, record LIST/GET = %v, want [1 2 0 0]", got) |
| + } |
| + cs.reset() |
| + // The pages whose only box-report read is this change's. (The Running |
| + // tab, the instance page, Settings and Releases each make reads of their |
| + // own that predate it: the region note, the rollout join, the domain |
| + // readings. They are unchanged, and the Running tab is pinned below.) |
| + for _, path := range []string{"/apps/shop", "/apps/shop/deployments", "/"} { |
| + tb.page(t, path) |
| + } |
| + if got := cs.counts(); got != [4]int{0, 0, 0, 0} { |
| + t.Fatalf("views within the minute = %v, want no box or record reads", got) |
| + } |
| + // The Running tab's region note reads the reports itself, through |
| + // liveEdges (appDefault), and did before this change. One read is that |
| + // note's; a second would be this change failing to share the cache. |
| + cs.reset() |
| + tb.page(t, "/apps/shop/instances") |
| + if got := cs.counts(); got != [4]int{1, 2, 0, 0} { |
| + t.Fatalf("Running tab within the minute = %v, want only the region note's own [1 2 0 0]", got) |
| + } |
| + clock = clock.Add(boxReportTTL + time.Second) |
| + cs.reset() |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [4]int{1, 2, 0, 0} { |
| + t.Fatalf("overview after the minute = %v, want [1 2 0 0]", got) |
| + } |
| + |
| + // Unarmed: one LIST and one GET for the app's one record. |
| + tb.fx.srv.SetRecordView(nil) |
| + cs.reset() |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [4]int{0, 0, 1, 1} { |
| + t.Fatalf("unarmed overview within the minute = %v, want [0 0 1 1]", got) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index c351563ad..1572e9a80 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1188,6 +1188,10 @@ type Server struct { |
| // arms it; nil (disarmed) is every sweep walking the bucket as before |
| // the index. |
| recordView *provision.RecordView |
| + // boxReports is the page views' shared read of every box's status report |
| + // (remoteinstances.go), held for boxReportTTL so the app pages ask the |
| + // bucket at most once a minute however many people browse. |
| + boxReports boxReportCache |
| // viewUse is the last recordWalkStore outcome, so a switch between the |
| // view and the bucket is logged once, not on every pass. |
| viewUse atomic.Int32 |
| @@ -3248,7 +3252,7 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if len(apps) > 0 { |
| - views, err := Assemble(s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, apps, s.dnsTargets()) |
| + views, err := s.assembleApps(r.Context(), acct.Sqid, apps) |
| if err != nil { |
| log.Printf("console: assemble: %v", err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read platform state. Please try again.") |
| @@ -3404,7 +3408,7 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa |
| // bucket hiccup there is deliberately non-fatal, and this is where it gets |
| // another chance. Best-effort — a page view never fails on it. |
| s.ensureAccountManifest(r.Context(), acct) |
| - views, err := Assemble(s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, []string{app}, s.dnsTargets()) |
| + views, err := s.assembleApps(r.Context(), acct.Sqid, []string{app}) |
| if err != nil || len(views) != 1 { |
| log.Printf("console: assemble %s: %v", app, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read platform state. Please try again.") |
| @@ -3424,8 +3428,20 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa |
| if review, all, err := s.appAccountReview(addr, acct, app); err != nil { |
| log.Printf("console: account review %s/%s: %v", acct.Sqid, app, err) |
| } else { |
| + // The review itself reads the console box's registry: it is about |
| + // local rows stamped with another account. Its two claims about the |
| + // app as a whole ("no instances", "not deploying") must also count |
| + // the account's instances on other boxes, or an app whose instances |
| + // all moved away would be told it has none. |
| + remoteOwned := 0 |
| + for _, rt := range p.Detail.Routes { |
| + if rt.remote && rt.Account == acct.Sqid { |
| + remoteOwned++ |
| + } |
| + } |
| + all = all && remoteOwned == 0 |
| p.AccountReview = review |
| - p.AccountReview.NoInstances = review.Owned == 0 && hasPublishedChannel(p.Detail.Channels) |
| + p.AccountReview.NoInstances = review.Owned == 0 && remoteOwned == 0 && hasPublishedChannel(p.Detail.Channels) |
| for _, group := range review.Groups { |
| for _, host := range group.Hosts { |
| p.Detail.Mismatched = append(p.Detail.Mismatched, MismatchedRoute{Host: host, Account: group.Account.Sqid}) |
| @@ -3549,9 +3565,10 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) { |
| metrics := s.appResourceMetrics(r.Context(), p.Detail, acct) |
| // The Database tile's sizes are best-effort: a slow status read costs the |
| // tile its number (the em-dash), never the page. |
| - joinCtx, cancelJoin := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| - dbJoin := loadBoxJoin(joinCtx, s.cfg.Releases, time.Now()) |
| - cancelJoin() |
| + // The box reports are the page views' shared, minute-old read |
| + // (pageBoxReports), the same one Assemble joined remote rows from. |
| + boxes, _ := s.pageBoxReports(r.Context()) |
| + dbJoin := joinBoxes(boxes, time.Now()) |
| p.Overview = assembleOverview(p.Detail, acct.Sqid, metrics, versions, dbJoin) |
| // The diagram is drawn from the SAME tenant-filtered rows the Running tab |
| // renders, so the two can never disagree about which addresses exist or |
| @@ -3792,7 +3809,7 @@ func (s *Server) handleAppLogs(w http.ResponseWriter, r *http.Request) { |
| } |
| if s.cfg.Releases != nil { |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| - recs, _, err := provision.ListRecords(ctx, s.cfg.Releases, acct.Sqid, p.AppName, instanceListMax) |
| + recs, err := s.pageRecords(ctx, acct.Sqid, p.AppName) |
| cancel() |
| if err == nil { |
| for _, rec := range recs { |
| @@ -5115,14 +5132,27 @@ func (s *Server) handleFastTrack(w http.ResponseWriter, r *http.Request) { |
| // name becomes a channel path segment and an on-box state file name. |
| var canaryNameRe = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`) |
| -// channelHosts lists the registry hosts whose routes follow app's channel, |
| -// and reports whether the registry could be read at all. The two call sites |
| -// deliberately treat that error differently: handleNewCanary's use is |
| +// channelHosts lists the hosts that follow app's channel, and reports |
| +// whether that could be checked at all. Two sources, because a follower can |
| +// live on any box: |
| +// |
| +// - the console box's registry: every route of an app by this NAME (any |
| +// account: over-counting here only ever refuses a retire), as before; |
| +// - acct/app's instance and sidecar records in the bucket, read strictly |
| +// and live (not through the record view: a record written without its |
| +// change-index bump is missing from a snapshot until the backstop, and |
| +// this is the one reader whose "nobody" deletes something). A follower |
| +// whose route is on another box is in no registry this console can see, |
| +// so without the records a canary followed only from another region |
| +// would read as unfollowed, be retired, and strand that host. |
| +// |
| +// The two call sites treat the error differently: handleNewCanary's use is |
| // cosmetic (which URL to show in a success flash) and downgrades an error to |
| -// "no hosts", but handleRetireCanary's use is load-bearing — a canary with |
| -// followers must never be deleted — so it must fail CLOSED on a registry |
| -// hiccup rather than silently reading the error as "safe to retire". |
| -func (s *Server) channelHosts(app, channel string) ([]string, error) { |
| +// "no hosts", but handleRetireCanary's use is load-bearing, a canary with |
| +// followers must never be deleted, so it fails CLOSED: an unreadable |
| +// registry, a failed listing, a record that will not read or parse, or more |
| +// records than the cap is an error, never "nobody follows this channel". |
| +func (s *Server) channelHosts(ctx context.Context, acct, app, channel string) ([]string, error) { |
| reg, err := openRegistry(s.cfg.Registry) |
| if err != nil { |
| return nil, err |
| @@ -5132,9 +5162,42 @@ func (s *Server) channelHosts(app, channel string) ([]string, error) { |
| return nil, err |
| } |
| var out []string |
| + seen := map[string]bool{} |
| + add := func(host string) { |
| + if !seen[host] { |
| + seen[host] = true |
| + out = append(out, host) |
| + } |
| + } |
| for _, rt := range routes { |
| if rt.App == app && rt.Channel == channel { |
| - out = append(out, rt.Host) |
| + add(rt.Host) |
| + } |
| + } |
| + if s.cfg.Releases == nil { |
| + return out, nil |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| + defer cancel() |
| + recs, unreadable, err := provision.ListRecordsStrict(ctx, s.cfg.Releases, acct, app, instanceListMax) |
| + if err != nil { |
| + return nil, fmt.Errorf("instance records of %s/%s: %w", acct, app, err) |
| + } |
| + if len(unreadable) > 0 { |
| + return nil, fmt.Errorf("instance records of %s/%s: %d will not read", acct, app, len(unreadable)) |
| + } |
| + for _, rec := range recs { |
| + if rec.Channel == channel { |
| + add(rec.Host) |
| + } |
| + } |
| + sidecars, err := provision.ListSidecarRecordsStrict(ctx, s.cfg.Releases, acct, app) |
| + if err != nil { |
| + return nil, fmt.Errorf("sidecar records of %s/%s: %w", acct, app, err) |
| + } |
| + for _, rec := range sidecars { |
| + if rec.Channel == channel { |
| + add(rec.Host) |
| } |
| } |
| return out, nil |
| @@ -5224,7 +5287,7 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) { |
| // Best-effort here: which URL to show in the success flash is cosmetic, |
| // so a registry hiccup just falls back to the generic "attach one" copy |
| // rather than failing the create that already succeeded. |
| - if hosts, _ := s.channelHosts(app, channel); len(hosts) > 0 { |
| + if hosts, _ := s.channelHosts(ctx, acct.Sqid, app, channel); len(hosts) > 0 { |
| back("ok", "Created canary "+name+" — live at https://"+hosts[0]+" serving "+version+" (test versions have no safety delay).") |
| return |
| } |
| @@ -5325,7 +5388,9 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| // A canary with followers is load-bearing: retiring its pointer would |
| // strand every host on it. Fail CLOSED on a registry error — an "I |
| // couldn't check" must never be read as "nobody follows this channel". |
| - hosts, err := s.channelHosts(app, channel) |
| + checkCtx, cancelCheck := context.WithTimeout(r.Context(), 15*time.Second) |
| + hosts, err := s.channelHosts(checkCtx, acct.Sqid, app, channel) |
| + cancelCheck() |
| if err != nil { |
| log.Printf("console: retire %s %s: check followers: %v", app, channel, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", |
diff --git a/internal/console/view.go b/internal/console/view.go| index 47b09e3f4..1c93c7eef 100644 |
| --- a/internal/console/view.go |
| +++ b/internal/console/view.go |
| @@ -364,6 +364,18 @@ type RouteView struct { |
| // Provisioned mirrors registry.Route.Provisioned: minted from a bucket |
| // instance record, so the activator runs its process by construction. |
| Provisioned bool |
| + |
| + // remote marks a row built from a bucket instance record whose route is |
| + // on another box (remoteinstances.go), not from the console box's own |
| + // registry. The rest are that row's live state from the box report it |
| + // joined: which box, its database size, the custom domains it routes to |
| + // the host, and whether its rollout report says the process is awake. |
| + // All zero on a local row. |
| + remote bool |
| + box string |
| + dbBytes *int64 |
| + aliases []string |
| + boxAwake bool |
| } |
| // humanizeCaps renders a registry.Route.Caps column for a person: the |
| @@ -549,8 +561,22 @@ func openRegistry(path string) (consoleRegistry, error) { |
| // edge addresses nor a steering hostname known). Every app in apps gets an |
| // AppView, even an empty one; per-channel failures degrade to |
| // ChannelView.Err. |
| +// |
| +// Assemble sees the console box's registry only. Page views go through |
| +// Server.assembleApps, which also adds the account's instances on other |
| +// boxes (remoteinstances.go). |
| func Assemble(regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets) ([]AppView, error) { |
| - ctx := context.Background() |
| + return assemble(context.Background(), regPath, s, pub, acct, apps, dns, nil) |
| +} |
| + |
| +// assemble is Assemble plus, when remote is not nil, a row for every |
| +// instance record of the account's apps whose host has no row in the console |
| +// box's registry. A host the registry has, under ANY account, gets no remote |
| +// row: the local row is authoritative for its host (Status, Unit, Backing, |
| +// Caps, the mismatch review), and a local row stamped to another account is |
| +// the account review's business, not a reason to show a second row. A record |
| +// that cannot be read costs that app its remote rows and nothing else. |
| +func assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, remote *remoteRows) ([]AppView, error) { |
| reg, err := openRegistry(regPath) |
| if err != nil { |
| return nil, err |
| @@ -566,7 +592,9 @@ func Assemble(regPath string, s release.Store, pub ed25519.PublicKey, acct strin |
| // the server, after it knows the viewer's memberships. |
| byApp := map[string][]RouteView{} |
| domainsByApp := map[string][]DomainView{} |
| + localHosts := make(map[string]bool, len(routes)) |
| for _, rt := range routes { |
| + localHosts[rt.Host] = true |
| rtAcct := release.RouteAccount(rt) |
| if rtAcct != acct { |
| continue |
| @@ -610,6 +638,9 @@ func Assemble(regPath string, s release.Store, pub ed25519.PublicKey, acct strin |
| continue |
| } |
| seen[app] = true |
| + if remote != nil { |
| + byApp[app], domainsByApp[app] = addRemoteRows(remote, acct, app, localHosts, byApp[app], domainsByApp[app], dns) |
| + } |
| channels := assembleChannels(ctx, s, pub, acct, app, now) |
| pv := assembleProduction(ctx, s, pub, acct, app, channels, byApp[app], now) |
| if pv.Err == "" && !pv.On { |
| @@ -642,6 +673,47 @@ func Assemble(regPath string, s release.Store, pub ed25519.PublicKey, acct strin |
| return out, nil |
| } |
| +// addRemoteRows appends a row for each of acct/app's records whose host the |
| +// console box's registry does not have, keeping Routes and Domains parallel |
| +// and in host order (assembleOverview joins them by index). |
| +// |
| +// The account check on each record is the tenant boundary and is made here |
| +// again, not trusted to the reader: a record is acct's only when it sits |
| +// under apps/<acct>/<app>/ AND says so (provision.GetRecord refuses one that |
| +// disagrees with its own path; this refuses one a reader handed over from |
| +// anywhere else). |
| +func addRemoteRows(remote *remoteRows, acct, app string, localHosts map[string]bool, routes []RouteView, domains []DomainView, dns DNSTargets) ([]RouteView, []DomainView) { |
| + recs, err := remote.records(app) |
| + if err != nil { |
| + log.Printf("console: instance records %s/%s: %v", acct, app, err) |
| + return routes, domains |
| + } |
| + added := false |
| + for _, rec := range recs { |
| + if rec.Account != acct || rec.App != app || rec.Host == "" || localHosts[rec.Host] { |
| + continue |
| + } |
| + rv, dv := remoteRoute(rec, remote.reports.pick(rec.Host, acct, app), remote.reports.complete, acct, dns) |
| + routes = append(routes, rv) |
| + domains = append(domains, dv) |
| + added = true |
| + } |
| + if added { |
| + idx := make([]int, len(routes)) |
| + for i := range idx { |
| + idx[i] = i |
| + } |
| + sort.SliceStable(idx, func(a, b int) bool { return routes[idx[a]].Host < routes[idx[b]].Host }) |
| + r2 := make([]RouteView, len(routes)) |
| + d2 := make([]DomainView, len(domains)) |
| + for i, j := range idx { |
| + r2[i], d2[i] = routes[j], domains[j] |
| + } |
| + routes, domains = r2, d2 |
| + } |
| + return routes, domains |
| +} |
| + |
| // assembleCanaries derives the canary list: every canary/* channel, with the |
| // hosts whose routes follow it. |
| func assembleCanaries(channels []ChannelView, routes []RouteView) []CanaryView { |