console-perf-hot-routes
Squashed from console-perf-hot-routes into main.
21 files changed,
+1,722
−158
internal/console/apiinstances.go+54 −8internal/console/apisystemupdate.go+154 −34internal/console/appframe.go+51 −33internal/console/hotreads.go+385 −0internal/console/hotreads_test.go+361 −0internal/console/instancesplacement.go+8 −2internal/console/lifetimes_read.go+58 −4internal/console/opboxes.go+27 −9internal/console/opdashboard.go+18 −5internal/console/perfbudgets_test.go+15 −4internal/console/perfhotroutes_test.go+324 −0internal/console/perflatency_test.go+9 −4internal/console/perfquickwins_test.go+3 −1internal/console/perfwalk_test.go+35 −6internal/console/remoteinstances.go+95 −15internal/console/reqmemo.go+50 −11internal/console/server.go+12 −1internal/console/testdata/perf-budgets.txt+29 −19internal/console/testdata/perf-session-s3.txt+1 −1internal/provision/console_perf_hot_routes_census_test.go+32 −0internal/provision/plan9_b8_census_test.go+1 −1
CI passed — run details
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index ac379f94b..f736a76bf 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -757,6 +757,32 @@ func (s *Server) loadRolloutJoin(ctx context.Context, acct string, now time.Time |
| return j, complete |
| } |
| +// warmRolloutBoxes makes the box-report reads loadRolloutJoin makes for acct |
| +// (the platform's, and each of acct's own fleets'), at once, into the |
| +// request memo, so a caller can start them beside other reads and have |
| +// loadRolloutJoin find them done. It decides nothing: a read that fails |
| +// here fails the same way for loadRolloutJoin, which reports it. |
| +func (s *Server) warmRolloutBoxes(ctx context.Context, acct string) { |
| + if s.cfg.Releases == nil { |
| + return |
| + } |
| + prefixes := []string{""} |
| + if s.cfg.Registry != "" { |
| + if reg, err := s.openPassRegistry(); err == nil { |
| + if fleets, err := reg.ListFleets(); err == nil { |
| + for _, f := range fleets { |
| + if f.Account == acct { |
| + prefixes = append(prefixes, "fleets/"+f.Name+"/") |
| + } |
| + } |
| + } |
| + } |
| + } |
| + forEachLimit(len(prefixes), readConcurrency, func(i int) { |
| + _, _, _ = s.loadBoxes(ctx, s.cfg.Releases, prefixes[i]) |
| + }) |
| +} |
| + |
| // recordFleets is the set of customer fleets that could hold reports for |
| // recs: the fleet each record is placed on (its Region, "fleet/<name>"), |
| // and either end of a move in flight. Never nil, so an app with no |
| @@ -939,9 +965,30 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| defer cancel() |
| - // Judged when the request was admitted with lifetimes on: a record its |
| - // slot no longer vouches for is not listed. Unjudged (nil) as main. |
| - recs, truncated, skipped, err := s.listRecordsComplete(ctx, acct.Sqid, app, instanceListMax) |
| + // The four reads below are independent, so they run at once: the |
| + // records, the box reports the rollout join reads (into the request |
| + // memo, where loadRolloutJoin and instanceHealth find them), the edges |
| + // files, and the app's update policy. |
| + var ( |
| + recs []provision.Record |
| + truncated bool |
| + skipped []string |
| + err error |
| + served map[string][]servedBy |
| + manifest *provision.Manifest |
| + policyErr error |
| + ) |
| + runConcurrently( |
| + func() { |
| + // Judged when the request was admitted with lifetimes on: a |
| + // record its slot no longer vouches for is not listed. |
| + // Unjudged (nil) as main. |
| + recs, truncated, skipped, err = s.listRecordsComplete(ctx, acct.Sqid, app, instanceListMax) |
| + }, |
| + func() { s.warmRolloutBoxes(ctx, acct.Sqid) }, |
| + func() { served = loadEdgesJoin(ctx, s.cfg.Releases) }, |
| + func() { manifest, policyErr = provision.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app) }, |
| + ) |
| if err != nil { |
| log.Printf("console: api instances list %s/%s: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusBadGateway, "could not list instances") |
| @@ -957,15 +1004,14 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) { |
| relevant = nil |
| } |
| join, joinComplete := s.loadRolloutJoin(ctx, acct.Sqid, time.Now(), relevant) |
| - served := loadEdgesJoin(ctx, s.cfg.Releases) |
| // The app's update policy, read once: an absent manifest is no policy, |
| // and a read error is logged and treated the same. The list never fails |
| // for it; SettingsDefault is then computed from the record alone. |
| var policy *provision.UpdatePolicy |
| - if m, err := provision.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app); err == nil { |
| - policy = m.Updates |
| - } else if !errors.Is(err, os.ErrNotExist) { |
| - log.Printf("console: api instances list %s/%s: update policy: %v; settings_default computed from the records alone", acct.Sqid, app, err) |
| + if policyErr == nil { |
| + policy = manifest.Updates |
| + } else if !errors.Is(policyErr, os.ErrNotExist) { |
| + log.Printf("console: api instances list %s/%s: update policy: %v; settings_default computed from the records alone", acct.Sqid, app, policyErr) |
| } |
| params := r.URL.Query() |
| q := parseInstanceQuery(params) |
diff --git a/internal/console/apisystemupdate.go b/internal/console/apisystemupdate.go| index 8bbe83abf..a32807071 100644 |
| --- a/internal/console/apisystemupdate.go |
| +++ b/internal/console/apisystemupdate.go |
| @@ -268,17 +268,35 @@ func (s *Server) systemFeed() publicrelease.Feed { |
| // cannot be opened, or one whose fleets cannot be listed, is a fleet set this |
| // console cannot see. |
| func (s *Server) systemBoxes(ctx context.Context, strict bool) ([]status.Box, bool, error) { |
| - boxes, _, err := s.loadBoxes(ctx, s.cfg.Releases, "") |
| + _, fleets, fleetsErr := s.systemFleets() |
| + // The platform's heartbeats and each fleet's are read at once, then |
| + // taken in the order they were always taken: the platform's, then the |
| + // fleets in registry order. |
| + type read struct { |
| + boxes []status.Box |
| + err error |
| + } |
| + prefixes := []string{""} |
| + if fleetsErr == nil { |
| + for _, f := range fleets { |
| + prefixes = append(prefixes, "fleets/"+f.Name+"/") |
| + } |
| + } |
| + reads := make([]read, len(prefixes)) |
| + forEachLimit(len(prefixes), readConcurrency, func(i int) { |
| + b, _, err := s.loadBoxes(ctx, s.cfg.Releases, prefixes[i]) |
| + reads[i] = read{b, err} |
| + }) |
| + boxes, err := reads[0].boxes, reads[0].err |
| if err != nil { |
| return nil, false, err |
| } |
| - _, fleets, err := s.systemFleets() |
| - if err != nil { |
| - return s.systemFleetsUnreadable(boxes, strict, err) |
| + if fleetsErr != nil { |
| + return s.systemFleetsUnreadable(boxes, strict, fleetsErr) |
| } |
| partial := false |
| - for _, f := range fleets { |
| - fb, _, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+f.Name+"/") |
| + for i, f := range fleets { |
| + fb, err := reads[i+1].boxes, reads[i+1].err |
| if err != nil { |
| if strict { |
| return nil, false, fmt.Errorf("fleet %s: cannot read its box heartbeats, refusing to guess which platforms to mirror: %w", f.Name, err) |
| @@ -690,7 +708,7 @@ func (s *Server) bootstrapState(ctx context.Context, stable *release.SystemPoint |
| row := map[string]any{"version": stable.Current.Version, "key": art.Key} |
| ctx, cancel := context.WithTimeout(ctx, bootstrapReadBudget) |
| defer cancel() |
| - got, err := s.objectSHA256(ctx, bootstrapKey) |
| + got, err := s.bootstrapSHA256(ctx) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| return nil |
| @@ -705,6 +723,76 @@ func (s *Server) bootstrapState(ctx context.Context, stable *release.SystemPoint |
| return row |
| } |
| +// bootstrapHash is bootstrapSHA256's memory: the sha256 of bootstrap/carlos |
| +// as last read, and the ETag it was read under. mu is held across a |
| +// comparison, so two status reads never download the binary at once. |
| +type bootstrapHash struct { |
| + mu sync.Mutex |
| + etag string |
| + sum string |
| +} |
| + |
| +// bootstrapSHA256 is objectSHA256 of bootstrapKey without downloading the |
| +// binary again while it has not changed. The first read streams the object |
| +// through a hasher and keeps the sum with the ETag it was read under. Each |
| +// later read asks the bucket for the object only if its ETag differs (a |
| +// conditional GET): an unchanged object answers 304 with no body, and its |
| +// sum is the one kept, since the same ETag names the same bytes. A changed |
| +// object comes back whole (in memory, once per change) and is hashed |
| +// afresh. So every status read still asks the bucket, and answers for the |
| +// object as it is at that moment; only the download of an unchanged binary |
| +// is gone. A store with no conditional read, or a conditional read that |
| +// fails while the request is still live, streams it, as before. |
| +func (s *Server) bootstrapSHA256(ctx context.Context) (string, error) { |
| + h := &s.bootstrapSum |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + if cg, ok := s.cfg.Releases.(release.ConditionalGetter); ok && h.etag != "" { |
| + body, etag, changed, err := cg.GetIfChanged(ctx, bootstrapKey, h.etag) |
| + if err == nil { |
| + err = ctx.Err() |
| + } |
| + switch { |
| + case err == nil && !changed: |
| + return h.sum, nil |
| + case err == nil: |
| + sum := sha256.Sum256(body) |
| + got := hex.EncodeToString(sum[:]) |
| + h.etag, h.sum = etag, got |
| + if etag == "" { |
| + h.sum = "" |
| + } |
| + return got, nil |
| + case errors.Is(err, os.ErrNotExist): |
| + h.etag, h.sum = "", "" |
| + return "", err |
| + case ctx.Err() != nil: |
| + return "", err |
| + } |
| + // The conditional read failed some other way (a store that cannot |
| + // make one answers errors.ErrUnsupported): forget the kept sum and |
| + // stream the object, as a first read does. The kept sum is never |
| + // the answer after an error. |
| + h.etag, h.sum = "", "" |
| + } |
| + rc, etag, err := release.OpenObject(ctx, s.cfg.Releases, bootstrapKey) |
| + if err != nil { |
| + h.etag, h.sum = "", "" |
| + return "", err |
| + } |
| + defer rc.Close() |
| + hs := sha256.New() |
| + if _, err := io.Copy(hs, rc); err != nil { |
| + return "", fmt.Errorf("%s: reading the object to compare it: %w", bootstrapKey, err) |
| + } |
| + if err := ctx.Err(); err != nil { |
| + return "", fmt.Errorf("%s: reading the object to compare it: %w", bootstrapKey, err) |
| + } |
| + sum := hex.EncodeToString(hs.Sum(nil)) |
| + h.etag, h.sum = etag, sum |
| + return sum, nil |
| +} |
| + |
| func (s *Server) handleAPISystemJob(w http.ResponseWriter, r *http.Request) { |
| if _, _, ok := s.apiSystemRoller(w, r); !ok { |
| return |
| @@ -898,32 +986,23 @@ func (s *Server) handleAPISystemStatus(w http.ResponseWriter, r *http.Request) { |
| pointers := map[string]any{} |
| targets := map[string]string{} |
| var stable *release.SystemPointer |
| - for _, ch := range []string{release.RungCanary, release.RungStable} { |
| - p, _, err := release.GetSystemPointer(ctx, s.cfg.Releases, s.cfg.ReleasePub, release.SystemComponentRouter, ch) |
| - switch { |
| - case errors.Is(err, os.ErrNotExist): |
| - // null means exactly one thing: this channel has never been |
| - // promoted. It must not also mean "there IS a pointer and this |
| - // console cannot verify it" โ a tampered or wrongly-signed |
| - // pointer reading as "never promoted" is the one failure an |
| - // operator most needs to see, shown as the one thing they would |
| - // ignore. |
| - pointers[ch] = nil |
| - case err != nil: |
| - log.Printf("console: api system status: %s pointer: %v", ch, err) |
| - pointers[ch] = map[string]any{"error": err.Error()} |
| - default: |
| - pointers[ch] = map[string]any{"version": p.Current.Version, "promoted_at": p.PromotedAt, "spread": p.Spread, "source": p.Current.Source, |
| - "history": len(p.History)} |
| - targets[ch] = p.Current.Version |
| - if ch == release.RungStable { |
| - stable = p |
| - } |
| - } |
| - } |
| - boxes, partial, err := s.systemBoxes(ctx, false) |
| - if err != nil { |
| - jsonError(w, http.StatusBadGateway, "box heartbeats unreadable: "+err.Error()) |
| + // The box heartbeats are read beside the two pointers and the |
| + // bootstrap comparison, which needs stable's pointer first. |
| + var ( |
| + boxes []status.Box |
| + partial bool |
| + boxesErr error |
| + bootstrap map[string]any |
| + ) |
| + runConcurrently( |
| + func() { boxes, partial, boxesErr = s.systemBoxes(ctx, false) }, |
| + func() { |
| + stable = s.systemStatusPointers(ctx, pointers, targets) |
| + bootstrap = s.bootstrapState(ctx, stable) |
| + }, |
| + ) |
| + if boxesErr != nil { |
| + jsonError(w, http.StatusBadGateway, "box heartbeats unreadable: "+boxesErr.Error()) |
| return |
| } |
| now := time.Now() |
| @@ -952,5 +1031,46 @@ func (s *Server) handleAPISystemStatus(w http.ResponseWriter, r *http.Request) { |
| // |
| // bootstrap is null when there is nothing to compare (bootstrapState). |
| writeJSON(w, http.StatusOK, map[string]any{"pointers": pointers, "boxes": rows, "partial": partial, |
| - "bootstrap": s.bootstrapState(ctx, stable)}) |
| + "bootstrap": bootstrap}) |
| +} |
| + |
| +// systemStatusPointers reads the canary and stable pointers at once into |
| +// pointers (each channel's row) and targets (each channel's version), and |
| +// returns stable's pointer when it read and verified. |
| +func (s *Server) systemStatusPointers(ctx context.Context, pointers map[string]any, targets map[string]string) *release.SystemPointer { |
| + channels := []string{release.RungCanary, release.RungStable} |
| + type read struct { |
| + p *release.SystemPointer |
| + err error |
| + } |
| + reads := make([]read, len(channels)) |
| + forEachLimit(len(channels), len(channels), func(i int) { |
| + p, _, err := release.GetSystemPointer(ctx, s.cfg.Releases, s.cfg.ReleasePub, release.SystemComponentRouter, channels[i]) |
| + reads[i] = read{p, err} |
| + }) |
| + var stable *release.SystemPointer |
| + for i, ch := range channels { |
| + p, err := reads[i].p, reads[i].err |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + // null means exactly one thing: this channel has never been |
| + // promoted. It must not also mean "there IS a pointer and this |
| + // console cannot verify it" โ a tampered or wrongly-signed |
| + // pointer reading as "never promoted" is the one failure an |
| + // operator most needs to see, shown as the one thing they would |
| + // ignore. |
| + pointers[ch] = nil |
| + case err != nil: |
| + log.Printf("console: api system status: %s pointer: %v", ch, err) |
| + pointers[ch] = map[string]any{"error": err.Error()} |
| + default: |
| + pointers[ch] = map[string]any{"version": p.Current.Version, "promoted_at": p.PromotedAt, "spread": p.Spread, "source": p.Current.Source, |
| + "history": len(p.History)} |
| + targets[ch] = p.Current.Version |
| + if ch == release.RungStable { |
| + stable = p |
| + } |
| + } |
| + } |
| + return stable |
| } |
diff --git a/internal/console/appframe.go b/internal/console/appframe.go| index 48ae009f4..2a6c6ba48 100644 |
| --- a/internal/console/appframe.go |
| +++ b/internal/console/appframe.go |
| @@ -99,47 +99,65 @@ func (f appFrame) clone() appFrame { |
| return out |
| } |
| -// loadAppFrame makes the frame's reads, in the order the app tabs have |
| -// always made them: the channel listing, each channel, the production flag, |
| -// then the pipeline (bounded by pipelineStoreTimeout, as it always was). |
| +// loadAppFrame makes the frame's reads: the channel listing and each |
| +// channel, the production flag, and the pipeline (bounded by |
| +// pipelineStoreTimeout, as it always was). The three are independent and |
| +// run at once, and the channels are read readConcurrency at a time, kept in |
| +// name order. |
| func loadAppFrame(ctx context.Context, st release.Store, pub ed25519.PublicKey, acct, app string) appFrame { |
| var f appFrame |
| + runConcurrently( |
| + func() { f.Channels, f.ChannelsErr = loadFrameChannels(ctx, st, pub, acct, app) }, |
| + func() { |
| + if flag, err := release.GetProduction(ctx, st, pub, acct, app); err != nil { |
| + f.ProductionErr = err.Error() |
| + } else { |
| + f.Production = flag |
| + } |
| + }, |
| + func() { |
| + pctx, cancel := context.WithTimeout(ctx, pipelineStoreTimeout) |
| + defer cancel() |
| + if pipe, err := release.GetPipeline(pctx, st, pub, acct, app); err != nil { |
| + f.PipelineErr = err.Error() |
| + } else { |
| + f.Pipeline = pipe |
| + } |
| + }, |
| + ) |
| + return f |
| +} |
| + |
| +// loadFrameChannels is the frame's channel listing and every channel's |
| +// pointer, sorted by name, or the listing's error text. |
| +func loadFrameChannels(ctx context.Context, st release.Store, pub ed25519.PublicKey, acct, app string) ([]frameChannel, string) { |
| prefix := release.ChannelsPrefix(acct, app) |
| keys, err := st.List(ctx, prefix) |
| if err != nil { |
| - f.ChannelsErr = err.Error() |
| - } else { |
| - var names []string |
| - for _, k := range keys { |
| - name := strings.TrimPrefix(k, prefix) |
| - if !strings.HasSuffix(name, ".json") { |
| - continue |
| - } |
| - names = append(names, strings.TrimSuffix(name, ".json")) |
| - } |
| - sort.Strings(names) |
| - for _, name := range names { |
| - p, err := release.Channel(ctx, st, pub, acct, app, name) |
| - if err != nil { |
| - f.Channels = append(f.Channels, frameChannel{Name: name, Err: err.Error()}) |
| - continue |
| - } |
| - f.Channels = append(f.Channels, frameChannel{Name: name, Pointer: p}) |
| - } |
| + return nil, err.Error() |
| } |
| - if flag, err := release.GetProduction(ctx, st, pub, acct, app); err != nil { |
| - f.ProductionErr = err.Error() |
| - } else { |
| - f.Production = flag |
| + var names []string |
| + for _, k := range keys { |
| + name := strings.TrimPrefix(k, prefix) |
| + if !strings.HasSuffix(name, ".json") { |
| + continue |
| + } |
| + names = append(names, strings.TrimSuffix(name, ".json")) |
| } |
| - pctx, cancel := context.WithTimeout(ctx, pipelineStoreTimeout) |
| - defer cancel() |
| - if pipe, err := release.GetPipeline(pctx, st, pub, acct, app); err != nil { |
| - f.PipelineErr = err.Error() |
| - } else { |
| - f.Pipeline = pipe |
| + sort.Strings(names) |
| + var out []frameChannel |
| + if len(names) > 0 { |
| + out = make([]frameChannel, len(names)) |
| } |
| - return f |
| + forEachLimit(len(names), readConcurrency, func(i int) { |
| + p, err := release.Channel(ctx, st, pub, acct, app, names[i]) |
| + if err != nil { |
| + out[i] = frameChannel{Name: names[i], Err: err.Error()} |
| + return |
| + } |
| + out[i] = frameChannel{Name: names[i], Pointer: p} |
| + }) |
| + return out, "" |
| } |
| type frameKey struct{ acct, app string } |
diff --git a/internal/console/hotreads.go b/internal/console/hotreads.go| new file mode 100644 |
| index 000000000..61aee5c42 |
| --- /dev/null |
| +++ b/internal/console/hotreads.go |
| @@ -0,0 +1,385 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// Concurrent reads for the slow GET routes (console-perf-hot-routes): the |
| +// CLI's instance list and system status, the account home, and the |
| +// operator's dashboard and Boxes. Each helper here makes the requests the |
| +// sequential code it replaces made, and gives the same answer in the same |
| +// order; only the waiting overlaps. Nothing is kept between requests. |
| + |
| +// readConcurrency bounds how many requests one fan-out has in flight. It |
| +// matches the AWS SDK's idle connections per host (10), so a fan-out reuses |
| +// warm connections rather than opening new ones. |
| +const readConcurrency = 10 |
| + |
| +// runConcurrently runs every fn at once and returns when all have. A panic |
| +// in one is raised again on the caller's goroutine once all have returned, |
| +// so it reaches the request's own recovery as it did when the calls ran in |
| +// sequence. |
| +func runConcurrently(fns ...func()) { |
| + forEachLimit(len(fns), len(fns), func(i int) { fns[i]() }) |
| +} |
| + |
| +// forEachLimit runs fn(i) for every i in [0, n), at most limit at a time, |
| +// and returns when all have. A panic is raised again as in runConcurrently. |
| +func forEachLimit(n, limit int, fn func(i int)) { |
| + if n <= 0 { |
| + return |
| + } |
| + if n == 1 { |
| + fn(0) |
| + return |
| + } |
| + limit = max(1, min(limit, n)) |
| + var ( |
| + next atomic.Int64 |
| + wg sync.WaitGroup |
| + panicked atomic.Pointer[any] |
| + ) |
| + for range limit { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + defer func() { |
| + if v := recover(); v != nil { |
| + panicked.CompareAndSwap(nil, &v) |
| + } |
| + }() |
| + for { |
| + i := int(next.Add(1) - 1) |
| + if i >= n { |
| + return |
| + } |
| + fn(i) |
| + } |
| + }() |
| + } |
| + wg.Wait() |
| + if v := panicked.Load(); v != nil { |
| + panic(*v) |
| + } |
| +} |
| + |
| +// errNoListMod is a prefetchStore's ListMod answer over a store that cannot |
| +// list modification times: the reader then falls back to List, as it does |
| +// when the store is not a release.ModLister at all. |
| +var errNoListMod = errors.New("console: the store cannot list modification times") |
| + |
| +// prefetchStore lets a reader whose reads follow from its listings alone |
| +// read concurrently without being rewritten. readConcurrently runs the |
| +// reader twice over it. The first pass is dry: its listings go to the |
| +// store and are kept, and each Get is noted and answered with dryBody, |
| +// which the reader accepts without a word. The second pass is the real |
| +// one: it gets the kept listings, and the noted keys are fetched ahead of |
| +// it, in the order the dry pass asked for them, while it runs. So it |
| +// decides on exactly the bytes it would have read itself. The reader keeps |
| +// every rule of its own (which keys it reads, its caps, how it judges a |
| +// body), so nothing is copied out of it. |
| +// |
| +// The bytes held are bounded, not only the requests: a fetched body holds |
| +// one of readConcurrency window slots until the real pass takes it, so at |
| +// most readConcurrency bodies are in flight or waiting at once. And no body |
| +// is read past limit(key)+1 bytes, the same cap the reader applies (a body |
| +// over it is cut there, still over the cap, and the reader refuses it as |
| +// it always did), so a box that writes huge reports costs the console at |
| +// most readConcurrency times the cap, however many it writes. |
| +type prefetchStore struct { |
| + release.Store |
| + dryBody []byte |
| + // limit is the most bytes the reader accepts for key, 0 for no limit. |
| + limit func(key string) int64 |
| + |
| + mu sync.Mutex |
| + dry bool |
| + lists map[string]listed |
| + mods map[string]listedMod |
| + asked []string |
| + pending map[string]*pendingGet |
| + window chan struct{} |
| + // held is the bytes fetched and not yet taken; stats its most, and the |
| + // largest body, for the tests. |
| + held int64 |
| + stats prefetchStats |
| +} |
| + |
| +// prefetchStats is what one concurrent read held: the most fetched bytes |
| +// at once, and the largest single body. |
| +type prefetchStats struct { |
| + Peak, Largest int64 |
| +} |
| + |
| +type listed struct { |
| + keys []string |
| + err error |
| +} |
| + |
| +type listedMod struct { |
| + mods []release.KeyMod |
| + err error |
| +} |
| + |
| +type fetched struct { |
| + body []byte |
| + etag string |
| + err error |
| +} |
| + |
| +// pendingGet is one key the dry pass named: whether its fetch has started, |
| +// whether the real pass has asked for it, and the fetch's result once done |
| +// is closed. |
| +type pendingGet struct { |
| + started, taken bool |
| + done chan struct{} |
| + f fetched |
| +} |
| + |
| +func (p *prefetchStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + p.mu.Lock() |
| + l, ok := p.lists[prefix] |
| + p.mu.Unlock() |
| + if !ok { |
| + keys, err := p.Store.List(ctx, prefix) |
| + l = listed{keys: keys, err: err} |
| + p.mu.Lock() |
| + p.lists[prefix] = l |
| + p.mu.Unlock() |
| + } |
| + return slices.Clone(l.keys), l.err |
| +} |
| + |
| +func (p *prefetchStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + p.mu.Lock() |
| + l, ok := p.mods[prefix] |
| + p.mu.Unlock() |
| + if !ok { |
| + if ml, can := p.Store.(release.ModLister); can { |
| + mods, err := ml.ListMod(ctx, prefix) |
| + l = listedMod{mods: mods, err: err} |
| + } else { |
| + l = listedMod{err: errNoListMod} |
| + } |
| + p.mu.Lock() |
| + p.mods[prefix] = l |
| + p.mu.Unlock() |
| + } |
| + return slices.Clone(l.mods), l.err |
| +} |
| + |
| +func (p *prefetchStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + p.mu.Lock() |
| + if p.dry { |
| + p.asked = append(p.asked, key) |
| + p.mu.Unlock() |
| + return slices.Clone(p.dryBody), "", nil |
| + } |
| + pg, ok := p.pending[key] |
| + if !ok || pg.taken { |
| + p.mu.Unlock() |
| + f := p.readOne(ctx, key) |
| + return f.body, f.etag, f.err |
| + } |
| + pg.taken = true |
| + started := pg.started |
| + p.mu.Unlock() |
| + if !started { |
| + // Asked before its turn: read it here (the fetcher skips it). |
| + f := p.readOne(ctx, key) |
| + return f.body, f.etag, f.err |
| + } |
| + <-pg.done |
| + p.mu.Lock() |
| + p.held -= int64(len(pg.f.body)) |
| + f := pg.f |
| + pg.f = fetched{} |
| + p.mu.Unlock() |
| + <-p.window |
| + return f.body, f.etag, f.err |
| +} |
| + |
| +// readOne reads key from the store, no further than its limit and one |
| +// byte: a body over the limit comes back cut at limit+1 bytes, which the |
| +// reader refuses as over its cap without the rest ever being held. |
| +func (p *prefetchStore) readOne(ctx context.Context, key string) fetched { |
| + rc, etag, err := release.OpenObject(ctx, p.Store, key) |
| + if errors.Is(err, errors.ErrUnsupported) { |
| + body, etag, err := p.Store.Get(ctx, key) |
| + return fetched{body: body, etag: etag, err: err} |
| + } |
| + if err != nil { |
| + return fetched{err: err} |
| + } |
| + defer rc.Close() |
| + var r io.Reader = rc |
| + if n := p.limitOf(key); n > 0 { |
| + r = io.LimitReader(rc, n+1) |
| + } |
| + body, err := io.ReadAll(r) |
| + if err != nil { |
| + return fetched{err: err} |
| + } |
| + return fetched{body: body, etag: etag} |
| +} |
| + |
| +func (p *prefetchStore) limitOf(key string) int64 { |
| + if p.limit == nil { |
| + return 0 |
| + } |
| + return p.limit(key) |
| +} |
| + |
| +// fetchAhead fetches keys in order, each into its pendingGet, holding a |
| +// window slot from the start of a fetch until the real pass takes the |
| +// body. It returns when stop is closed or every key has been started, and |
| +// done is closed once every fetch it started has finished. |
| +func (p *prefetchStore) fetchAhead(ctx context.Context, keys []string, stop <-chan struct{}, done chan<- struct{}, panicked *atomic.Pointer[any]) { |
| + var wg sync.WaitGroup |
| + defer func() { |
| + wg.Wait() |
| + close(done) |
| + }() |
| + for _, k := range keys { |
| + select { |
| + case p.window <- struct{}{}: |
| + case <-stop: |
| + return |
| + } |
| + p.mu.Lock() |
| + pg := p.pending[k] |
| + if pg.taken { |
| + p.mu.Unlock() |
| + <-p.window |
| + continue |
| + } |
| + pg.started = true |
| + p.mu.Unlock() |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + defer close(pg.done) |
| + defer func() { |
| + if v := recover(); v != nil { |
| + panicked.CompareAndSwap(nil, &v) |
| + pg.f = fetched{err: errMemoLoadPanicked} |
| + } |
| + }() |
| + f := p.readOne(ctx, k) |
| + p.mu.Lock() |
| + pg.f = f |
| + p.held += int64(len(f.body)) |
| + p.stats.Peak = max(p.stats.Peak, p.held) |
| + p.stats.Largest = max(p.stats.Largest, int64(len(f.body))) |
| + p.mu.Unlock() |
| + }() |
| + } |
| +} |
| + |
| +// readConcurrently is read(st), with the object reads read makes after its |
| +// listings made concurrently (prefetchStore), no body read past limit(key) |
| +// and one byte (limit nil, or 0 for a key, is no limit). read must decide |
| +// which keys to Get from its listings alone, never from a body it read, |
| +// and must take dryBody as a body it accepts silently; a key it asks for |
| +// in the real pass that the dry pass did not name is read when asked. |
| +func readConcurrently[T any](ctx context.Context, st release.Store, dryBody []byte, limit func(key string) int64, read func(release.Store) T) T { |
| + out, _ := readConcurrentlyStats(ctx, st, dryBody, limit, read) |
| + return out |
| +} |
| + |
| +// readConcurrentlyStats is readConcurrently, and what it held. |
| +func readConcurrentlyStats[T any](ctx context.Context, st release.Store, dryBody []byte, limit func(key string) int64, read func(release.Store) T) (T, prefetchStats) { |
| + p := &prefetchStore{Store: st, dryBody: dryBody, limit: limit, dry: true, |
| + lists: map[string]listed{}, mods: map[string]listedMod{}, pending: map[string]*pendingGet{}, |
| + window: make(chan struct{}, readConcurrency)} |
| + read(p) |
| + p.mu.Lock() |
| + p.dry = false |
| + var keys []string |
| + for _, k := range p.asked { |
| + if _, seen := p.pending[k]; !seen { |
| + p.pending[k] = &pendingGet{done: make(chan struct{})} |
| + keys = append(keys, k) |
| + } |
| + } |
| + p.mu.Unlock() |
| + stop, fetchDone := make(chan struct{}), make(chan struct{}) |
| + var panicked atomic.Pointer[any] |
| + go p.fetchAhead(ctx, keys, stop, fetchDone, &panicked) |
| + out := func() T { |
| + defer func() { |
| + // Start nothing more, and wait for every fetch started, so |
| + // nothing this read began outlives it. |
| + close(stop) |
| + <-fetchDone |
| + }() |
| + return read(p) |
| + }() |
| + if v := panicked.Load(); v != nil { |
| + panic(*v) |
| + } |
| + p.mu.Lock() |
| + stats := p.stats |
| + p.mu.Unlock() |
| + return out, stats |
| +} |
| + |
| +// boxReportCap is the largest box report status.LoadBoxesComplete accepts |
| +// (status's maxFleetBoxBodyBytes): a customer fleet's boxes write their own |
| +// reports, so a prefetch reads none of them past it and one byte. |
| +// TestBoxReportCapIsStatusCap holds the two equal. |
| +const boxReportCap = 1 << 20 |
| + |
| +// boxReportLimit limits every key a box-report load reads to boxReportCap. |
| +func boxReportLimit(string) int64 { return boxReportCap } |
| + |
| +// boxReportKeyLimit limits only the box reports among a reader's keys, for |
| +// a reader that also reads other objects (the edge-address fold). |
| +func boxReportKeyLimit(key string) int64 { |
| + if strings.HasPrefix(key, "status/boxes/") { |
| + return boxReportCap |
| + } |
| + return 0 |
| +} |
| + |
| +// loadBoxesConcurrently is status.LoadBoxesComplete on st with the box |
| +// reports read concurrently: the same listing, the same reports, the same |
| +// skips and the same completeness. "{}" decodes to an empty report, which |
| +// LoadBoxesComplete keeps without logging. |
| +func loadBoxesConcurrently(ctx context.Context, st release.Store) ([]status.Box, bool, error) { |
| + type out struct { |
| + boxes []status.Box |
| + complete bool |
| + err error |
| + } |
| + o := readConcurrently(ctx, st, []byte("{}"), boxReportLimit, func(s release.Store) out { |
| + b, c, err := status.LoadBoxesComplete(ctx, s) |
| + return out{b, c, err} |
| + }) |
| + return o.boxes, o.complete, o.err |
| +} |
| + |
| +// readEdgesSnapshotConcurrently is readEdgesSnapshot with the edges files |
| +// read concurrently: the same listing, files and skips. The dry body is |
| +// the smallest versioned edges file, which the snapshot keeps without |
| +// logging. |
| +func readEdgesSnapshotConcurrently(ctx context.Context, st release.Store) (edgesSnapshot, error) { |
| + type out struct { |
| + snap edgesSnapshot |
| + err error |
| + } |
| + o := readConcurrently(ctx, st, []byte(`{"v":1,"box":"-"}`), nil, func(s release.Store) out { |
| + snap, err := readEdgesSnapshot(ctx, s) |
| + return out{snap, err} |
| + }) |
| + return o.snap, o.err |
| +} |
diff --git a/internal/console/hotreads_test.go b/internal/console/hotreads_test.go| new file mode 100644 |
| index 000000000..b5edfc621 |
| --- /dev/null |
| +++ b/internal/console/hotreads_test.go |
| @@ -0,0 +1,361 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The concurrent readers of hotreads.go and lifetimes_read.go against the |
| +// sequential readers they stand in for, over the perf fixture's real store |
| +// (the S3 client over the fake): the same answer, and the same requests. |
| + |
| +// TestListRecordsCompleteMatchesProvision: the console's concurrent record |
| +// listing answers what provision.ListRecordsCompleteJudged answers, judged |
| +// and unjudged, capped and not, over a valid record, one its slot no longer |
| +// vouches for, a tombstone, a corrupt body and a malformed slot, and makes |
| +// the same number of requests. |
| +func TestListRecordsCompleteMatchesProvision(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + ctx := context.Background() |
| + st, acct, app := fx.srv.cfg.Releases, fx.sqid, "kass" |
| + now := time.Now() |
| + put := func(key string, v any) { |
| + t.Helper() |
| + body, ok := v.([]byte) |
| + if !ok { |
| + var err error |
| + if body, err = json.Marshal(v); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if _, err := fx.rel.Put(ctx, key, body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + rec := func(host string) provision.Record { |
| + return provision.Record{Schema: 1, Host: host, Slug: strings.Split(host, ".")[0], App: app, Account: acct, |
| + Channel: "stable", Region: "ie", CreatedAt: now, CreatedBy: "paul@keymail.dev"} |
| + } |
| + for i := range 3 { |
| + put(provision.RecordKey(acct, app, fmt.Sprintf("ok%d.example.com", i)), rec(fmt.Sprintf("ok%d.example.com", i))) |
| + } |
| + // Another app holds this host's slot: the record is stale. |
| + put(provision.RecordKey(acct, app, "stale.example.com"), rec("stale.example.com")) |
| + put(provision.HostIncarnationKey("stale.example.com"), |
| + provision.HostIncarnation{Incarnation: 1, State: provision.SlotLive, Account: acct, App: "other"}) |
| + // A tombstone. |
| + gone := rec("gone.example.com") |
| + gone.Retired = true |
| + put(provision.RecordKey(acct, app, "gone.example.com"), gone) |
| + // A body that will not decode, and a slot that will not. |
| + put(provision.RecordKey(acct, app, "corrupt.example.com"), []byte("{not json")) |
| + put(provision.RecordKey(acct, app, "badslot.example.com"), rec("badslot.example.com")) |
| + put(provision.HostIncarnationKey("badslot.example.com"), []byte("{not json")) |
| + |
| + type answer struct { |
| + Hosts []string |
| + Truncated bool |
| + Skipped []string |
| + } |
| + hostsOf := func(recs []provision.Record) []string { |
| + var out []string |
| + for _, r := range recs { |
| + out = append(out, r.Host) |
| + } |
| + return out |
| + } |
| + for _, judged := range []bool{false, true} { |
| + for _, max := range []int{instanceListMax, 4, 0} { |
| + t.Run(fmt.Sprintf("judged=%v/max=%d", judged, max), func(t *testing.T) { |
| + var j *provision.LifetimeJudge |
| + jctx := ctx |
| + if judged { |
| + j = provision.NewLifetimeJudge() |
| + jctx = provision.WithLifetimes(ctx, j) |
| + } |
| + s0, _ := lat.Calls() |
| + wantRecs, wantTrunc, wantSkipped, err := provision.ListRecordsCompleteJudged(ctx, st, j, acct, app, max) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s1, _ := lat.Calls() |
| + gotRecs, gotTrunc, gotSkipped, err := fx.srv.listRecordsComplete(jctx, acct, app, max) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s2, _ := lat.Calls() |
| + want := answer{hostsOf(wantRecs), wantTrunc, wantSkipped} |
| + got := answer{hostsOf(gotRecs), gotTrunc, gotSkipped} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Errorf("console listing = %+v, provision = %+v", got, want) |
| + } |
| + if !reflect.DeepEqual(gotRecs, wantRecs) { |
| + t.Errorf("records differ:\nconsole %+v\nprovision %+v", gotRecs, wantRecs) |
| + } |
| + if s2-s1 != s1-s0 { |
| + t.Errorf("console listing made %d S3 requests, provision %d", s2-s1, s1-s0) |
| + } |
| + // The fixture's cases are live: judged, the stale record and |
| + // the tombstone are dropped and the corrupt body and the |
| + // malformed slot skipped; unjudged, the tombstone and the |
| + // corrupt body are skipped. |
| + live := []string{"corrupt.example.com", "gone.example.com"} |
| + if judged { |
| + live = []string{"badslot.example.com", "corrupt.example.com"} |
| + } |
| + if max == instanceListMax && !reflect.DeepEqual(want.Skipped, live) { |
| + t.Errorf("provision skipped %v, want %v: the fixture no longer tests what it says", want.Skipped, live) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// putBoxReport writes a raw body as a box report, past status.WriteBox's |
| +// own checks, as a misbehaving box could. |
| +func putBoxReport(t *testing.T, fx *consoleFixture, key string, body []byte) { |
| + t.Helper() |
| + if _, err := fx.rel.Put(context.Background(), key, body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestLoadBoxesConcurrentlyMatchesStatus: loadBoxesConcurrently answers |
| +// what status.LoadBoxesComplete answers (the reports, their order and the |
| +// completeness) with the same number of requests, on the platform prefix |
| +// (two listing pages, gone reports past the horizon) and a fleet's, with a |
| +// corrupt and an oversized report among them. |
| +func TestLoadBoxesConcurrentlyMatchesStatus(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + ctx := context.Background() |
| + putBoxReport(t, fx, "status/boxes/zz-corrupt.json", []byte("{not json")) |
| + putBoxReport(t, fx, "status/boxes/zz-huge.json", []byte(`{"label":"zz-huge","name":"`+strings.Repeat("x", 1<<20)+`"}`)) |
| + for _, prefix := range []string{"", "fleets/fleet-a/"} { |
| + t.Run("prefix="+prefix, func(t *testing.T) { |
| + var st release.Store = fx.srv.cfg.Releases |
| + if prefix != "" { |
| + st = release.NewPrefixStore(st, prefix) |
| + } |
| + s0, _ := lat.Calls() |
| + want, wantComplete, wantErr := status.LoadBoxesComplete(ctx, st) |
| + s1, _ := lat.Calls() |
| + got, gotComplete, gotErr := loadBoxesConcurrently(ctx, st) |
| + s2, _ := lat.Calls() |
| + if !reflect.DeepEqual(got, want) || gotComplete != wantComplete || (gotErr == nil) != (wantErr == nil) { |
| + t.Errorf("concurrent = %d boxes, complete %v, err %v; status = %d boxes, complete %v, err %v", |
| + len(got), gotComplete, gotErr, len(want), wantComplete, wantErr) |
| + } |
| + if s2-s1 != s1-s0 { |
| + t.Errorf("concurrent load made %d S3 requests, status %d", s2-s1, s1-s0) |
| + } |
| + if len(want) == 0 { |
| + t.Error("the fixture has no box report here: it tests nothing") |
| + } |
| + if prefix == "" && wantComplete { |
| + t.Error("the corrupt and oversized reports should make the platform's read incomplete") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestEdgesReadsConcurrentlyMatch: the edges snapshot and the edge address |
| +// fold, read concurrently, answer what their sequential readers answer, |
| +// with the same number of requests. |
| +func TestEdgesReadsConcurrentlyMatch(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + ctx := context.Background() |
| + if _, err := fx.rel.Put(ctx, "control/edges/zz-unversioned.json", []byte(`{"box":"zz"}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + st := fx.srv.cfg.Releases |
| + s0, _ := lat.Calls() |
| + want, wantErr := readEdgesSnapshot(ctx, st) |
| + s1, _ := lat.Calls() |
| + got, gotErr := readEdgesSnapshotConcurrently(ctx, st) |
| + s2, _ := lat.Calls() |
| + if !reflect.DeepEqual(got, want) || (gotErr == nil) != (wantErr == nil) { |
| + t.Errorf("edges snapshot: concurrent = %+v (%v), sequential = %+v (%v)", got, gotErr, want, wantErr) |
| + } |
| + if s2-s1 != s1-s0 { |
| + t.Errorf("edges snapshot: concurrent read made %d S3 requests, sequential %d", s2-s1, s1-s0) |
| + } |
| + if len(want.Files) < len(perfFlagshipBoxes) || want.Complete { |
| + t.Errorf("edges snapshot: %d files, complete %v; want every seeded box and incomplete for the unversioned file", len(want.Files), want.Complete) |
| + } |
| + |
| + now := time.Now() |
| + s0, _ = lat.Calls() |
| + wantIPs := edgesfile.EdgeIPs(ctx, st, nil, now) |
| + s1, _ = lat.Calls() |
| + gotIPs := fx.srv.realFoldEdgeIPs(ctx) |
| + s2, _ = lat.Calls() |
| + wantSorted := slices.Sorted(slices.Values(wantIPs)) |
| + if !reflect.DeepEqual(gotIPs, wantSorted) || len(wantIPs) == 0 { |
| + t.Errorf("edge fold: concurrent = %v, sequential = %v (want at least one address)", gotIPs, wantSorted) |
| + } |
| + if s2-s1 != s1-s0 { |
| + t.Errorf("edge fold: concurrent read made %d S3 requests, sequential %d", s2-s1, s1-s0) |
| + } |
| +} |
| + |
| +// TestForEachLimitRaisesAPanicOnTheCaller: a panic in one task reaches the |
| +// caller once the workers have returned, as it would have in sequence. |
| +func TestForEachLimitRaisesAPanicOnTheCaller(t *testing.T) { |
| + var ran atomic.Int32 |
| + func() { |
| + defer func() { |
| + if v := recover(); v != "task 7" { |
| + t.Errorf("recovered %v, want the task's panic", v) |
| + } |
| + }() |
| + forEachLimit(20, 4, func(i int) { |
| + ran.Add(1) |
| + if i == 7 { |
| + panic("task 7") |
| + } |
| + }) |
| + }() |
| + if ran.Load() < 8 { |
| + t.Errorf("%d tasks ran, want task 7 and those before it at least", ran.Load()) |
| + } |
| +} |
| + |
| +// boxReportOfSize is a box report body of exactly n bytes that decodes. |
| +func boxReportOfSize(t *testing.T, label string, n int) []byte { |
| + t.Helper() |
| + head, tail := `{"label":"`+label+`","name":"`, `"}` |
| + pad := n - len(head) - len(tail) |
| + if pad < 0 { |
| + t.Fatalf("a report of %d bytes is too small to build", n) |
| + } |
| + return []byte(head + strings.Repeat("x", pad) + tail) |
| +} |
| + |
| +// TestBoxReportCapIsStatusCap: the prefetch's cut (boxReportCap) is the |
| +// size status.LoadBoxesComplete refuses past, so cutting a body there and |
| +// one byte over never changes what the reader decides. |
| +func TestBoxReportCapIsStatusCap(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, _ := newPerfFixture(t) |
| + ctx := context.Background() |
| + for _, c := range []struct { |
| + size int |
| + complete bool |
| + }{{boxReportCap, true}, {boxReportCap + 1, false}} { |
| + prefix := fmt.Sprintf("fleets/cap-%d/", c.size) |
| + putBoxReport(t, fx, prefix+"status/boxes/b.json", boxReportOfSize(t, "b", c.size)) |
| + st := release.NewPrefixStore(fx.srv.cfg.Releases, prefix) |
| + boxes, complete, err := status.LoadBoxesComplete(ctx, st) |
| + if err != nil || complete != c.complete || (len(boxes) == 1) != c.complete { |
| + t.Errorf("a %d-byte report: %d boxes, complete %v, err %v; want accepted %v (status's cap moved: move boxReportCap with it)", |
| + c.size, len(boxes), complete, err, c.complete) |
| + } |
| + got, gotComplete, _ := loadBoxesConcurrently(ctx, st) |
| + if !reflect.DeepEqual(got, boxes) || gotComplete != complete { |
| + t.Errorf("a %d-byte report: the concurrent load answered %d boxes, complete %v; status %d, %v", c.size, len(got), gotComplete, len(boxes), complete) |
| + } |
| + } |
| +} |
| + |
| +// TestBoxLoadHoldsBoundedBytes: a fleet whose boxes write many oversized |
| +// reports (a customer fleet writes its own prefix) costs the concurrent |
| +// load at most readConcurrency bodies cut at the cap and one byte, never |
| +// the reports themselves; the answer is status's, incomplete. |
| +func TestBoxLoadHoldsBoundedBytes(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + ctx := context.Background() |
| + const prefix, huge, many = "fleets/flood/", 2 * boxReportCap, 3 * readConcurrency |
| + for i := range many { |
| + putBoxReport(t, fx, fmt.Sprintf("%sstatus/boxes/huge-%02d.json", prefix, i), boxReportOfSize(t, "huge", huge)) |
| + } |
| + putBoxReport(t, fx, prefix+"status/boxes/ok.json", boxReportOfSize(t, "ok", 200)) |
| + st := release.NewPrefixStore(fx.srv.cfg.Releases, prefix) |
| + s0, _ := lat.Calls() |
| + want, wantComplete, wantErr := status.LoadBoxesComplete(ctx, st) |
| + s1, _ := lat.Calls() |
| + type out struct { |
| + boxes []status.Box |
| + complete bool |
| + err error |
| + } |
| + got, held := readConcurrentlyStats(ctx, st, []byte("{}"), boxReportLimit, func(s release.Store) out { |
| + b, c, err := status.LoadBoxesComplete(ctx, s) |
| + return out{b, c, err} |
| + }) |
| + s2, _ := lat.Calls() |
| + if wantErr != nil || got.err != nil || wantComplete || got.complete || len(want) != 1 || !reflect.DeepEqual(got.boxes, want) { |
| + t.Errorf("concurrent = %d boxes, complete %v, err %v; status = %d boxes, complete %v, err %v; want the one small report, incomplete", |
| + len(got.boxes), got.complete, got.err, len(want), wantComplete, wantErr) |
| + } |
| + if bound := int64(readConcurrency) * (boxReportCap + 1); held.Peak > bound { |
| + t.Errorf("the load held %d bytes at once, over %d (%d bodies cut at the cap and one byte)", held.Peak, bound, readConcurrency) |
| + } |
| + if held.Largest > boxReportCap+1 { |
| + t.Errorf("the load held a %d-byte body: an oversized report past the cap and one byte", held.Largest) |
| + } |
| + if s2-s1 != s1-s0 { |
| + t.Errorf("concurrent load made %d S3 requests, status %d", s2-s1, s1-s0) |
| + } |
| +} |
| + |
| +// TestPageBoxReportsTakesNoMemoReadFromBeforeAnInvalidation: a request |
| +// whose own read of the box reports finished before an invalidation (a |
| +// record deletion) does not hand that read to the page views' cache: the |
| +// cache loads afresh and sees what changed. Without an invalidation the |
| +// request's read is held and nothing is read again. |
| +func TestPageBoxReportsTakesNoMemoReadFromBeforeAnInvalidation(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + s := fx.srv |
| + labels := func(boxes []status.Box) []string { |
| + var out []string |
| + for _, b := range boxes { |
| + out = append(out, b.Label) |
| + } |
| + return out |
| + } |
| + |
| + ctx := withReqMemo(context.Background()) |
| + s.boxReports.invalidate() |
| + if _, _, err := s.loadBoxes(ctx, s.cfg.Releases, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + s0, _ := lat.Calls() |
| + s.pageBoxReports(ctx) |
| + if s1, _ := lat.Calls(); s1 != s0 { |
| + t.Errorf("no invalidation: the page views' cache read %d more requests, want the request's own read held", s1-s0) |
| + } |
| + |
| + ctx = withReqMemo(context.Background()) |
| + s.boxReports.invalidate() |
| + if _, _, err := s.loadBoxes(ctx, s.cfg.Releases, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := status.WriteBox(context.Background(), fx.rel, status.Box{GeneratedAt: time.Now(), Label: "box-new", Region: "eu-west-1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.boxReports.invalidate() |
| + boxes, _ := s.pageBoxReports(ctx) |
| + if !slices.Contains(labels(boxes), "box-new") { |
| + t.Errorf("after an invalidation the page views' cache holds %v, want a fresh read with box-new", labels(boxes)) |
| + } |
| + if again, _ := s.pageBoxReports(context.Background()); !slices.Contains(labels(again), "box-new") { |
| + t.Errorf("the cache then holds %v, want box-new", labels(again)) |
| + } |
| +} |
diff --git a/internal/console/instancesplacement.go b/internal/console/instancesplacement.go| index 30898f3d8..74e714648 100644 |
| --- a/internal/console/instancesplacement.go |
| +++ b/internal/console/instancesplacement.go |
| @@ -47,7 +47,7 @@ type edgesFilePlacementView = edgesfile.PlacementView |
| // all, the same shape filter the other readers apply. |
| func loadEdgesJoin(ctx context.Context, s release.Store) map[string][]servedBy { |
| out := map[string][]servedBy{} |
| - for _, f := range readEdgesFiles(ctx, s) { |
| + for _, f := range readEdgesFilesWith(ctx, s, readEdgesSnapshotConcurrently) { |
| for host := range f.Hosts { |
| out[host] = append(out[host], servedBy{Box: f.Box, Region: f.Region}) |
| } |
| @@ -64,10 +64,16 @@ func loadEdgesJoin(ctx context.Context, s release.Store) map[string][]servedBy { |
| // their pre-#337/#329 behaviour rather than failing the request. It is |
| // readEdgesSnapshot with the listing error folded into that empty answer. |
| func readEdgesFiles(ctx context.Context, s release.Store) []edgesFilePlacementView { |
| + return readEdgesFilesWith(ctx, s, readEdgesSnapshot) |
| +} |
| + |
| +// readEdgesFilesWith is readEdgesFiles over read, readEdgesSnapshot or its |
| +// concurrent twin (loadEdgesJoin's, hotreads.go). |
| +func readEdgesFilesWith(ctx context.Context, s release.Store, read func(context.Context, release.Store) (edgesSnapshot, error)) []edgesFilePlacementView { |
| if s == nil { |
| return nil |
| } |
| - snap, err := readEdgesSnapshot(ctx, s) |
| + snap, err := read(ctx, s) |
| if err != nil { |
| log.Printf("console: api instances: could not list %s for the placement join: %v", edgesFilePrefix, err) |
| return nil |
diff --git a/internal/console/lifetimes_read.go b/internal/console/lifetimes_read.go| index 8b62d57d6..dab2a88f6 100644 |
| --- a/internal/console/lifetimes_read.go |
| +++ b/internal/console/lifetimes_read.go |
| @@ -30,9 +30,11 @@ func (s *Server) observeRecord(ctx context.Context, acct, app, host string) prov |
| return provision.JudgeFrom(ctx).Observe(ctx, s.cfg.Releases, acct, app, host) |
| } |
| -// listRecords is ListRecords under the context's judge. |
| +// listRecords is ListRecords under the context's judge, read as |
| +// listRecordsComplete reads. |
| func (s *Server) listRecords(ctx context.Context, acct, app string, max int) ([]provision.Record, bool, error) { |
| - return provision.ListRecordsJudged(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct, app, max) |
| + recs, truncated, _, err := s.listRecordsComplete(ctx, acct, app, max) |
| + return recs, truncated, err |
| } |
| // listRecordsStrict is ListRecordsStrict under the context's judge. |
| @@ -40,9 +42,61 @@ func (s *Server) listRecordsStrict(ctx context.Context, acct, app string, max in |
| return provision.ListRecordsStrictJudged(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct, app, max) |
| } |
| -// listRecordsComplete is ListRecordsComplete under the context's judge. |
| +// listRecordsComplete is provision.ListRecordsCompleteJudged under the |
| +// context's judge, with each host read on its own, readConcurrency hosts at |
| +// a time: the same listing, the same reads (a host's record, then under a |
| +// judge its slot, in that order, as Observe makes them), and the same |
| +// records, truncation and skipped hosts in the same order. |
| +// TestListRecordsCompleteMatchesProvision holds the two together. |
| func (s *Server) listRecordsComplete(ctx context.Context, acct, app string, max int) ([]provision.Record, bool, []string, error) { |
| - return provision.ListRecordsCompleteJudged(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct, app, max) |
| + st, j := s.cfg.Releases, provision.JudgeFrom(ctx) |
| + if max < 0 { |
| + max = 0 |
| + } |
| + hosts, err := provision.ListRecordHosts(ctx, st, acct, app) |
| + if err != nil { |
| + return nil, false, nil, err |
| + } |
| + truncated := len(hosts) > max |
| + if truncated { |
| + hosts = hosts[:max] |
| + } |
| + type read struct { |
| + rec *provision.Record |
| + drop bool // a stale body: left out without a word |
| + } |
| + reads := make([]read, len(hosts)) |
| + forEachLimit(len(hosts), readConcurrency, func(i int) { |
| + host := hosts[i] |
| + if j == nil { |
| + // ListRecordsComplete's read: any error skips the host. |
| + if rec, _, err := provision.ReadRecordJudged(ctx, st, nil, acct, app, host); err == nil { |
| + reads[i].rec = rec |
| + } |
| + return |
| + } |
| + obs := j.Observe(ctx, st, acct, app, host) |
| + switch { |
| + case obs.Present && obs.Verdict == provision.LifetimeStale: |
| + reads[i].drop = true |
| + case obs.Verdict == provision.LifetimeUnreadable || obs.Verdict == provision.LifetimeCorrupt: |
| + case !obs.Present || obs.Rec == nil || obs.Rec.Retired: |
| + default: |
| + reads[i].rec = obs.Rec |
| + } |
| + }) |
| + var recs []provision.Record |
| + var skipped []string |
| + for i, r := range reads { |
| + switch { |
| + case r.drop: |
| + case r.rec == nil: |
| + skipped = append(skipped, hosts[i]) |
| + default: |
| + recs = append(recs, *r.rec) |
| + } |
| + } |
| + return recs, truncated, skipped, nil |
| } |
| // listAllRecordsStrict is ListAllRecordsStrict under the context's judge. |
diff --git a/internal/console/opboxes.go b/internal/console/opboxes.go| index 93817c3bf..e781de29e 100644 |
| --- a/internal/console/opboxes.go |
| +++ b/internal/console/opboxes.go |
| @@ -42,7 +42,7 @@ func (s *Server) opHostRows(ctx context.Context, p *page) (rows []HostRow, compl |
| if s.cfg.Releases == nil { |
| return nil, true, nil |
| } |
| - boxes, complete, err := status.LoadBoxesComplete(ctx, s.cfg.Releases) |
| + boxes, complete, err := loadBoxesConcurrently(ctx, s.cfg.Releases) |
| if err != nil { |
| return nil, false, err |
| } |
| @@ -75,9 +75,28 @@ func (s *Server) handleBoxes(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx := r.Context() |
| p := s.opPage(addr, raw, "boxes") |
| - f, err := s.opFleetJSON(ctx, &p) |
| - if err != nil { |
| - log.Printf("console: fleet view: %v", err) |
| + // The page's three bucket reads are independent and run at once: |
| + // status/fleet.json, the box reports, and (for a store operator) the |
| + // storage queue. Operator pages are seldom viewed and keep no cache. |
| + var ( |
| + f *status.Fleet |
| + fleetErr, hostsErr error |
| + hosts []HostRow |
| + complete bool |
| + storeN *int |
| + storeErr error |
| + ) |
| + runConcurrently( |
| + func() { f, fleetErr = s.opFleetJSON(ctx, &p) }, |
| + func() { hosts, complete, hostsErr = s.opHostRows(ctx, &p) }, |
| + func() { |
| + if p.Op.StoreOperator { |
| + storeN, storeErr = s.opStorePending(ctx, &p) |
| + } |
| + }, |
| + ) |
| + if fleetErr != nil { |
| + log.Printf("console: fleet view: %v", fleetErr) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read fleet status. Please try again.") |
| return |
| } |
| @@ -87,7 +106,7 @@ func (s *Server) handleBoxes(w http.ResponseWriter, r *http.Request) { |
| // rather than turning a readable page into a 500. It says so (OPS-154) |
| // where the Hosts table would be. A report that could not be read says |
| // so too, above the rows that were. |
| - hosts, complete, err := s.opHostRows(ctx, &p) |
| + err := hostsErr |
| switch { |
| case err != nil: |
| log.Printf("console: fleet hosts: %v", err) |
| @@ -122,11 +141,10 @@ func (s *Server) handleBoxes(w http.ResponseWriter, r *http.Request) { |
| } |
| p.Fleet, p.Hosts, p.BoxRegions, p.FleetAppRegions = f, hosts, labels, appRegions |
| if p.Op.StoreOperator { |
| - n, err := s.opStorePending(ctx, &p) |
| - if err != nil { |
| - log.Printf("console: boxes storage queue: %v", err) |
| + if storeErr != nil { |
| + log.Printf("console: boxes storage queue: %v", storeErr) |
| } |
| - p.StorePending, p.StoreQueueUnknown = n, n == nil |
| + p.StorePending, p.StoreQueueUnknown = storeN, storeN == nil |
| } |
| p.Jobs = opJobRows(s.jobs.Snapshot()) |
| s.render(w, http.StatusOK, "ops_boxes", p) |
diff --git a/internal/console/opdashboard.go b/internal/console/opdashboard.go| index 11d998c14..49703b9c4 100644 |
| --- a/internal/console/opdashboard.go |
| +++ b/internal/console/opdashboard.go |
| @@ -377,13 +377,27 @@ func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { |
| d.Activity = feed |
| } |
| - f, fleetErr := s.opFleetJSON(ctx, &p) |
| + // The dashboard's three bucket reads are independent and run at once: |
| + // status/fleet.json, the box reports and the storage queue. Operator |
| + // pages are seldom viewed and keep no cache. |
| + var ( |
| + f *status.Fleet |
| + fleetErr, hostsErr error |
| + hosts []HostRow |
| + complete bool |
| + pending *int |
| + pendingErr error |
| + ) |
| + runConcurrently( |
| + func() { f, fleetErr = s.opFleetJSON(ctx, &p) }, |
| + func() { hosts, complete, hostsErr = s.opHostRows(ctx, &p) }, |
| + func() { pending, pendingErr = s.opStorePending(ctx, &p) }, |
| + ) |
| if fleetErr != nil { |
| log.Printf("console: dashboard fleet view: %v", fleetErr) |
| f = nil |
| } |
| d.HasFleet = f != nil |
| - hosts, complete, hostsErr := s.opHostRows(ctx, &p) |
| if hostsErr != nil { |
| log.Printf("console: dashboard fleet hosts: %v", hostsErr) |
| d.HostsUnread = opHostsUnread |
| @@ -399,9 +413,8 @@ func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { |
| d.Boxes[i].Region = name |
| } |
| } |
| - pending, err := s.opStorePending(ctx, &p) |
| - if err != nil { |
| - log.Printf("console: dashboard storage queue: %v", err) |
| + if pendingErr != nil { |
| + log.Printf("console: dashboard storage queue: %v", pendingErr) |
| } |
| alerts, known := s.alertsNow.Firing() |
| jobs := s.jobs.Snapshot() |
diff --git a/internal/console/perfbudgets_test.go b/internal/console/perfbudgets_test.go| index abf882d37..52f6c360f 100644 |
| --- a/internal/console/perfbudgets_test.go |
| +++ b/internal/console/perfbudgets_test.go |
| @@ -133,9 +133,17 @@ func loadPerfBudgets(t testing.TB) map[string]perfRecord { |
| return recs |
| } |
| +// perfCLIScreens are the CLI JSON doors the walk requests, with the CLI's |
| +// bearer token: the ones flagship's speed table put among the slowest |
| +// GETs (console-perf-hot-routes). Every other door under /api/ is left out. |
| +var perfCLIScreens = map[string]bool{ |
| + "GET /api/cli/apps/{account}/{app}/instances": true, |
| + "GET /api/cli/system/status": true, |
| +} |
| + |
| // perfInventory is the screens the walk can request: every registered route |
| // that answers GET (pattern "GET /x" or method-less "/x"), minus the CLI JSON |
| -// doors under /api/ and /healthz. Sorted. |
| +// doors under /api/ other than perfCLIScreens, and /healthz. Sorted. |
| func perfInventory(entries []claimEntry) []string { |
| var out []string |
| for _, e := range entries { |
| @@ -143,7 +151,7 @@ func perfInventory(entries []claimEntry) []string { |
| continue |
| } |
| path, _ := perfScreenPath(e.Pattern) |
| - if path == "/api" || strings.HasPrefix(path, "/api/") || path == "/healthz" { |
| + if (path == "/api" || strings.HasPrefix(path, "/api/")) && !perfCLIScreens[e.Pattern] || path == "/healthz" { |
| continue |
| } |
| out = append(out, e.Pattern) |
| @@ -235,10 +243,11 @@ func TestPerfInventoryIncludesMethodlessScreens(t *testing.T) { |
| {Kind: "route", Pattern: "POST /b"}, |
| {Kind: "route", Pattern: "/api/economics/bill"}, |
| {Kind: "route", Pattern: "GET /api/cli/x"}, |
| + {Kind: "route", Pattern: "GET /api/cli/system/status"}, |
| {Kind: "route", Pattern: "GET /healthz"}, |
| {Kind: "worker", Pattern: "StartX"}, |
| }) |
| - want := []string{"/fleet/architecture", "GET /a"} |
| + want := []string{"/fleet/architecture", "GET /a", "GET /api/cli/system/status"} |
| if strings.Join(got, "|") != strings.Join(want, "|") { |
| t.Fatalf("got %q, want %q", got, want) |
| } |
| @@ -253,7 +262,7 @@ func TestPerfInventoryOfTheRealConsole(t *testing.T) { |
| if strings.HasPrefix(s, "POST ") { |
| t.Errorf("inventory holds %q", s) |
| } |
| - if p, _ := perfScreenPath(s); p == "/api" || strings.HasPrefix(p, "/api/") { |
| + if p, _ := perfScreenPath(s); (p == "/api" || strings.HasPrefix(p, "/api/")) && !perfCLIScreens[s] { |
| t.Errorf("inventory holds %q", s) |
| } |
| } |
| @@ -262,6 +271,8 @@ func TestPerfInventoryOfTheRealConsole(t *testing.T) { |
| "GET /a/{sqid}/apps/{app}/settings/{section}", |
| "/fleet/architecture", |
| "GET /fleet/metrics", |
| + "GET /api/cli/apps/{account}/{app}/instances", |
| + "GET /api/cli/system/status", |
| } { |
| if !have[want] { |
| t.Errorf("inventory lacks %q", want) |
diff --git a/internal/console/perfhotroutes_test.go b/internal/console/perfhotroutes_test.go| new file mode 100644 |
| index 000000000..733e78136 |
| --- /dev/null |
| +++ b/internal/console/perfhotroutes_test.go |
| @@ -0,0 +1,324 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "maps" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The hot routes (console-perf-hot-routes): the console GETs flagship's |
| +// speed table put slowest, measured over a fixture shaped like flagship. |
| + |
| +// perfFlagshipApp is the walk's app with many instances, placed across |
| +// three regions; perfFlagshipInstances is how many. |
| +const ( |
| + perfFlagshipApp = "shopfront" |
| + perfFlagshipInstances = 30 |
| +) |
| + |
| +// perfFlagshipBoxes are the boxes perfSeedFlagship adds: two regions |
| +// beyond the base seeds' eu-west-1, each box with an edges file, a fresh |
| +// report carrying metrics and the system channel, and the instance hosts |
| +// it serves. |
| +var perfFlagshipBoxes = []struct{ label, aws, code string }{ |
| + {"box-c", "eu-west-1", "ie"}, |
| + {"box-d", "eu-west-2", "uk"}, |
| + {"box-e", "eu-west-2", "uk"}, |
| + {"box-f", "us-east-1", "us"}, |
| +} |
| + |
| +// perfSeedFlagship adds the shape flagship has and the base seeds lack: |
| +// boxes in three regions, an account with several apps, one of them with |
| +// perfFlagshipInstances instances spread over the regions, and the stable |
| +// system pointer with a bootstrap binary for `carlos system status`. |
| +// Everything is written straight into fx.rel, so none of it is counted. |
| +func perfSeedFlagship(t *testing.T, fx *consoleFixture) { |
| + t.Helper() |
| + ctx := context.Background() |
| + now := time.Now() |
| + acct := fx.sqid |
| + |
| + // Two more apps beside kass, each with a release on stable, and the |
| + // many-instance app with instances enabled. |
| + for _, app := range []string{perfFlagshipApp, "blog", "docs"} { |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, app, "paul@keymail.dev", now.Add(-time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + shipVersion(t, fx, app, "v1") |
| + seedChannel(t, fx, app, "stable", "v1") |
| + } |
| + enableInstances(t, fx, perfFlagshipApp, provision.Manifest{Schema: 1, App: perfFlagshipApp, |
| + Domain: "shopfront.example.com", Channel: "stable", Regions: []string{"ie", "uk", "us"}}) |
| + |
| + codes := []string{"ie", "uk", "us"} |
| + hostsBy := map[string][]string{} // region code -> hosts |
| + for i := 0; i < perfFlagshipInstances; i++ { |
| + host := fmt.Sprintf("s%02d.shopfront.example.com", i) |
| + code := codes[i%len(codes)] |
| + hostsBy[code] = append(hostsBy[code], host) |
| + rec := provision.Record{Schema: 1, Host: host, Slug: fmt.Sprintf("s%02d", i), App: perfFlagshipApp, Account: acct, |
| + Channel: "stable", Region: code, CreatedAt: now.Add(-2 * time.Hour), CreatedBy: "paul@keymail.dev"} |
| + if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + // Each region's hosts are served by its boxes, the first box of a |
| + // region taking the even ones and the second the odd. |
| + inRegion := map[string][]string{} |
| + for _, b := range perfFlagshipBoxes { |
| + inRegion[b.code] = append(inRegion[b.code], b.label) |
| + } |
| + for _, b := range perfFlagshipBoxes { |
| + var served []string |
| + peers := inRegion[b.code] |
| + for i, h := range hostsBy[b.code] { |
| + if peers[i%len(peers)] == b.label { |
| + served = append(served, h) |
| + } |
| + } |
| + hosts := map[string]any{} |
| + versions := map[string]string{} |
| + for _, h := range served { |
| + hosts[h] = map[string]any{"role": "home", "stamp": 1} |
| + versions[h] = "v1" |
| + } |
| + raw, err := json.Marshal(map[string]any{"v": 1, "box": b.label, "eip": "192.0.2.10", "region": b.aws, |
| + "placement": b.code, "hosts": hosts}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, "control/edges/"+b.label+".json", raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + box := status.CollectBox(nil, status.Probes{Release: "v0.28.29", Platform: "linux-arm64", SystemChannel: "stable"}, now) |
| + box.Label, box.Region = b.label, b.aws |
| + box.Metrics.RouteVersions = versions |
| + if err := status.WriteBox(ctx, fx.rel, box); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + // Stable's system pointer, and the bootstrap binary a new box boots, |
| + // which matches it. |
| + build := []byte(strings.Repeat("stable build ", 4096)) |
| + sum := sha256.Sum256(build) |
| + if _, err := release.PromoteSystem(ctx, fx.rel, release.RootSigner(fx.priv), "router", "stable", release.SystemRelease{ |
| + Version: "v0.28.29", Artifacts: map[string]release.SystemArtifact{"linux-arm64": { |
| + Key: release.SystemArtifactKey("v0.28.29", "linux-arm64"), SHA256: hex.EncodeToString(sum[:])}}, |
| + }, release.SystemPromoteOptions{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, bootstrapKey, build, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// perfHotRoute is one hot route: its path, whether it is asked with the |
| +// CLI's bearer token rather than the browser's session, and the S3 |
| +// requests one view makes, cold (no cross-request cache holds anything for |
| +// it) and warm (asked again at once). |
| +type perfHotRoute struct { |
| + Name string |
| + Path string |
| + CLI bool |
| + Cold, Warm int |
| +} |
| + |
| +// perfHotRoutes are the hot routes over newPerfFixture with lifetimes on. |
| +// Their counts, by what they read: |
| +// |
| +// - the instance list: the record listing and, per instance, its record |
| +// and its lifetime slot (1 + 2x30); instances.json; the edges listing |
| +// and six files; the platform's box reports (two listing pages, seven |
| +// reports) and fleet-a's (one listing, one report). 80, cold or warm: |
| +// a CLI read keeps nothing between requests. |
| +// - system status: the canary and stable pointers, bootstrap/carlos (a |
| +// conditional read once its ETag is known), and the same box reports. |
| +// 14. |
| +// - the account home, warm: nothing (every app's frame and records are |
| +// held). Cold, it reads every app's frame and records, the box reports |
| +// and the edge-address fold: see TestPerfHotRoutesReadEachObjectOnce |
| +// for the one read it repeats. |
| +// - Dashboard and Boxes: status/fleet.json, the platform's box reports |
| +// and the storage queue (a listing and one entitlement). 12. |
| +func perfHotRoutes(fx *consoleFixture) []perfHotRoute { |
| + return []perfHotRoute{ |
| + {"instances list", "/api/cli/apps/" + fx.sqid + "/" + perfFlagshipApp + "/instances", true, 80, 80}, |
| + {"system status", "/api/cli/system/status", true, 14, 14}, |
| + {"account home", fx.path("/"), false, 113, 0}, |
| + {"fleet", "/fleet", false, 12, 12}, |
| + {"fleet boxes", "/fleet/boxes", false, 12, 12}, |
| + } |
| +} |
| + |
| +// s3Summary is a recorder's requests one per line, a repeated request with |
| +// its count, and the requests made more than once. |
| +func s3Summary(reqs []s3Req) (summary string, repeated []string) { |
| + counts := map[string]int{} |
| + for _, q := range reqs { |
| + counts[s3ReqName(q)]++ |
| + } |
| + var b strings.Builder |
| + for _, k := range slices.Sorted(maps.Keys(counts)) { |
| + if counts[k] > 1 { |
| + fmt.Fprintf(&b, " %dx %s\n", counts[k], k) |
| + repeated = append(repeated, k) |
| + } else { |
| + fmt.Fprintf(&b, " %s\n", k) |
| + } |
| + } |
| + return b.String(), repeated |
| +} |
| + |
| +// s3ReqName names one request: its method and key, or its listing's |
| +// prefix and page. |
| +func s3ReqName(q s3Req) string { |
| + if q.Key != "" { |
| + return q.Method + " " + q.Key |
| + } |
| + if q.Token != "" { |
| + return q.Method + " list " + q.Prefix + " (page 2+)" |
| + } |
| + return q.Method + " list " + q.Prefix |
| +} |
| + |
| +// perfFullyCold forgets everything the console holds across requests that a |
| +// hot route reads: the app frames and account manifests (perfColdReset), |
| +// the page views' box reports and records, and the edge-address fold. |
| +func perfFullyCold(fx *consoleFixture) { |
| + perfColdReset(fx) |
| + fx.srv.boxReports.invalidate() |
| + fx.srv.edgeFold.mu.Lock() |
| + fx.srv.edgeFold.at = time.Time{} |
| + fx.srv.edgeFold.mu.Unlock() |
| +} |
| + |
| +// TestPerfHotRoutesReadEachObjectOnce: over the flagship-shaped fixture with |
| +// lifetimes on, each hot route reads each object and each listing page at |
| +// most once per view, cold and warm, and makes the requests perfHotRoutes |
| +// counts. The one exception is the cold account home, where two caches |
| +// that keep for different spans (the edge-address fold and the page views' |
| +// box reports, a minute each) both read the platform's box reports. The |
| +// second system status read of the unchanged bootstrap binary is |
| +// conditional, so its body is not downloaded again. |
| +func TestPerfHotRoutesReadEachObjectOnce(t *testing.T) { |
| + perfCaptureLogs(t) |
| + clock := useLifetimesClock(t) |
| + fx, lat := newPerfFixture(t) |
| + browser := signInPaul(t, fx) |
| + token := cliToken(t, fx, "paul@keymail.dev", "code-perf-hot") |
| + turnLifetimesOn(t, fx.srv, clock) |
| + rec := recordS3(lat, nil) |
| + for _, rt := range perfHotRoutes(fx) { |
| + for _, pass := range []string{"cold", "warm"} { |
| + if pass == "cold" { |
| + perfFullyCold(fx) |
| + } |
| + rec.reset() |
| + var st int |
| + if rt.CLI { |
| + st, _ = getRaw(t, fx.ts.URL+rt.Path, token) |
| + } else { |
| + st, _, _ = get(t, browser, fx.ts.URL+rt.Path) |
| + } |
| + if !perfIdle(perfSeedsOf(fx).inflight, 2*time.Second) { |
| + t.Fatalf("%s: a handler was still running 2s after its response", rt.Name) |
| + } |
| + if st != http.StatusOK { |
| + t.Fatalf("%s %s = %d", rt.Name, rt.Path, st) |
| + } |
| + reqs := rec.all() |
| + summary, repeated := s3Summary(reqs) |
| + want := rt.Warm |
| + if pass == "cold" { |
| + want = rt.Cold |
| + } |
| + if len(reqs) != want { |
| + t.Errorf("%s (%s): %d S3 requests, want %d:\n%s", rt.Name, pass, len(reqs), want, summary) |
| + } |
| + for _, k := range repeated { |
| + if rt.Name == "account home" && pass == "cold" && strings.Contains(k, " status/boxes/") { |
| + continue |
| + } |
| + t.Errorf("%s (%s): %s more than once in one view:\n%s", rt.Name, pass, k, summary) |
| + } |
| + if rt.Name == "system status" && pass == "warm" { |
| + for _, q := range reqs { |
| + if q.Key == bootstrapKey && q.IfNoneMatch == "" { |
| + t.Errorf("system status (warm): read %s whole, want a conditional read of the binary it hashed before", bootstrapKey) |
| + } |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// TestBootstrapFallsBackToStreamingWhenTheConditionalReadFails: once the |
| +// bootstrap binary's sum is kept, a conditional read that fails (here the |
| +// bucket refuses it) is followed by a plain streaming read, and the status |
| +// still answers for the binary; the kept sum is never the answer to a |
| +// failed read. |
| +func TestBootstrapFallsBackToStreamingWhenTheConditionalReadFails(t *testing.T) { |
| + perfCaptureLogs(t) |
| + fx, lat := newPerfFixture(t) |
| + token := cliToken(t, fx, "paul@keymail.dev", "code-bootstrap-fallback") |
| + refuse := atomic.Bool{} |
| + rec := recordS3(lat, func(q s3Req) bool { return refuse.Load() && q.Key == bootstrapKey && q.IfNoneMatch != "" }) |
| + state := func() any { |
| + t.Helper() |
| + st, out := getJSON(t, fx.ts.URL+"/api/cli/system/status", token) |
| + if st != http.StatusOK { |
| + t.Fatalf("status = %d %v", st, out) |
| + } |
| + row, _ := out["bootstrap"].(map[string]any) |
| + return row["state"] |
| + } |
| + bootstrapReads := func() (plain, conditional int) { |
| + for _, q := range rec.all() { |
| + if q.Key == bootstrapKey && q.Method == http.MethodGet { |
| + if q.IfNoneMatch != "" { |
| + conditional++ |
| + } else { |
| + plain++ |
| + } |
| + } |
| + } |
| + return plain, conditional |
| + } |
| + if got := state(); got != "current" { |
| + t.Fatalf("first read: bootstrap %v, want current", got) |
| + } |
| + if p, c := bootstrapReads(); p != 1 || c != 0 { |
| + t.Fatalf("first read: %d plain and %d conditional reads of the binary, want one plain", p, c) |
| + } |
| + rec.reset() |
| + refuse.Store(true) |
| + if got := state(); got != "current" { |
| + t.Errorf("conditional read refused: bootstrap %v, want current from a streaming read", got) |
| + } |
| + if p, c := bootstrapReads(); p != 1 || c != 1 { |
| + t.Errorf("conditional read refused: %d plain and %d conditional reads, want the refused conditional one and one plain", p, c) |
| + } |
| + rec.reset() |
| + refuse.Store(false) |
| + if got := state(); got != "current" { |
| + t.Errorf("after the fallback: bootstrap %v, want current", got) |
| + } |
| + if p, c := bootstrapReads(); p != 0 || c != 1 { |
| + t.Errorf("after the fallback: %d plain and %d conditional reads, want one conditional", p, c) |
| + } |
| +} |
diff --git a/internal/console/perflatency_test.go b/internal/console/perflatency_test.go| index 7ed8a30c7..97b26c116 100644 |
| --- a/internal/console/perflatency_test.go |
| +++ b/internal/console/perflatency_test.go |
| @@ -166,9 +166,12 @@ func TestLatencyAppClientAnswersTheContract(t *testing.T) { |
| // cache answers an app page from memory in far less than the budget, so |
| // whether the over-budget warning fired would depend on how fast the |
| // page is; reading the frame afresh through the delayed fake makes the |
| -// view's S3 round trips the cost, whatever the cache saves. |
| +// view's S3 round trips the cost, whatever the cache saves. The frame's |
| +// reads run at once (console-perf-hot-routes), so the delay is 50 ms here, |
| +// not the walk's 25: the cold page's few rounds of them still cross the |
| +// budget. |
| func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) { |
| - lat := &perfLatency{S3Delay: 25 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| + lat := &perfLatency{S3Delay: 50 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, S3: lat, AppClient: lat.AppClient()}) |
| c := signInPaul(t, fx) |
| const screen = "GET /a/{sqid}/apps/{app}" |
| @@ -232,8 +235,10 @@ func TestFixtureOverTheS3FakeServesAppPage(t *testing.T) { |
| if fake <= 0 || sample != fake || background != 0 { |
| t.Errorf("delayed view: sample Calls[s3] = %d (background %d), the fake answered %d; want them equal", sample, background, fake) |
| } |
| - if took, floor := time.Since(start), time.Duration(fake)*lat.S3Delay; took < floor { |
| - t.Errorf("delayed view with S3 delays on took %v, under %d requests at %v", took, fake, lat.S3Delay) |
| + // Some reads overlap, so the view waits at least one delay, not one per |
| + // request. |
| + if took := time.Since(start); took < lat.S3Delay { |
| + t.Errorf("delayed view with S3 delays on took %v, under one request at %v", took, lat.S3Delay) |
| } |
| if g := findGroup(fx.srv.PerfGroups(), screen); g == nil || g.Requests != 2 { |
| t.Errorf("app page group = %+v, want two requests", g) |
diff --git a/internal/console/perfquickwins_test.go b/internal/console/perfquickwins_test.go| index ede5f1440..7b900bb20 100644 |
| --- a/internal/console/perfquickwins_test.go |
| +++ b/internal/console/perfquickwins_test.go |
| @@ -110,6 +110,8 @@ type s3Req struct { |
| Key string // "" for a listing |
| Prefix string // a listing's prefix |
| Token string // a listing's continuation token: "" on its first page |
| + // IfNoneMatch is a conditional read's ETag, "" for a plain one. |
| + IfNoneMatch string |
| } |
| // recordS3 installs the recorder as the fake's request hook; fail, when |
| @@ -119,7 +121,7 @@ func recordS3(lat *perfLatency, fail func(s3Req) bool) *s3Recorder { |
| rec := &s3Recorder{} |
| lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) { |
| _, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") |
| - q := s3Req{Method: r.Method, Key: key} |
| + q := s3Req{Method: r.Method, Key: key, IfNoneMatch: r.Header.Get("If-None-Match")} |
| if key == "" { |
| q.Prefix = r.URL.Query().Get("prefix") |
| q.Token = r.URL.Query().Get("continuation-token") |
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go| index b1e5c281b..dd639effc 100644 |
| --- a/internal/console/perfwalk_test.go |
| +++ b/internal/console/perfwalk_test.go |
| @@ -45,11 +45,13 @@ import ( |
| // Exceptions live in testdata/perf-budgets.txt. |
| // perfTarget is one request the walk makes for a screen: a path (with its |
| -// query), the status it must answer, and whether it is made signed out. |
| +// query), the status it must answer, and whether it is made signed out or |
| +// with the CLI's bearer token (a perfCLIScreens door). |
| type perfTarget struct { |
| Path string |
| Expect int |
| Anonymous bool |
| + CLI bool |
| } |
| // perfScreenTarget is one walked request: its screen, the target and the |
| @@ -343,6 +345,10 @@ func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) { |
| // The operator pages' tables, populated (opdashboard_test.go). |
| seedOperatorScale(t, fx) |
| + // Flagship's shape: boxes in three regions, several apps, one with |
| + // many instances across them (perfhotroutes_test.go). |
| + perfSeedFlagship(t, fx) |
| + |
| // Every object was written seconds ago, and readers that trust an |
| // object's stamp only once it has settled (domains.ClaimCache's |
| // modSettle, two seconds) would re-read them for the first moments of |
| @@ -502,6 +508,11 @@ func perfTargets(fx *consoleFixture) map[string][]perfTarget { |
| for screen, ts := range perfOperatorTargets() { |
| m[screen] = ts |
| } |
| + // The CLI doors, asked as `carlos instances list` and `carlos system |
| + // status` ask them: the many-instance app's list, and the status read. |
| + m["GET /api/cli/apps/{account}/{app}/instances"] = []perfTarget{{ |
| + Path: "/api/cli/apps/" + fx.sqid + "/" + perfFlagshipApp + "/instances", Expect: http.StatusOK, CLI: true}} |
| + m["GET /api/cli/system/status"] = []perfTarget{{Path: "/api/cli/system/status", Expect: http.StatusOK, CLI: true}} |
| return m |
| } |
| @@ -627,17 +638,34 @@ func mapKeys[V any](m map[string]V) func(func(string) bool) { |
| } |
| } |
| -// perfClients are the walk's two browsers: Paul signed in (an operator and |
| -// the ops account's owner) and a signed-out one. |
| -type perfClients struct{ paul, anon *http.Client } |
| +// perfClients are the walk's two browsers, Paul signed in (an operator and |
| +// the ops account's owner) and a signed-out one, and Paul's CLI. |
| +type perfClients struct{ paul, anon, cli *http.Client } |
| func (c perfClients) of(tg perfTarget) *http.Client { |
| - if tg.Anonymous { |
| + switch { |
| + case tg.Anonymous: |
| return c.anon |
| + case tg.CLI: |
| + return c.cli |
| } |
| return c.paul |
| } |
| +// perfCLIClient is a client that sends token as the CLI does, a bearer |
| +// Authorization header on every request. |
| +func perfCLIClient(token string) *http.Client { |
| + return &http.Client{Transport: perfBearer{token: token}} |
| +} |
| + |
| +type perfBearer struct{ token string } |
| + |
| +func (b perfBearer) RoundTrip(r *http.Request) (*http.Response, error) { |
| + r = r.Clone(r.Context()) |
| + r.Header.Set("Authorization", "Bearer "+b.token) |
| + return http.DefaultTransport.RoundTrip(r) |
| +} |
| + |
| // perfResult is one walked request's measurement. |
| type perfResult struct { |
| ttfb time.Duration |
| @@ -751,7 +779,8 @@ func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| } |
| t.FailNow() |
| } |
| - clients := perfClients{paul: signInPaul(t, fx), anon: newBrowser(t)} |
| + clients := perfClients{paul: signInPaul(t, fx), anon: newBrowser(t), |
| + cli: perfCLIClient(cliToken(t, fx, "paul@keymail.dev", "code-perf-walk-cli"))} |
| enforce := perfEnforce() |
| timing := func(format string, a ...any) { |
| t.Helper() |
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go| index 6936bf6ea..75b548883 100644 |
| --- a/internal/console/remoteinstances.go |
| +++ b/internal/console/remoteinstances.go |
| @@ -190,15 +190,32 @@ func (s *Server) pageBoxReports(ctx context.Context) ([]status.Box, bool) { |
| gen := c.gen |
| c.mu.Unlock() |
| - loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), instanceStoreTimeout) |
| - boxes, complete, err := status.LoadBoxesComplete(loadCtx, s.cfg.Releases) |
| - cancel() |
| - if err != nil { |
| - log.Printf("console: box reports for the app pages: %v", err) |
| - boxes, complete = nil, false |
| + // A read of the platform's boxes this request has already finished |
| + // (the instance list's rollout join, loadBoxes) is the read this |
| + // load would make, so it is held instead, timed from when it |
| + // finished, but only when it began at this generation: a read that |
| + // began before an invalidation is what the invalidation discards. |
| + // Otherwise the load is the cache's own. |
| + var ( |
| + boxes []status.Box |
| + complete bool |
| + err error |
| + at time.Time |
| + ) |
| + if l, ok := memoFinished[loadedBoxes](ctx, boxesMemoKey("")); ok && l.gen == gen { |
| + boxes, complete, at = l.boxes[:len(l.boxes):len(l.boxes)], l.complete, c.clock().Add(-time.Since(l.at)) |
| + } else { |
| + loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), instanceStoreTimeout) |
| + boxes, complete, err = loadBoxesConcurrently(loadCtx, s.cfg.Releases) |
| + cancel() |
| + if err != nil { |
| + log.Printf("console: box reports for the app pages: %v", err) |
| + boxes, complete = nil, false |
| + } |
| + at = c.clock() |
| } |
| c.mu.Lock() |
| - c.at, c.valid, c.failed, c.boxes, c.complete = c.clock(), c.gen == gen, err != nil || !complete, boxes, complete |
| + c.at, c.valid, c.failed, c.boxes, c.complete = at, c.gen == gen, err != nil || !complete, boxes, complete |
| c.loading = nil |
| close(done) |
| c.mu.Unlock() |
| @@ -506,17 +523,24 @@ func (s *Server) pageRecords(ctx context.Context, acct, app string) ([]provision |
| hosts = append(hosts, host) |
| } |
| sort.Strings(hosts) |
| - recs := make([]provision.Record, 0, len(hosts)) |
| - for _, host := range hosts { |
| - rec, _, err := provision.ReadRecordJudged(ctx, store, judge, acct, app, host) |
| + // Each host's record (and, judged, its slot after it) is read on its |
| + // own, readConcurrency hosts at a time; recs keeps host order. |
| + read := make([]*provision.Record, len(hosts)) |
| + forEachLimit(len(hosts), readConcurrency, func(i int) { |
| + rec, _, err := provision.ReadRecordJudged(ctx, store, judge, acct, app, hosts[i]) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| - continue |
| case err != nil: |
| - log.Printf("console: instance record %s/%s/%s: %v", acct, app, host, err) |
| - continue |
| + log.Printf("console: instance record %s/%s/%s: %v", acct, app, hosts[i], err) |
| + default: |
| + read[i] = rec |
| + } |
| + }) |
| + recs := make([]provision.Record, 0, len(hosts)) |
| + for _, rec := range read { |
| + if rec != nil { |
| + recs = append(recs, *rec) |
| } |
| - recs = append(recs, *rec) |
| } |
| s.boxReports.holdRecords(gen, k, slices.Clone(recs)) |
| return recs, nil |
| @@ -549,8 +573,64 @@ func (s *Server) assembleApps(ctx context.Context, acct string, apps []string) ( |
| // assembleAppsNamed is assembleApps for a caller that knows the account's |
| // name, which the frame cache keeps so a write addressed by name clears it. |
| +// |
| +// Each app's frame and instance records, and the box reports, are read |
| +// before Assemble runs, all at once (readConcurrency at a time), and |
| +// Assemble is handed what they read: the same reads, through the same |
| +// caches, that Assemble would otherwise make one app after another. |
| func (s *Server) assembleAppsNamed(ctx context.Context, acct, acctName string, apps []string) ([]AppView, error) { |
| - return assembleViews(ctx, s.cfg.Registry, acct, apps, s.dnsTargets(ctx), s.remoteSource(ctx, acct), func(app string) appFrame { |
| + remote := s.remoteSource(ctx, acct) |
| + var names []string |
| + for _, app := range apps { |
| + if app != "" && !slices.Contains(names, app) { |
| + names = append(names, app) |
| + } |
| + } |
| + type records struct { |
| + recs []provision.Record |
| + err error |
| + } |
| + frames := make([]appFrame, len(names)) |
| + recs := make([]records, len(names)) |
| + var dns DNSTargets |
| + // Task 0 is the DNS guidance's edge addresses (a cached fold, read |
| + // when it has aged); tasks 1 to len(names) are the apps' frames; with |
| + // remote rows, the next len(names) are their records and the last |
| + // warms the box reports remote rows join against (remoteFacts, whose |
| + // read every app's facts share). |
| + tasks := 1 + len(names) |
| + if remote != nil && len(names) > 0 { |
| + tasks += len(names) + 1 |
| + } |
| + forEachLimit(tasks, readConcurrency, func(task int) { |
| + i := task - 1 |
| + switch { |
| + case i < 0: |
| + dns = s.dnsTargets(ctx) |
| + case i < len(names): |
| + frames[i] = s.appFrame(ctx, acct, acctName, names[i]) |
| + case i < 2*len(names): |
| + r, err := remote.records(names[i-len(names)]) |
| + recs[i-len(names)] = records{r, err} |
| + default: |
| + remote.facts(names[0]) |
| + } |
| + }) |
| + index := func(app string) int { return slices.Index(names, app) } |
| + if remote != nil { |
| + read := *remote |
| + read.records = func(app string) ([]provision.Record, error) { |
| + if i := index(app); i >= 0 { |
| + return recs[i].recs, recs[i].err |
| + } |
| + return remote.records(app) |
| + } |
| + remote = &read |
| + } |
| + return assembleViews(ctx, s.cfg.Registry, acct, apps, dns, remote, func(app string) appFrame { |
| + if i := index(app); i >= 0 { |
| + return frames[i] |
| + } |
| return s.appFrame(ctx, acct, acctName, app) |
| }) |
| } |
diff --git a/internal/console/reqmemo.go b/internal/console/reqmemo.go| index 6cc401eb4..842e9f4f3 100644 |
| --- a/internal/console/reqmemo.go |
| +++ b/internal/console/reqmemo.go |
| @@ -75,6 +75,33 @@ func memoize[T any](ctx context.Context, key string, load func() (T, error)) (T, |
| return v, err |
| } |
| +// memoFinished is key's value when this request's memo holds a load of it |
| +// that has finished without error; ok is false otherwise (no memo, no |
| +// such load, one still running, or one that failed). It never loads and |
| +// never waits. |
| +func memoFinished[T any](ctx context.Context, key string) (v T, ok bool) { |
| + m, _ := ctx.Value(reqMemoKey{}).(*reqMemo) |
| + if m == nil { |
| + return v, false |
| + } |
| + m.mu.Lock() |
| + e, has := m.entries[key] |
| + m.mu.Unlock() |
| + if !has { |
| + return v, false |
| + } |
| + select { |
| + case <-e.done: |
| + default: |
| + return v, false |
| + } |
| + if e.err != nil { |
| + return v, false |
| + } |
| + v, ok = e.val.(T) |
| + return v, ok |
| +} |
| + |
| // withReqMemoOnViews gives each GET and HEAD request a memo of its own. |
| func withReqMemoOnViews(h http.HandlerFunc) http.HandlerFunc { |
| return func(w http.ResponseWriter, r *http.Request) { |
| @@ -85,24 +112,36 @@ func withReqMemoOnViews(h http.HandlerFunc) http.HandlerFunc { |
| } |
| } |
| +// loadedBoxes is one memoized read of a prefix's box reports, when it |
| +// finished, and the page views' box-report cache generation (boxReports) |
| +// when it began: pageBoxReports holds the read only if no invalidation |
| +// came between. |
| +type loadedBoxes struct { |
| + boxes []status.Box |
| + complete bool |
| + at time.Time |
| + gen uint64 |
| +} |
| + |
| +// boxesMemoKey is loadBoxes' memo key for prefix. |
| +func boxesMemoKey(prefix string) string { return "boxes:" + prefix } |
| + |
| // loadBoxes is status.LoadBoxesComplete on st under prefix ("" for the |
| // platform's own boxes, "fleets/<name>/" for a customer fleet's), once per |
| -// request. complete and err are exactly the load's: a partial listing stays |
| -// partial for every reader. The memo key names only the prefix, so st is |
| -// always the console's release store. The slice is clipped, so a reader |
| -// that appends to it gets a copy rather than writing into the memo's. |
| +// request, with the reports read concurrently (loadBoxesConcurrently). |
| +// complete and err are exactly the load's: a partial listing stays partial |
| +// for every reader. The memo key names only the prefix, so st is always the |
| +// console's release store. The slice is clipped, so a reader that appends |
| +// to it gets a copy rather than writing into the memo's. |
| func (s *Server) loadBoxes(ctx context.Context, st release.Store, prefix string) (boxes []status.Box, complete bool, err error) { |
| - type loaded struct { |
| - boxes []status.Box |
| - complete bool |
| - } |
| - l, err := memoize(ctx, "boxes:"+prefix, func() (loaded, error) { |
| + l, err := memoize(ctx, boxesMemoKey(prefix), func() (loadedBoxes, error) { |
| store := st |
| if prefix != "" { |
| store = release.NewPrefixStore(st, prefix) |
| } |
| - b, c, err := status.LoadBoxesComplete(ctx, store) |
| - return loaded{b, c}, err |
| + gen := s.boxReports.generation() |
| + b, c, err := loadBoxesConcurrently(ctx, store) |
| + return loadedBoxes{b, c, time.Now(), gen}, err |
| }) |
| return l.boxes[:len(l.boxes):len(l.boxes)], l.complete, err |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 67681a899..1e287daba 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1323,6 +1323,9 @@ type Server struct { |
| // every step of it is idempotent. |
| systemMu sync.Mutex |
| systemJobs map[string]*systemJob |
| + // bootstrapSum is the last sha256 the system status computed for |
| + // bootstrap/carlos, with the ETag it was read under (bootstrapSHA256). |
| + bootstrapSum bootstrapHash |
| // geoip is the single writer of control/geoip/ (geoip spec ยง3); nil |
| // when this console has no deployment bucket. |
| geoip *geoipPublisher |
| @@ -1533,7 +1536,15 @@ func (s *Server) realFoldEdgeIPs(ctx context.Context) []string { |
| if s.cfg.Releases == nil { |
| return nil |
| } |
| - ips := edgesfile.EdgeIPs(ctx, s.cfg.Releases, nil, time.Now()) |
| + // The box reports and the edges files are read concurrently |
| + // (readConcurrently). The dry pass's body is a live box report and a |
| + // versioned edges file for one made-up box at once, which EdgeIPs |
| + // accepts for either without logging. |
| + now := time.Now() |
| + dry := []byte(`{"v":1,"box":"-","label":"-","generated_at":"` + now.UTC().Format(time.RFC3339) + `"}`) |
| + ips := readConcurrently(ctx, s.cfg.Releases, dry, boxReportKeyLimit, func(st release.Store) []string { |
| + return edgesfile.EdgeIPs(ctx, st, nil, now) |
| + }) |
| slices.Sort(ips) |
| return ips |
| } |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index f8c5d62a5..9c400c386 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -31,39 +31,49 @@ GET /static/{hash}/{file...} skip: static asset, not a screen; consolePerfSkip l |
| # Deferred parts: timed and printed, exempt from 150 ms and the call count. |
| GET /a/{sqid}/apps/new calls 1: the account telemetry settings, which set the analytics checkbox the form starts from (1 S3 call warm, 10 ms or less) |
| + |
| +# The CLI doors flagship's speed table put slowest (console-perf-hot-routes, |
| +# 2026-10-27), walked with the CLI's token. Their reads run at once, ten at |
| +# a time, and nothing is kept between requests, so warm and cold read the |
| +# same. Counts are the walk's fixture: seven platform boxes (two listing |
| +# pages, past 1,100 gone reports), one fleet box, six edges files, and an |
| +# app with 30 instances across three regions, lifetimes off. |
| +GET /api/cli/apps/{account}/{app}/instances calls 50: carlos instances list: the record listing and each of the 30 records, instances.json, the edges listing and its six files, and the platform's and fleet-a's box reports (two listing pages and seven reports, one listing and one report); median about 135 ms. With lifetimes on each record's slot is read after it, 30 more (TestPerfHotRoutesReadEachObjectOnce) |
| +GET /api/cli/system/status calls 14: carlos system status: the canary and stable pointers, bootstrap/carlos (a conditional read once its ETag is known, so an unchanged binary is not downloaded again), and the same box reports; median about 130 ms |
| GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data endpoint) |
| # Known slow today (measured 2026-10-26 after console-perf-quick-wins, with |
| -# 25 ms per S3 request and 40 ms per app-host call). The next round deletes |
| -# these. "the app-tab frame" is what every app tab reads before its own part: |
| +# 25 ms per S3 request and 40 ms per app-host call; counts and times |
| +# re-measured 2026-10-27 after console-perf-hot-routes, whose fixture has |
| +# seven boxes and six edges files, and whose app-tab frame reads at once). |
| +# The next round deletes these. "the app-tab frame" is what every app tab reads before its own part: |
| # the production flag, the pipeline, and a listing plus one read per channel |
| # (6 S3 calls). It is cached per app for 30 s (appframe.go), so a warm view |
| # reads none of it; the account manifest is read once per process and then |
| # remembered. A cold view (perfColdReset) reads both: 7 S3 calls, about |
| -# 180 ms, over the 150 ms budget on their own, which keeps every app tab here. |
| +# 80 ms now the frame's reads run at once. |
| # The walk prints only warm counts for these records; the cold counts below |
| # were measured by walking with each record turned into a calls record. |
| -/fleet/architecture over: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (8 S3 calls warm and cold, median about 260 ms) |
| -GET /a/{sqid}/apps/{app} over: Overview is the release listing and every manifest (3 S3 calls warm, median about 80 ms); cold, also the app-tab frame, the account manifest and every box's metrics hours for two days (129 S3 calls, about 1.1 s) |
| -GET /a/{sqid}/apps/{app}/account-review over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 185 ms) |
| -GET /a/{sqid}/apps/{app}/activity over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 185 ms) |
| -GET /a/{sqid}/apps/{app}/analytics over: both telemetry settings, the analytics day listing and one day read (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 285 ms) |
| -GET /a/{sqid}/apps/{app}/availability over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 440 ms) |
| -GET /a/{sqid}/apps/{app}/errors over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 440 ms) |
| -GET /a/{sqid}/apps/{app}/instances over: instances.json, and every edges file and box report listed and read once per view (9 S3 calls warm, median about 290 ms); cold, also the app-tab frame and the account manifest (16 S3 calls and 1 host call, about 510 ms) |
| -GET /a/{sqid}/apps/{app}/instances/{host} over: the instance record, instances.json, the edges listing, and the box reports and the fleet box reports listed and read once per view (10 S3 calls warm, median about 315 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 495 ms) |
| -GET /a/{sqid}/apps/{app}/logs over: three listings for the log chunks and a chunk read; the host picker uses the records the page already holds (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 285 ms) |
| -GET /a/{sqid}/apps/{app}/releases over: the release and tag listings, at most 20 manifests, retention and instances.json (6 S3 calls warm, median about 160 ms; 4 on the fixture's empty page 2); cold, also the app-tab frame and the account manifest (13 S3 calls, about 340 ms; 11 on page 2) |
| -GET /a/{sqid}/apps/{app}/settings over: the one-key app listing for the rename check (a second for the legacy prefix when the first is empty) and the swap policy (2 S3 calls warm, 3 at most, median about 55 ms); cold, also the app-tab frame and the account manifest (9 S3 calls, about 235 ms) |
| -GET /a/{sqid}/apps/{app}/settings/{section} over: Domains still reads the domain claims, cert-warm records, every box report and every instance record (12 S3 calls warm, median about 365 ms; 20 cold); the other sections read only their own data, warm (cold adds the app-tab frame and the account manifest, 7 more): General 2 (cold 9), Environments 5 (12), Storage 4 (11), Email 1 (8), Feature flags 1 (8), Errors and analytics 2 (9), the pipeline section, Placement and Delete none (7); the advanced redirect none, warm or cold |
| +/fleet/architecture over: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, median about 370 ms) |
| +GET /a/{sqid}/apps/{app} over: Overview is the release listing and every manifest (3 S3 calls warm, median about 80 ms); cold, also the app-tab frame, the account manifest and every box's metrics hours for two days (141 S3 calls, about 610 ms) |
| +GET /a/{sqid}/apps/{app}/account-review over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 80 ms) |
| +GET /a/{sqid}/apps/{app}/activity over: a warm view reads nothing (0 S3 calls; the app-tab frame is cached); a cold view reads the frame and the account manifest (7 S3 calls, about 80 ms) |
| +GET /a/{sqid}/apps/{app}/analytics over: both telemetry settings, the analytics day listing and one day read (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 180 ms) |
| +GET /a/{sqid}/apps/{app}/availability over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 335 ms) |
| +GET /a/{sqid}/apps/{app}/errors over: both telemetry settings and three listings and a read each for the log and error chunks (10 S3 calls warm, median about 260 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 335 ms) |
| +GET /a/{sqid}/apps/{app}/instances over: instances.json, and every edges file and box report listed and read once per view (17 S3 calls warm, median about 500 ms: the edges files are still read one after another); cold, also the app-tab frame and the account manifest (24 S3 calls and 1 host call, about 615 ms) |
| +GET /a/{sqid}/apps/{app}/instances/{host} over: the instance record, instances.json, the edges listing, and the box reports and the fleet box reports listed and read once per view (14 S3 calls warm, median about 210 ms); cold, also the app-tab frame and the account manifest (21 S3 calls, about 290 ms) |
| +GET /a/{sqid}/apps/{app}/logs over: three listings for the log chunks and a chunk read; the host picker uses the records the page already holds (4 S3 calls warm, median about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 180 ms) |
| +GET /a/{sqid}/apps/{app}/releases over: the release and tag listings, at most 20 manifests, retention and instances.json (6 S3 calls warm, median about 160 ms; 4 on the fixture's empty page 2); cold, also the app-tab frame and the account manifest (13 S3 calls, about 235 ms; 11 on page 2) |
| +GET /a/{sqid}/apps/{app}/settings over: the one-key app listing for the rename check (a second for the legacy prefix when the first is empty) and the swap policy (2 S3 calls warm, 3 at most, median about 55 ms); cold, also the app-tab frame and the account manifest (9 S3 calls, about 130 ms) |
| +GET /a/{sqid}/apps/{app}/settings/{section} over: Domains still reads the domain claims, cert-warm records, every box report and every instance record (16 S3 calls warm, median about 420 ms; 24 cold); the other sections read only their own data, warm (cold adds the app-tab frame and the account manifest, 7 more): General 2 (cold 9), Environments 5 (12), Storage 4 (11), Email 1 (8), Feature flags 1 (8), Errors and analytics 2 (9), the pipeline section, Placement and Delete none (7); the advanced redirect none, warm or cold |
| GET /a/{sqid}/fleet over: reads status/fleet.json and lists and reads each customer fleet's box reports (3 S3 calls warm and cold, median about 80 ms) |
| GET /a/{sqid}/fleets/{fleet} over: lists and reads the fleet's box reports (2 S3 calls warm and cold, median about 55 ms) |
| GET /a/{sqid}/plan/keep over: the lapse inventory lists every app's instance records and reads each one, lists every app's sidecar records, and lists the domain claims (8 S3 calls warm for two apps and three instances, median 209 ms; it grows with the account) |
| GET /a/{sqid}/settings calls 2: the account telemetry settings and the storage entitlement |
| -GET /a/{sqid}/{$} over: a warm view reads nothing (0 S3 calls; each app's frame is cached); a cold view reads every app's frame (6 S3 calls per app, about 155 ms for one) |
| GET /a/{sqid}/trash over: reads each trashed app's deleted.json marker (1 S3 call warm and cold per app) |
| -GET /fleet over: the dashboard reads status/fleet.json, lists and reads every box report once each, and for a store operator lists and reads the storage entitlements, the same reads Boxes makes; operator pages are seldom viewed and carry no cache, and its SQLite reads add no remote call (8 S3 calls warm and cold, median about 270 ms) |
| -GET /fleet/boxes over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements; operator pages are seldom viewed and carry no cache (8 S3 calls warm and cold, median about 260 ms) |
| +GET /fleet over: the dashboard reads status/fleet.json, lists and reads every box report once each, and for a store operator lists and reads the storage entitlements, the same reads Boxes makes, all at once; operator pages are seldom viewed and carry no cache, and its SQLite reads add no remote call (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk, whose eleven views of it would cost 1.5 s of the walk's 10 s) |
| +GET /fleet/boxes over: lists and reads every box report, reads status/fleet.json, and lists and reads the storage entitlements, all at once; operator pages are seldom viewed and carry no cache (12 S3 calls warm and cold, median about 133 ms, inside the budget; kept out of the timed walk as Dashboard is) |
| GET /fleet/economics over: the cold view sweeps usage for every day of the period (162 S3 calls, about 4.1 s); warm views come from the 60 s cache (0 S3 calls) |
| GET /fleet/economics/accounts over: shares /fleet/economics's sweep cache, so its own cold view is that same sweep (0 S3 calls warm) |
| GET /fleet/metrics over: a cold view reads every box's metrics hours for two days (about 120 S3 calls, counted in Overview's cold view); warm views are cached (0 S3 calls), and the walk never sees it cold: the app pages before it fill that cache and perfColdReset leaves it |
diff --git a/internal/console/testdata/perf-session-s3.txt b/internal/console/testdata/perf-session-s3.txt| index 9cb4ea6f7..090b46a84 100644 |
| --- a/internal/console/testdata/perf-session-s3.txt |
| +++ b/internal/console/testdata/perf-session-s3.txt |
| @@ -1 +1 @@ |
| -320 after console-perf-quick-wins, 2026-10-26 |
| +401 after console-perf-hot-routes, 2026-10-27: the fixture now has seven boxes, six edges files and four live apps, one with 30 instances (320 before on the old fixture); the concurrent reads add no request |
diff --git a/internal/provision/console_perf_hot_routes_census_test.go b/internal/provision/console_perf_hot_routes_census_test.go| new file mode 100644 |
| index 000000000..f58007f0a |
| --- /dev/null |
| +++ b/internal/provision/console_perf_hot_routes_census_test.go |
| @@ -0,0 +1,32 @@ |
| +package provision |
| + |
| +// Record-write census entries for console-perf-hot-routes, layered on |
| +// operatorPeopleDetailWriteCensusInventory (main's newest at 2d224b1e). |
| +// Reviewed by the branch author; the census owner rules on #280. No record |
| +// write is added anywhere, and no class or site kind changes: each unit |
| +// below is re-pinned because its reads now run concurrently. |
| +// - Server.handleAPIInstanceList: the record listing, the rollout join's |
| +// box reports, the edges files and instances.json are read at once |
| +// (runConcurrently). Same "instances" literal: still key-site. |
| +// - Server.pageRecords: each listed host's record (and, judged, its slot |
| +// after it) is read ten hosts at a time, kept in host order. Same |
| +// RecordsPrefix listing: still key-site. |
| +func consolePerfHotRoutesWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), operatorPeopleDetailWriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"internal/console/apiinstances.go", "Server.handleAPIInstanceList", "key-site", "lit:instances", "75fea29320ab769047d0e36e0a00ed2adbe9a2b4e6e45d1af7786ca3e8c0414d"}, |
| + {"internal/console/remoteinstances.go", "Server.pageRecords", "key-site", "key:RecordsPrefix", "56021ef9c7f57a3dbbad6da4b61d11a06354e86d4d53199d193b6a9baf6968c9"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("console-perf-hot-routes replacement of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 7abe29462..67ed78019 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := operatorPeopleDetailWriteCensusInventory() |
| + inventory := consolePerfHotRoutesWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |