| new file mode 100644 |
| index 000000000..cfc3bbde0 |
| --- /dev/null |
| +++ b/internal/console/perfwalk_test.go |
| @@ -0,0 +1,831 @@ |
| +package console |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/http/httptrace" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/crypto/bcrypt" |
| + |
| + "github.com/carlosframework/platform/internal/analytics" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/apperr" |
| + "github.com/carlosframework/platform/internal/applog" |
| + "github.com/carlosframework/platform/internal/certwarm" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/ratelimit" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The CI walk (spec Part 2, §2.5 step 2): every HTML screen in the route |
| +// inventory, requested through the production-wired fixture over the S3 |
| +// fake with latency on, timed to first byte and counted in remote calls. |
| +// 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. |
| +type perfTarget struct { |
| + Path string |
| + Expect int |
| + Anonymous bool |
| +} |
| + |
| +// perfScreenTarget is one walked request: its screen, the target and the |
| +// screen's budgets record (nil when it has none). |
| +type perfScreenTarget struct { |
| + Screen string |
| + Target perfTarget |
| + Record *perfRecord |
| +} |
| + |
| +// perfQuiesce runs after every walked request, before its call count is |
| +// read, so background loads the request started are counted against it. |
| +// Plan 2 fills it in. |
| +var perfQuiesce = func(fx *consoleFixture) {} |
| + |
| +// perfColdReset runs before a screen's cold request, so that it meets a |
| +// console that has cached nothing for it. Plan 2 fills it in. |
| +var perfColdReset = func(fx *consoleFixture) {} |
| + |
| +// perfEnforce is whether timing fails the walk: only in CI, where the |
| +// machine is quiet enough to hold to a number. Call counts and fixture |
| +// checks fail everywhere. |
| +func perfEnforce() bool { return os.Getenv("CI") != "" || os.Getenv("AMADAN_CI") != "" } |
| + |
| +const ( |
| + perfBudget = 150 * time.Millisecond |
| + perfWorstBudget = 450 * time.Millisecond |
| + perfTotalBudget = 10 * time.Second |
| +) |
| + |
| +// perfSeeds is what newPerfFixture seeded that perfTargets needs to spell |
| +// a path, and the walk's in-flight counter, keyed by fixture. |
| +type perfSeeds struct { |
| + invite, emailLink string |
| + inflight *atomic.Int32 |
| +} |
| + |
| +var perfSeeded sync.Map // *consoleFixture -> *perfSeeds |
| + |
| +func perfSeedsOf(fx *consoleFixture) *perfSeeds { |
| + v, ok := perfSeeded.Load(fx) |
| + if !ok { |
| + panic("perf: fixture not built by newPerfFixture") |
| + } |
| + return v.(*perfSeeds) |
| +} |
| + |
| +// newPerfFixture is the console under the walk: newConsoleFixtureWith over |
| +// the S3 fake with the walk's latency (off until a test enables it), the |
| +// app-host client from the same perfLatency, and every section a screen |
| +// renders seeded so its loops run. |
| +func newPerfFixture(t *testing.T) (*consoleFixture, *perfLatency) { |
| + t.Helper() |
| + lat := &perfLatency{S3Delay: 25 * time.Millisecond, HostDelay: 40 * time.Millisecond} |
| + seeds := &perfSeeds{inflight: new(atomic.Int32)} |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{ |
| + WithKey: true, |
| + S3: lat, |
| + AppClient: lat.AppClient(), |
| + Wrap: func(h http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + seeds.inflight.Add(1) |
| + defer seeds.inflight.Add(-1) |
| + h.ServeHTTP(w, r) |
| + }) |
| + }, |
| + }) |
| + perfSeeded.Store(fx, seeds) |
| + t.Cleanup(func() { perfSeeded.Delete(fx) }) |
| + perfSeed(t, fx, seeds) |
| + return fx, lat |
| +} |
| + |
| +// perfSeed adds the walk's seeds on top of the fixture's own (kass with v1 |
| +// and v2, channels stable and canary/x, routes kass.carlosapp.dev and |
| +// docs.kass.carlosapp.dev), so every loop a screen runs has rows to run |
| +// over. Everything is written straight into fx.rel (the DirStore under the |
| +// S3 fake), the registry file or the console store, so none of it is |
| +// counted. |
| +func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) { |
| + t.Helper() |
| + ctx := context.Background() |
| + now := time.Now() |
| + acct := fx.sqid |
| + if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + // /fleet/store is for the operators the deployment lists, too. |
| + fx.srv.cfg.StoreOperators = []string{"paul@keymail.dev"} |
| + |
| + // /invite/{token}: an invite to the address signed in, which answers |
| + // the confirm page. |
| + tok, err := fx.st.CreateInvite(OpsAccountID, "paul@keymail.dev", "paul@keymail.dev", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seeds.invite = tok |
| + // /auth/email/link?t=: a live sign-in link; its GET never spends it. |
| + link, _, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "paul@keymail.dev", |
| + FlowHash: hashToken("perf-walk-flow")}, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + seeds.emailLink = link |
| + |
| + // The registry: a customer fleet with one box, and routes for the |
| + // instance records below. |
| + reg := openTestReg(t, fx) |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: "fleet-a", Account: acct, Bucket: "fleet-a-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.AddFleetBox(registry.FleetBox{Fleet: "fleet-a", Label: "pi-1", TokenHash: strings.Repeat("a", 64)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rt := range []registry.Route{ |
| + {Host: "beta.kass.carlosapp.dev", Kind: "instance", Status: "ready", Version: "v2", App: "kass", Channel: "beta", Addr: "127.0.0.1:9002"}, |
| + {Host: "staging.kass.carlosapp.dev", Kind: "instance", Status: "ready", Version: "v1", App: "kass", Channel: "stable", Addr: "127.0.0.1:9003"}, |
| + } { |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + reg.Close() |
| + writeFleetHeartbeat(t, fx, "fleet-a", status.Box{GeneratedAt: now, Label: "pi-1", |
| + Metrics: &status.BoxMetrics{MemTotalBytes: pi64(2 << 30), MemAvailBytes: pi64(1 << 30), Load1: p(0.4), |
| + DiskFreeBytes: pi64(5 << 30), Release: "v1", Tunnel: "connected"}}) |
| + |
| + // A pipeline (beta then stable) with v2 on beta, so a promote of v2 to |
| + // stable is the next rung, and one pending change waiting on it. |
| + if _, err := release.SetPipeline(ctx, fx.rel, fx.priv, acct, "kass", |
| + []release.PipelineChannel{{Name: "beta"}, {Name: "stable"}}, "fixture"); err != nil { |
| + t.Fatal(err) |
| + } |
| + seedChannel(t, fx, "kass", "beta", "v2") |
| + if _, err := fx.st.ProposeChange(OpsAccountID, "kass", "promote", []byte(`{"version":"v1","channel":"beta"}`), 2, |
| + "paul@keymail.dev", false, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Two tags and a retention policy. |
| + for _, v := range []string{"v1", "v2"} { |
| + if _, _, err := release.EnsureTag(ctx, fx.rel, acct, "kass", v, "fixture", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.SetRetention(ctx, fx.rel, acct, "kass", 25, "fixture", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // Three instance records: one behind a password gate, one with a rate |
| + // limit, one bound to an environment. |
| + gate, err := bcrypt.GenerateFromPassword([]byte("correct horse"), bcrypt.MinCost) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rec := range []provision.Record{ |
| + {Host: "kass.carlosapp.dev", Channel: "stable", Gate: string(gate)}, |
| + {Host: "beta.kass.carlosapp.dev", Channel: "beta", RateLimit: &ratelimit.Settings{Rule: ratelimit.Rule{Rate: 500}}}, |
| + {Host: "staging.kass.carlosapp.dev", Channel: "stable", Environment: "staging"}, |
| + } { |
| + rec.Schema, rec.App, rec.Account, rec.Region, rec.CreatedAt, rec.CreatedBy = 1, "kass", acct, "ie", now, "paul@keymail.dev" |
| + rec.Slug = strings.Split(rec.Host, ".")[0] |
| + if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + |
| + // Two config environments, each with a store of its own. |
| + for _, env := range []string{"staging", "production"} { |
| + if _, err := appconfig.ApplyEnvironment(ctx, fx.rel, acct, "kass", env, map[string]appconfig.Var{ |
| + "APP_ORIGIN": {Kind: "env", Value: "https://" + env + ".example.com"}, |
| + "API_KEY": {Kind: "secret", Envelope: "sealed-envelope-bytes"}, |
| + }, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + bucket := "carlos-" + acct + "-kass-" + env |
| + if _, err := objstore.PutIn(ctx, fx.rel, acct, "kass", env, &objstore.Record{ |
| + Declared: &objstore.Declared{EnvPrefix: "CARLOS_STORE", At: now, By: "paul@keymail.dev"}, |
| + Grant: &objstore.GrantBlock{Backend: "mem", Bucket: bucket, Source: objstore.GrantSourceOperator, At: now, By: "op"}, |
| + Provisioned: &objstore.Provisioned{Bucket: bucket, Region: "eu-west-1", IAMUser: "u", KeyID: "K", At: now}, |
| + }, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // A pending storage application for /fleet/store's queue. |
| + putEntitlement(t, fx, acct, &objstore.Entitlement{Applied: &objstore.Applied{By: "paul@keymail.dev", At: now, Note: "for uploads"}}) |
| + // A mail sender, and feature flags. |
| + putMailRecord(t, fx, "kass", &mail.Record{ |
| + Declared: &mail.Declared{EnvPrefix: "CARLOS_SMTP", From: "hi@shop.example.com", At: now}, |
| + Grant: &mail.GrantBlock{Domains: []string{"shop.example.com"}, DailyCap: 500, At: now}, |
| + Provisioned: &mail.Provisioned{KeyID: "AKIAEXAMPLE", Active: true, At: now}, |
| + }) |
| + if _, _, err := release.UpdateFeatures(ctx, fx.rel, acct, "kass", map[string]string{"beta": "on", "checkout": "v2"}, nil, |
| + "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A custom domain claim, failing to get its certificate. |
| + seedClaim(t, fx, domains.Claim{Schema: 1, Host: "shop.example.com", Account: acct, App: "kass", |
| + CreatedAt: now.UTC().Format(time.RFC3339), CreatedBy: "paul@keymail.dev"}) |
| + warm, err := certwarm.Record{Host: "shop.example.com", Attempts: 1, Class: certwarm.ClassOther, |
| + NextAttemptAt: now.Add(time.Hour).Unix()}.Encode(now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, certwarm.Key("shop.example.com"), warm, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // A trashed app. |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop-old", "paul@keymail.dev", now.Add(-time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + shipVersion(t, fx, "shop-old", "v1") |
| + if err := release.TrashApp(ctx, fx.rel, acct, "shop-old", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.TrashAppRow(OpsAccountID, "shop-old", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // Two boxes: an edges file, a status snapshot and a metrics chunk each. |
| + for _, box := range []string{"box-a", "box-b"} { |
| + putStatusEdges(t, fx, box, map[string]any{"kass.carlosapp.dev": map[string]any{"role": "home", "stamp": 1}}) |
| + if err := status.WriteBox(ctx, fx.rel, status.Box{GeneratedAt: now, Label: box, Region: "eu-west-1", |
| + Routes: status.RouteCounts{Static: 1, Resident: 1}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + at := now.UTC().Add(-time.Minute) |
| + writeChunk(t, fx.rel, box, metrics.HourOf(at), []metrics.Sample{{At: at, Host: metrics.HostSample{CPUFrac: p(0.5)}}}) |
| + } |
| + seedFleetJSON(t, fx) |
| + |
| + // One log chunk, one error chunk and one analytics day for kass. |
| + recs := []applog.Record{ |
| + {TS: now.Add(-10 * time.Minute), Box: "box-a", Host: "kass.carlosapp.dev", Stream: applog.StreamApp, Msg: "listening on socket", Seq: 100}, |
| + {TS: now.Add(-5 * time.Minute), Box: "box-a", Host: "kass.carlosapp.dev", Stream: applog.StreamPlatform, Level: applog.LevelError, |
| + Msg: "wake failed: nothing is promoted for this instance's channel", Seq: 101}, |
| + } |
| + body, err := applog.EncodeChunk(recs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, mustKey(t)(applog.ChunkKey(acct, "kass", "box-a", applog.HourOf(recs[0].TS), recs[0].Seq, len(body))), body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + errs := []apperr.Record{{TS: now.Add(-3 * time.Minute), Box: "box-a", Host: "kass.carlosapp.dev", |
| + Source: apperr.SourceEdge, Kind: apperr.KindHTTP, Name: "500 POST /checkout", Path: "/checkout", Status: 500, |
| + Release: "v1", FP: "edge500", FPV: 1, Count: 12, First: now.Add(-9 * time.Minute), Last: now.Add(-3 * time.Minute), Seq: 200}} |
| + eb, err := apperr.EncodeChunk(errs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, mustKey(t)(apperr.ChunkKey(acct, "kass", "box-a", apperr.HourOf(errs[0].TS), 200, len(eb))), eb, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + when := seedTime() |
| + m := analytics.NewMeter(t.TempDir(), "box-a", func() time.Time { return when }) |
| + for i := 0; i < 5; i++ { |
| + m.Observe(analytics.Obs{Acct: acct, App: "kass", Host: "kass.carlosapp.dev", Method: "GET", Status: 200, |
| + ContentType: "text/html", Path: "/pricing", RefererHost: "example.com", UA: "Mozilla/5.0 Safari", |
| + ClientIP: "203.0.113." + strconv.Itoa(i), Bytes: 1000, When: when}) |
| + } |
| + for k, ds := range m.Drain() { |
| + for _, d := range ds { |
| + if err := analytics.UpsertDay(ctx, fx.rel, k.Acct, k.App, d); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + |
| + // 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 |
| + // the walk and not after: the counts would depend on the clock. Age |
| + // them all half a minute, as a console that has been up a while sees. |
| + perfAgeObjects(t, fx, 30*time.Second) |
| + |
| + // 1,100 reports from boxes long gone, past the listing horizon: every |
| + // box listing is two pages, and none of them is read. |
| + perfSeedGoneBoxes(t, fx, 1100) |
| +} |
| + |
| +// perfAgeObjects sets every object's modification time in the fixture's |
| +// DirStore back by age. |
| +func perfAgeObjects(t *testing.T, fx *consoleFixture, age time.Duration) { |
| + t.Helper() |
| + at := time.Now().Add(-age) |
| + err := filepath.WalkDir(perfBucketRoot(t, fx), func(p string, de os.DirEntry, err error) error { |
| + if err != nil || de.IsDir() { |
| + return err |
| + } |
| + return os.Chtimes(p, at, at) |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// perfBucketRoot is the directory the fixture's DirStore keeps its objects in. |
| +func perfBucketRoot(t *testing.T, fx *consoleFixture) string { |
| + t.Helper() |
| + ds, ok := fx.rel.(*deletableStore) |
| + if !ok { |
| + t.Fatalf("fixture store is %T, want *deletableStore", fx.rel) |
| + } |
| + return ds.root |
| +} |
| + |
| +// perfSeedGoneBoxes writes n status/boxes/ reports straight to the |
| +// DirStore's files (Put fsyncs each one, which is slow at this count) and |
| +// ages them two days. |
| +func perfSeedGoneBoxes(t *testing.T, fx *consoleFixture, n int) { |
| + t.Helper() |
| + dir := filepath.Join(perfBucketRoot(t, fx), "status", "boxes") |
| + if err := os.MkdirAll(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + old := time.Now().Add(-48 * time.Hour) |
| + for i := 0; i < n; i++ { |
| + label := fmt.Sprintf("gone-%04d", i) |
| + path := filepath.Join(dir, label+".json") |
| + body := fmt.Sprintf(`{"generated_at":%q,"label":%q}`, old.UTC().Format(time.RFC3339), label) |
| + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Chtimes(path, old, old); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// perfTargets maps every screen with a path parameter, and every |
| +// parameter-less screen that does not answer 200 at its bare path, to the |
| +// requests the walk makes for it. |
| +func perfTargets(fx *consoleFixture) map[string][]perfTarget { |
| + seeds := perfSeedsOf(fx) |
| + app := fx.path("/apps/kass") |
| + ok := func(p string) []perfTarget { return []perfTarget{{Path: p, Expect: http.StatusOK}} } |
| + m := map[string][]perfTarget{ |
| + "GET /{$}": {{Path: "/", Expect: http.StatusFound}, {Path: "/", Expect: http.StatusOK, Anonymous: true}}, |
| + "GET /auth/signin": {{Path: "/auth/signin", Expect: http.StatusSeeOther, Anonymous: true}}, |
| + "GET /auth/confirm": ok("/auth/confirm"), |
| + "GET /auth/cli/tokens": {{Path: "/auth/cli/tokens", Expect: http.StatusSeeOther}}, |
| + "GET /auth/email/link": {{Path: "/auth/email/link?t=" + url.QueryEscape(seeds.emailLink), Expect: http.StatusOK, Anonymous: true}}, |
| + "GET /apps": {{Path: "/apps", Expect: http.StatusFound}}, |
| + "GET /apps/{app}": {{Path: "/apps/kass", Expect: http.StatusFound}}, |
| + "/fleet/architecture": ok("/fleet/architecture"), |
| + "GET /invite/{token}": ok("/invite/" + seeds.invite), |
| + "GET /a/{sqid}/{$}": ok(fx.path("/")), |
| + "GET /a/{sqid}/apps/new": ok(fx.path("/apps/new")), |
| + "GET /a/{sqid}/fleet": ok(fx.path("/fleet")), |
| + "GET /a/{sqid}/fleet/byo": ok(fx.path("/fleet/byo")), |
| + "GET /a/{sqid}/fleets/{fleet}": ok(fx.path("/fleets/fleet-a")), |
| + "GET /a/{sqid}/settings": ok(fx.path("/settings")), |
| + "GET /a/{sqid}/team": ok(fx.path("/team")), |
| + "GET /a/{sqid}/trash": ok(fx.path("/trash")), |
| + "GET /a/{sqid}/apps/{app}": ok(app), |
| + "GET /a/{sqid}/apps/{app}/instances/{host}": ok(app + "/instances/kass.carlosapp.dev"), |
| + } |
| + for _, tab := range []string{"account-review", "activity", "analytics", "availability", "deployments", "errors", |
| + "instances", "logs", "logs/data", "pipeline", "releases", "settings"} { |
| + m["GET /a/{sqid}/apps/{app}/"+tab] = ok(app + "/" + tab) |
| + } |
| + var sections []string |
| + for s := range appSettingsSections { |
| + sections = append(sections, s) |
| + } |
| + slices.Sort(sections) |
| + for _, s := range sections { |
| + m["GET /a/{sqid}/apps/{app}/settings/{section}"] = append(m["GET /a/{sqid}/apps/{app}/settings/{section}"], |
| + perfTarget{Path: app + "/settings/" + s, Expect: http.StatusOK}) |
| + } |
| + return m |
| +} |
| + |
| +// perfReadBudgets reads testdata/perf-budgets.txt for perfWalkTargets, |
| +// which has no test to fail; the walk loads it through loadPerfBudgets |
| +// first, so a bad file is reported there. |
| +func perfReadBudgets() map[string]perfRecord { |
| + f, err := os.Open("testdata/perf-budgets.txt") |
| + if err != nil { |
| + panic(err) |
| + } |
| + defer f.Close() |
| + recs, err := parsePerfBudgets(f) |
| + if err != nil { |
| + panic(fmt.Sprintf("testdata/perf-budgets.txt:\n%v", err)) |
| + } |
| + return recs |
| +} |
| + |
| +// perfWalkTargets is every request the walk makes, in inventory order: |
| +// each screen's perfTargets entries, or {its path, 200} for a screen |
| +// without parameters, with its budgets record. skip screens are left out. |
| +// A screen with parameters and no entry is left out too; the walk's |
| +// structural checks fail on it before anything is requested. |
| +func perfWalkTargets(fx *consoleFixture) []perfScreenTarget { |
| + recs := perfReadBudgets() |
| + targets := perfTargets(fx) |
| + var out []perfScreenTarget |
| + for _, screen := range perfInventory(fx.srv.claimEntries.snapshot()) { |
| + var rec *perfRecord |
| + if r, ok := recs[screen]; ok { |
| + rec = &r |
| + } |
| + if rec != nil && rec.Kind == "skip" { |
| + continue |
| + } |
| + ts, ok := targets[screen] |
| + if !ok { |
| + path, params := perfScreenPath(screen) |
| + if params { |
| + continue |
| + } |
| + ts = []perfTarget{{Path: path, Expect: http.StatusOK}} |
| + } |
| + for _, tg := range ts { |
| + out = append(out, perfScreenTarget{Screen: screen, Target: tg, Record: rec}) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// perfStructural is the walk's fixture checks, made before anything is |
| +// measured: a parameterised screen with no target, a target or record |
| +// naming no screen, a skip record on a screen that also has targets. |
| +func perfStructural(inventory []string, targets map[string][]perfTarget, recs map[string]perfRecord) []string { |
| + inInv := map[string]bool{} |
| + var problems []string |
| + for _, s := range inventory { |
| + inInv[s] = true |
| + _, has := targets[s] |
| + rec, hasRec := recs[s] |
| + if _, params := perfScreenPath(s); params && !has && !(hasRec && rec.Kind == "skip") { |
| + problems = append(problems, fmt.Sprintf("%s: has a path parameter and no perfTargets entry", s)) |
| + } |
| + if has && hasRec && rec.Kind == "skip" { |
| + problems = append(problems, fmt.Sprintf("%s: skip record (line %d) on a screen that also has perfTargets", s, rec.Line)) |
| + } |
| + } |
| + for _, s := range slices.Sorted(mapKeys(targets)) { |
| + if !inInv[s] { |
| + problems = append(problems, fmt.Sprintf("perfTargets names %q, which is not in the inventory: stale, delete it", s)) |
| + } |
| + } |
| + for _, s := range slices.Sorted(mapKeys(recs)) { |
| + if !inInv[s] { |
| + problems = append(problems, fmt.Sprintf("perf-budgets.txt line %d names %q, which is not in the inventory: stale, delete it", recs[s].Line, s)) |
| + } |
| + } |
| + return problems |
| +} |
| + |
| +func mapKeys[V any](m map[string]V) func(func(string) bool) { |
| + return func(yield func(string) bool) { |
| + for k := range m { |
| + if !yield(k) { |
| + return |
| + } |
| + } |
| + } |
| +} |
| + |
| +// 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 } |
| + |
| +func (c perfClients) of(tg perfTarget) *http.Client { |
| + if tg.Anonymous { |
| + return c.anon |
| + } |
| + return c.paul |
| +} |
| + |
| +// perfResult is one walked request's measurement. |
| +type perfResult struct { |
| + ttfb time.Duration |
| + status int |
| + s3, host int64 |
| + err error |
| + notIdle bool |
| + location string |
| + bodyStart string |
| +} |
| + |
| +// perfOnce makes one request and reads it to the end; TTFB is httptrace's |
| +// GotFirstResponseByte, as Rastrillo's perftest measures it. afterHeaders, |
| +// when set, runs as soon as the response headers are in (a cold request |
| +// turns latency off there). It then waits for the handler to return, runs |
| +// perfQuiesce, and reads the call delta. |
| +func perfOnce(fx *consoleFixture, lat *perfLatency, c *http.Client, tg perfTarget, afterHeaders func()) perfResult { |
| + seeds := perfSeedsOf(fx) |
| + s0, h0 := lat.Calls() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + var first time.Time |
| + ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotFirstResponseByte: func() { first = time.Now() }}) |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fx.ts.URL+tg.Path, nil) |
| + if err != nil { |
| + return perfResult{err: err} |
| + } |
| + start := time.Now() |
| + resp, err := c.Do(req) |
| + if afterHeaders != nil { |
| + afterHeaders() |
| + } |
| + if err != nil { |
| + return perfResult{err: err} |
| + } |
| + body, err := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + r := perfResult{ttfb: first.Sub(start), status: resp.StatusCode, err: err, location: resp.Header.Get("Location")} |
| + if len(body) > 300 { |
| + body = body[:300] |
| + } |
| + r.bodyStart = string(body) |
| + r.notIdle = !perfIdle(seeds.inflight, 2*time.Second) |
| + perfQuiesce(fx) |
| + s1, h1 := lat.Calls() |
| + r.s3, r.host = s1-s0, h1-h0 |
| + return r |
| +} |
| + |
| +// perfIdle waits up to grace for every handler to return. |
| +func perfIdle(inflight *atomic.Int32, grace time.Duration) bool { |
| + deadline := time.Now().Add(grace) |
| + for inflight.Load() > 0 { |
| + if time.Now().After(deadline) { |
| + return false |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + return true |
| +} |
| + |
| +func ms(d time.Duration) string { |
| + return strconv.FormatFloat(float64(d)/float64(time.Millisecond), 'f', 1, 64) |
| +} |
| + |
| +func TestConsoleScreensMeetTheBudget(t *testing.T) { |
| + began := time.Now() |
| + // Over-budget pages log a warning; keep it out of the test's output. |
| + logs := &syncBuffer{} |
| + prev := log.Writer() |
| + log.SetOutput(logs) |
| + t.Cleanup(func() { log.SetOutput(prev) }) |
| + |
| + fx, lat := newPerfFixture(t) |
| + recs := loadPerfBudgets(t) |
| + inventory := perfInventory(fx.srv.claimEntries.snapshot()) |
| + if problems := perfStructural(inventory, perfTargets(fx), recs); len(problems) > 0 { |
| + for _, p := range problems { |
| + t.Error(p) |
| + } |
| + t.FailNow() |
| + } |
| + clients := perfClients{paul: signInPaul(t, fx), anon: newBrowser(t)} |
| + enforce := perfEnforce() |
| + timing := func(format string, a ...any) { |
| + t.Helper() |
| + if enforce { |
| + t.Errorf(format, a...) |
| + } else { |
| + t.Logf("(not enforced locally) "+format, a...) |
| + } |
| + } |
| + check := func(label string, tg perfTarget, r perfResult) bool { |
| + t.Helper() |
| + switch { |
| + case r.err != nil: |
| + t.Errorf("%s: %v", label, r.err) |
| + case r.notIdle: |
| + t.Errorf("%s: a handler was still running 2s after its response", label) |
| + case r.status != tg.Expect: |
| + t.Errorf("%s: answered %d (Location %q), want %d: seed what it shows or set Expect:\n%s", label, r.status, r.location, tg.Expect, r.bodyStart) |
| + default: |
| + return true |
| + } |
| + return false |
| + } |
| + |
| + var table []string |
| + for _, w := range perfWalkTargets(fx) { |
| + tg := w.Target |
| + label := w.Screen + " " + tg.Path |
| + if tg.Anonymous { |
| + label += " (signed out)" |
| + } |
| + c := clients.of(tg) |
| + kind := "" |
| + if w.Record != nil { |
| + kind = w.Record.Kind |
| + } |
| + if kind == "over" { |
| + lat.Enable(false) |
| + var r perfResult |
| + for i := 0; i < 2; i++ { |
| + r = perfOnce(fx, lat, c, tg, nil) |
| + check(label, tg, r) |
| + } |
| + t.Logf("%s: over (%s): %d S3 and %d host calls warm", label, w.Record.Reason, r.s3, r.host) |
| + table = append(table, fmt.Sprintf("%s\t-\t-\t-\t%d+%d\tover", label, r.s3, r.host)) |
| + continue |
| + } |
| + |
| + cold, coldCalls := "-", "" |
| + if kind != "deferred" { |
| + perfColdReset(fx) |
| + lat.Enable(true) |
| + // Latency goes off once the headers are in and stays off until |
| + // perfQuiesce is done, so the background loads the cold view |
| + // started cost the test milliseconds. |
| + r := perfOnce(fx, lat, c, tg, func() { lat.Enable(false) }) |
| + if check(label+" (cold)", tg, r) { |
| + cold, coldCalls = ms(r.ttfb), fmt.Sprintf(" (%d+%d)", r.s3, r.host) |
| + if r.ttfb > perfBudget { |
| + timing("%s: cold first byte %sms, over %v", label, ms(r.ttfb), perfBudget) |
| + } |
| + } |
| + } |
| + |
| + lat.Enable(true) |
| + var ttfbs []time.Duration |
| + var maxCalls, maxS3, maxHost int64 |
| + good := true |
| + for i := 0; i < 10; i++ { |
| + r := perfOnce(fx, lat, c, tg, nil) |
| + if !check(label, tg, r) { |
| + good = false |
| + break |
| + } |
| + if i < 2 { |
| + continue |
| + } |
| + ttfbs = append(ttfbs, r.ttfb) |
| + if r.s3+r.host > maxCalls { |
| + maxCalls, maxS3, maxHost = r.s3+r.host, r.s3, r.host |
| + } |
| + } |
| + lat.Enable(false) |
| + if !good { |
| + continue |
| + } |
| + slices.Sort(ttfbs) |
| + median, worst := (ttfbs[3]+ttfbs[4])/2, ttfbs[len(ttfbs)-1] |
| + table = append(table, fmt.Sprintf("%s\t%s%s\t%s\t%s\t%d+%d\t%s", label, cold, coldCalls, ms(median), ms(worst), maxS3, maxHost, kind)) |
| + t.Logf("%s: cold %sms, median %sms, worst %sms, calls %d S3 + %d host", label, cold, ms(median), ms(worst), maxS3, maxHost) |
| + if kind == "deferred" { |
| + if worst > perfWorstBudget { |
| + timing("%s: worst first byte %sms, over %v", label, ms(worst), perfWorstBudget) |
| + } |
| + continue |
| + } |
| + allow := int64(0) |
| + if kind == "calls" { |
| + allow = int64(w.Record.Calls) |
| + } |
| + if maxCalls > allow { |
| + t.Errorf("%s: %d remote calls on a warm GET (%d S3, %d host), allowance %d: remove them, or record calls/over in testdata/perf-budgets.txt", |
| + label, maxCalls, maxS3, maxHost, allow) |
| + } |
| + if median > perfBudget { |
| + timing("%s: median first byte %sms, over %v", label, ms(median), perfBudget) |
| + } |
| + if worst > perfWorstBudget { |
| + timing("%s: worst first byte %sms, over %v", label, ms(worst), perfWorstBudget) |
| + } |
| + } |
| + t.Logf("screen\tcold ms\tmedian ms\tworst ms\tcalls (S3+host)\trecord\n%s", strings.Join(table, "\n")) |
| + total := time.Since(began) |
| + t.Logf("walk took %v", total.Round(time.Millisecond)) |
| + if enforce && total > perfTotalBudget { |
| + t.Errorf("the walk took %v, over %v", total.Round(time.Millisecond), perfTotalBudget) |
| + } |
| +} |
| + |
| +// perfSessionCeiling reads testdata/perf-session-s3.txt: one line, |
| +// "<n> <reason>". |
| +func perfSessionCeiling(t *testing.T) (int64, string, bool) { |
| + t.Helper() |
| + f, err := os.Open("testdata/perf-session-s3.txt") |
| + if os.IsNotExist(err) { |
| + return 0, "", false |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer f.Close() |
| + sc := bufio.NewScanner(f) |
| + for sc.Scan() { |
| + line := strings.TrimSpace(sc.Text()) |
| + if line == "" || strings.HasPrefix(line, "#") { |
| + continue |
| + } |
| + num, reason, _ := strings.Cut(line, " ") |
| + n, err := strconv.ParseInt(num, 10, 64) |
| + if err != nil || n < 0 || strings.TrimSpace(reason) == "" { |
| + t.Fatalf("testdata/perf-session-s3.txt: want \"<n> <reason>\", got %q", line) |
| + } |
| + return n, strings.TrimSpace(reason), true |
| + } |
| + t.Fatal("testdata/perf-session-s3.txt: no ceiling line") |
| + return 0, "", false |
| +} |
| + |
| +// TestPerfSessionS3Requests is the whole-session count the warm walk |
| +// cannot give: first views, deferred loads and a write's own reads. On |
| +// newPerfFixture with latency off, signed in as Paul, it runs a fixed |
| +// script and sums every S3 request the fake answers, with perfQuiesce |
| +// after each step so background loads are included, and holds the total |
| +// to the ceiling in testdata/perf-session-s3.txt. Counts are |
| +// deterministic, so this fails everywhere, not only in CI. |
| +func TestPerfSessionS3Requests(t *testing.T) { |
| + logs := &syncBuffer{} |
| + prev := log.Writer() |
| + log.SetOutput(logs) |
| + t.Cleanup(func() { log.SetOutput(prev) }) |
| + |
| + fx, lat := newPerfFixture(t) |
| + c := signInPaul(t, fx) |
| + seeds := perfSeedsOf(fx) |
| + var total int64 |
| + step := func(what string, do func() (int, string)) { |
| + t.Helper() |
| + s0, _ := lat.Calls() |
| + status, body := do() |
| + if !perfIdle(seeds.inflight, 2*time.Second) { |
| + t.Fatalf("%s: a handler was still running 2s after its response", what) |
| + } |
| + perfQuiesce(fx) |
| + s1, _ := lat.Calls() |
| + total += s1 - s0 |
| + t.Logf("%s: %d S3 requests", what, s1-s0) |
| + want := http.StatusOK |
| + if strings.HasPrefix(what, "POST ") { |
| + want = http.StatusSeeOther |
| + } |
| + if status != want { |
| + t.Fatalf("%s answered %d, want %d:\n%s", what, status, want, body) |
| + } |
| + } |
| + view := func(p string) { |
| + t.Helper() |
| + step("GET "+p, func() (int, string) { |
| + status, _, body := get(t, c, fx.ts.URL+p) |
| + return status, body |
| + }) |
| + } |
| + app := fx.path("/apps/kass") |
| + for _, tab := range []string{"", "/instances", "/deployments", "/releases", "/logs", "/errors", "/availability", "/analytics", "/activity"} { |
| + view(app + tab) |
| + view(app + tab) |
| + } |
| + for _, s := range slices.Sorted(mapKeys(appSettingsSections)) { |
| + view(app + "/settings/" + s) |
| + view(app + "/settings/" + s) |
| + } |
| + for _, p := range []string{"/", "/team", "/settings", "/trash"} { |
| + view(fx.path(p)) |
| + view(fx.path(p)) |
| + } |
| + csrf := sessionToken(t, fx, c) |
| + step("POST "+app+"/promote (v2 to stable)", func() (int, string) { |
| + status, _, body := postForm(t, c, fx.ts.URL+app+"/promote", |
| + url.Values{"csrf": {csrf}, "channel": {"stable"}, "version": {"v2"}, "confirmed": {"1"}}) |
| + return status, body |
| + }) |
| + if p := fx.channelVersion(t, "kass", "stable"); p.Version != "v2" { |
| + t.Fatalf("stable = %s after the promote, want v2", p.Version) |
| + } |
| + view(app) |
| + view(app + "/releases") |
| + |
| + ceiling, reason, ok := perfSessionCeiling(t) |
| + if !ok { |
| + t.Fatalf("the scripted session made %d S3 requests; testdata/perf-session-s3.txt is missing (want one line, \"<n> <reason>\")", total) |
| + } |
| + t.Logf("the scripted session made %d S3 requests (ceiling %d: %s)", total, ceiling, reason) |
| + if total > ceiling { |
| + t.Errorf("the scripted session made %d S3 requests, over the ceiling of %d in testdata/perf-session-s3.txt (%s)", total, ceiling, reason) |
| + } |
| +} |