carlos / platform Public

console: perf middleware around the mux; both renderers buffer so first byte includes the template

NewServer wraps s.mux directly in perf.Middleware (skipping /healthz) and
ServeHTTP serves that after the redirect-host branch, so every test built
on NewServer and cmd/console share one chain. Config.Perf lets cmd/console
share the recorder; nil makes one. PerfGroups and PerfBackground expose it.

render and renderCLI now go through writeTemplate: the template executes
into a pooled buffer, timed as the "render" span, before any header goes.
A failed template answers a plain 500 instead of half a page under a 200,
and the recorded first byte includes the template's time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev ed6599af18cb81c692548c68b5e3504994041f2e parent 1459c08
3 files changed, +218 −10
  • internal/console/authcli.go +1 −5
  • internal/console/perfwiring_test.go +149 −0
  • internal/console/server.go +68 −5
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 55aa45380..c1f0cd0c3 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1416,11 +1416,7 @@ type cliPage struct {
func (s *Server) renderCLI(w http.ResponseWriter, status int, name string, p cliPage) {
s.chrome(&p.page)
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(status)
- if err := templates.ExecuteTemplate(w, name, p); err != nil {
- log.Printf("console: render %s: %v", name, err)
- }
+ _ = s.writeTemplate(w, status, name, p)
}
// handleCLIApprovePage is where the printed link lands. A signed-out visitor
diff --git a/internal/console/perfwiring_test.go b/internal/console/perfwiring_test.go
new file mode 100644
index 000000000..2d7bc5be7
--- /dev/null
+++ b/internal/console/perfwiring_test.go
@@ -0,0 +1,149 @@
+package console
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/perf"
+)
+
+// The perf middleware is wired in NewServer, so these run through the
+// fixture's real Server: the same handler chain cmd/console serves.
+
+// perfGet fetches u with c and returns the response with its body read
+// and closed.
+func perfGet(t *testing.T, c *http.Client, u string) (*http.Response, string) {
+ t.Helper()
+ resp, err := c.Get(u)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ return resp, string(body)
+}
+
+func findGroup(groups []perf.Group, screen string) *perf.Group {
+ for i := range groups {
+ if groups[i].Screen == screen {
+ return &groups[i]
+ }
+ }
+ return nil
+}
+
+var serverTimingApp = regexp.MustCompile(`^app;dur=[0-9.]+`)
+
+func TestServerTimingOnAnAppPage(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ resp, _ := perfGet(t, c, fx.u("/apps/kass"))
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET app page = %d, want 200", resp.StatusCode)
+ }
+ st := resp.Header.Values("Server-Timing")
+ if len(st) != 1 {
+ t.Fatalf("Server-Timing headers = %q, want exactly one", st)
+ }
+ if !serverTimingApp.MatchString(st[0]) {
+ t.Errorf("Server-Timing = %q, want it to start app;dur=", st[0])
+ }
+ if !strings.Contains(st[0], "render;dur=") {
+ t.Errorf("Server-Timing = %q, want a render span", st[0])
+ }
+}
+
+func TestPerfGroupsByPattern(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ perfGet(t, c, fx.u("/apps/kass"))
+ groups := fx.srv.PerfGroups()
+ g := findGroup(groups, "GET /a/{sqid}/apps/{app}")
+ if g == nil || g.Method != "GET" {
+ t.Fatalf("no GET group for the app page pattern in %+v", groups)
+ }
+ for _, g := range groups {
+ if strings.Contains(g.Screen, "kass") {
+ t.Errorf("group screen %q carries a path segment", g.Screen)
+ }
+ }
+}
+
+func TestPerfGroupsMethodlessPattern(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ perfGet(t, c, fx.ts.URL+"/fleet/architecture")
+ if g := findGroup(fx.srv.PerfGroups(), "/fleet/architecture"); g == nil {
+ t.Fatalf("no group for /fleet/architecture in %+v", fx.srv.PerfGroups())
+ }
+}
+
+func TestPerfGroupsNeverCarryPaths(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := newBrowser(t)
+ perfGet(t, c, fx.ts.URL+"/invite/tok-abc123")
+ perfGet(t, c, fx.ts.URL+"/no/such/path")
+ groups := fx.srv.PerfGroups()
+ for _, g := range groups {
+ if strings.Contains(g.Screen, "tok-abc123") || strings.Contains(g.Screen, "/no/such/path") {
+ t.Errorf("group screen %q carries a path", g.Screen)
+ }
+ }
+ if findGroup(groups, "unmatched") == nil {
+ t.Errorf("no unmatched group in %+v", groups)
+ }
+ if findGroup(groups, "GET /invite/{token}") == nil {
+ t.Errorf("no group for the invite pattern in %+v", groups)
+ }
+}
+
+func TestHealthzIsNotMeasured(t *testing.T) {
+ fx := newConsoleFixture(t)
+ resp, _ := perfGet(t, newBrowser(t), fx.ts.URL+"/healthz")
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET /healthz = %d, want 200", resp.StatusCode)
+ }
+ if st := resp.Header.Values("Server-Timing"); len(st) != 0 {
+ t.Errorf("/healthz carries Server-Timing %q, want none", st)
+ }
+ for _, g := range fx.srv.PerfGroups() {
+ if strings.Contains(g.Screen, "healthz") {
+ t.Errorf("/healthz was measured: group %+v", g)
+ }
+ }
+}
+
+func TestRenderTemplateErrorAnswers500(t *testing.T) {
+ fx := newConsoleFixture(t)
+ check := func(name string, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ if rec.Code != http.StatusInternalServerError {
+ t.Errorf("%s: status = %d, want 500", name, rec.Code)
+ }
+ if strings.Contains(rec.Body.String(), "<html") {
+ t.Errorf("%s: body carries page chrome: %q", name, rec.Body.String())
+ }
+ }
+ rec := httptest.NewRecorder()
+ fx.srv.render(rec, http.StatusOK, "no-such-template", page{})
+ check("render", rec)
+ rec = httptest.NewRecorder()
+ fx.srv.renderCLI(rec, http.StatusOK, "no-such-template", cliPage{})
+ check("renderCLI", rec)
+}
+
+func TestCLIPagesAreTimed(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+ resp, _ := perfGet(t, c, fx.ts.URL+"/settings")
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET /settings = %d, want 200", resp.StatusCode)
+ }
+ if st := resp.Header.Get("Server-Timing"); !strings.Contains(st, "render;dur=") {
+ t.Errorf("Server-Timing = %q, want a render span", st)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index c351563ad..ec51e3a64 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -6,6 +6,7 @@
package console
import (
+ "bytes"
"context"
"crypto/ed25519"
"crypto/subtle"
@@ -49,6 +50,7 @@ import (
"github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/perf"
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/publicrelease"
@@ -870,6 +872,10 @@ type Config struct {
// existed. Set, every other account meets sidecarsPaused on the two
// doors that bring a sidecar into being (sidecarsgate.go).
SidecarAccounts []string
+ // Perf is the request-timing ring the console records into, shared
+ // with the S3 clients cmd/console builds so their calls count against
+ // the request that made them. nil: NewServer makes its own.
+ Perf *perf.Recorder
}
// Server is the console's http.Handler.
@@ -887,6 +893,10 @@ type Server struct {
claimBackendObserver func(backendEvent) // fixture recorder only
claimEntries claimInventory
claimWorkers map[string]func(context.Context)
+ // perf records every request but /healthz; handler is the mux wrapped
+ // in its middleware, and is what ServeHTTP serves (NewServer).
+ perf *perf.Recorder
+ handler http.Handler
// The console's move pass (movesrecovery.go): its clock (nil is
// time.Now; a TEST SEAM) and when each close was first seen due.
movesClock func() time.Time
@@ -1429,7 +1439,15 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// each other apart (relayops.go).
relayHolder: relayHolderID(),
scanQueue: objstore.NewQueueIndex(),
+ perf: cfg.Perf,
}
+ if s.perf == nil {
+ s.perf = &perf.Recorder{}
+ }
+ // The middleware wraps the mux directly, nothing between them: it reads
+ // the matched route pattern back from the request it handed the mux.
+ // Every test built on NewServer serves through this same chain.
+ s.handler = perf.Middleware(s.perf, perf.Options{Skip: consolePerfSkip})(s.mux)
s.seedScratch = startSeedScratch(cfg.SeedScratchDir)
if s.lookupTXT == nil {
s.lookupTXT = net.DefaultResolver.LookupTXT
@@ -1779,9 +1797,22 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, s.cfg.Origin+redirectTarget(r.URL), code)
return
}
- s.mux.ServeHTTP(w, r)
+ s.handler.ServeHTTP(w, r)
}
+// consolePerfSkip leaves /healthz unmeasured: a probe every few seconds
+// would crowd the console's real pages out of the ring. The console has no
+// static assets to skip (templates are embedded and CSS is inline).
+func consolePerfSkip(r *http.Request) bool { return r.URL.Path == "/healthz" }
+
+// PerfGroups summarises the requests the console has measured, by route
+// pattern and method.
+func (s *Server) PerfGroups() []perf.Group { return s.perf.Groups() }
+
+// PerfBackground counts the outbound requests, by span name, made outside
+// any measured request since the process started.
+func (s *Server) PerfBackground() map[string]int64 { return s.perf.Background() }
+
// redirectTarget is the path and query to hang off Origin: the request's own
// RequestURI, but only where that is the rooted path a browser sends. A
// request target may legally be rootless — `GET mailto:x@evil.com HTTP/1.1`
@@ -2205,15 +2236,47 @@ func (s *Server) render(w http.ResponseWriter, status int, name string, p page)
p.MismatchCopy = approvedMismatchCopy
p.SigninCopy = approvedSigninView
s.chrome(&p)
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(status)
- if err := templates.ExecuteTemplate(w, name, p); err != nil {
- log.Printf("console: render %s: %v", name, err)
+ if s.writeTemplate(w, status, name, p) != nil {
return
}
s.recordBannerNotice(p.planAcctID, p.planSeen, time.Now()) // plans 4a: the banner was served
}
+// templateBufs holds the buffers writeTemplate renders into. One grown past
+// maxPooledTemplateBuf is dropped rather than kept, so one huge page does
+// not pin its memory for the life of the process.
+var templateBufs = sync.Pool{New: func() any { return new(bytes.Buffer) }}
+
+const maxPooledTemplateBuf = 1 << 20
+
+// writeTemplate is the one place an HTML page is executed and sent, for both
+// renderers (render and renderCLI). The template runs into a buffer before
+// any header goes, so a template that fails part way answers a plain 500
+// rather than half a page under a 200, and the first byte the perf
+// middleware stamps comes after the template's work, which is timed as the
+// "render" span. The error is returned, already logged and answered.
+func (s *Server) writeTemplate(w http.ResponseWriter, status int, name string, data any) error {
+ buf := templateBufs.Get().(*bytes.Buffer)
+ buf.Reset()
+ defer func() {
+ if buf.Cap() <= maxPooledTemplateBuf {
+ templateBufs.Put(buf)
+ }
+ }()
+ end := perf.SpanFor(w, "render")
+ err := templates.ExecuteTemplate(buf, name, data)
+ end()
+ if err != nil {
+ log.Printf("console: render %s: %v", name, err)
+ http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
+ return err
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(status)
+ _, _ = w.Write(buf.Bytes())
+ return nil
+}
+
func (s *Server) renderMessage(w http.ResponseWriter, r *http.Request, status int, title, msg string) {
p := s.basePage(r)
p.Title = title