carlos / platform Public

perf: middleware, Server-Timing, spans by request, context, writer and HTTP doer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d413a7f974df63ca9969a4e1fd591e145ad98796 parent 2edd0b5
2 files changed, +1,059 −0
  • internal/perf/middleware.go +411 −0
  • internal/perf/middleware_test.go +648 −0
diff --git a/internal/perf/middleware.go b/internal/perf/middleware.go
new file mode 100644
index 000000000..a14ce2142
--- /dev/null
+++ b/internal/perf/middleware.go
@@ -0,0 +1,411 @@
+package perf
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Options configures Middleware. The zero value is usable.
+type Options struct {
+ // Screen names a request for grouping. Nil uses the pattern the
+ // ServeMux matched (r.Pattern), or "unmatched". Whatever it returns
+ // lands in log lines: never return anything taken from the path.
+ Screen func(*http.Request) string
+ // Skip leaves a request unmeasured. Nil skips /healthz only: a
+ // probe would crowd real pages out of the ring.
+ Skip func(*http.Request) bool
+ // Budget is the first-byte budget for a GET or HEAD; zero means
+ // DefaultBudget. Other methods have none and are never over.
+ Budget time.Duration
+ // Logger receives the over-budget warnings and the lost-route
+ // warning. Nil is slog.Default().
+ Logger *slog.Logger
+}
+
+// Middleware measures every request next serves that opts.Skip does
+// not skip, recording into c. Each measured response carries one
+// Server-Timing header: app (time to first byte), then each span that
+// ended before the first byte, by name.
+//
+// Mount it directly around the mux: it reads the matched pattern back
+// from the request it passed down, so middleware between the two that
+// copies the request hides the route (and is warned about, once).
+func Middleware(c *Recorder, opts Options) func(http.Handler) http.Handler {
+ if opts.Budget <= 0 {
+ opts.Budget = DefaultBudget
+ }
+ if opts.Logger == nil {
+ opts.Logger = slog.Default()
+ }
+ if opts.Skip == nil {
+ opts.Skip = defaultSkip
+ }
+ screenIsDefault := opts.Screen == nil
+ if screenIsDefault {
+ opts.Screen = defaultScreen
+ }
+ // lostRoute is the one warning that a request was served but its
+ // route pattern never reached the middleware. Once, because it is a
+ // wiring mistake, not an event.
+ lostRoute := &sync.Once{}
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if opts.Skip(r) {
+ next.ServeHTTP(w, r)
+ return
+ }
+ q, r2 := begin(c, w, r, &opts)
+ defer q.finish(r2, screenIsDefault, lostRoute)
+ next.ServeHTTP(q, r2)
+ })
+ }
+}
+
+func defaultSkip(r *http.Request) bool { return r.URL.Path == "/healthz" }
+
+func defaultScreen(r *http.Request) string {
+ // A CONNECT is the one request ServeMux answers with a redirect
+ // whose Pattern is the concrete destination path rather than a
+ // registered pattern, token and all. No console page is a CONNECT,
+ // so it is never named.
+ if r.Pattern != "" && r.Method != http.MethodConnect {
+ return r.Pattern
+ }
+ return "unmatched"
+}
+
+// method folds anything that is not a standard method into OTHER, so a
+// client inventing methods cannot mint unbounded groups.
+func method(m string) string {
+ switch m {
+ case "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "CONNECT":
+ return m
+ }
+ return "OTHER"
+}
+
+func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
+
+type contextKey struct{}
+
+// writer is the ResponseWriter wrapper and the request's measuring
+// state: it stamps the first byte, adds Server-Timing before the
+// headers go, and keeps Flush, Hijack and Unwrap working through it.
+//
+// It edits one header, once: Server-Timing, added to the real header
+// map in commit, before the real WriteHeader. Nothing else is written
+// to the map, and nothing after the headers have gone (that would be a
+// trailer).
+type writer struct {
+ http.ResponseWriter
+ recorder *Recorder
+ opts *Options
+ start time.Time
+
+ mu sync.Mutex
+ sample Sample
+ committed bool
+ // done is set once the sample is handed to the recorder. After it
+ // a span or a call changes nothing: the sample is the recorder's.
+ done bool
+}
+
+func begin(c *Recorder, w http.ResponseWriter, r *http.Request, opts *Options) (*writer, *http.Request) {
+ s := Sample{At: time.Now().UTC(), Method: method(r.Method)}
+ if r.Method == http.MethodGet || r.Method == http.MethodHead {
+ s.Budget = ms(opts.Budget)
+ }
+ q := &writer{ResponseWriter: w, recorder: c, opts: opts, start: time.Now(), sample: s}
+ r2 := r.WithContext(context.WithValue(r.Context(), contextKey{}, q))
+ // A mux outside this one may already have set Pattern. Cleared on
+ // this copy, so the pattern read back is the inner mux's or
+ // nothing: an inherited pattern would group every route under it
+ // when middleware between here and the mux copies the request, and
+ // the lost-route warning could never fire.
+ r2.Pattern = ""
+ return q, r2
+}
+
+func fromContext(ctx context.Context) *writer {
+ q, _ := ctx.Value(contextKey{}).(*writer)
+ return q
+}
+
+// Span starts timing one named part of the request's work and returns
+// the func that ends it; call it with defer. Spans of the same name add
+// up, so a loop of queries is one "db" span. Each name becomes a
+// Server-Timing metric, so keep names to a few fixed words ("db",
+// "render"), never a value. A span that ends after the first byte
+// counts in the sample but misses the header, which has gone; one that
+// ends after the handler returned counts nowhere. A no-op on a request
+// the middleware did not measure.
+func Span(r *http.Request, name string) func() { return SpanContext(r.Context(), name) }
+
+// SpanContext is Span for code that holds the request's context rather
+// than the request.
+func SpanContext(ctx context.Context, name string) func() {
+ if q := fromContext(ctx); q != nil {
+ return q.span(name)
+ }
+ return func() {}
+}
+
+// SpanFor is Span for code that holds only the ResponseWriter, perhaps
+// wrapped by other middleware: it finds the measuring writer by
+// following Unwrap. A no-op when there is none.
+func SpanFor(w http.ResponseWriter, name string) func() {
+ // Bounded, so a wrapper that unwraps to itself cannot hang a request.
+ for i := 0; w != nil && i < 64; i++ {
+ if q, ok := w.(*writer); ok {
+ return q.span(name)
+ }
+ u, ok := w.(interface{ Unwrap() http.ResponseWriter })
+ if !ok {
+ break
+ }
+ w = u.Unwrap()
+ }
+ return func() {}
+}
+
+// span starts a span and returns its end, which adds the elapsed time
+// once however often it is called.
+func (q *writer) span(name string) func() {
+ start := time.Now()
+ var once sync.Once
+ return func() {
+ once.Do(func() {
+ d := ms(time.Since(start))
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ if q.done {
+ return
+ }
+ if q.sample.Spans == nil {
+ q.sample.Spans = map[string]float64{}
+ }
+ q.sample.Spans[name] += d
+ })
+ }
+}
+
+// call counts one outbound request named name.
+func (q *writer) call(name string) {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ if q.done {
+ return
+ }
+ if q.sample.Calls == nil {
+ q.sample.Calls = map[string]int{}
+ }
+ q.sample.Calls[name]++
+}
+
+func (q *writer) WriteHeader(status int) {
+ // 1xx other than 101 are informational: more headers follow, and
+ // the real response has not started.
+ if status >= 100 && status < 200 && status != http.StatusSwitchingProtocols {
+ q.ResponseWriter.WriteHeader(status)
+ return
+ }
+ if q.commit(status) {
+ q.ResponseWriter.WriteHeader(status)
+ }
+}
+
+// commit stamps the first byte and writes Server-Timing while headers
+// can still change. It reports whether this call was the first.
+func (q *writer) commit(status int) bool {
+ q.mu.Lock()
+ defer q.mu.Unlock()
+ if q.committed {
+ return false
+ }
+ q.committed = true
+ q.sample.Status = status
+ q.sample.TTFB = ms(time.Since(q.start))
+ names := make([]string, 0, len(q.sample.Spans))
+ for name := range q.sample.Spans {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ var b strings.Builder
+ fmt.Fprintf(&b, "app;dur=%.3f", q.sample.TTFB)
+ for _, name := range names {
+ fmt.Fprintf(&b, ", %s;dur=%.3f", name, q.sample.Spans[name])
+ }
+ q.Header().Add("Server-Timing", b.String())
+ return true
+}
+
+func (q *writer) Write(b []byte) (int, error) {
+ q.commit(http.StatusOK)
+ return q.ResponseWriter.Write(b)
+}
+
+// Unwrap lets http.ResponseController reach the writer underneath.
+func (q *writer) Unwrap() http.ResponseWriter { return q.ResponseWriter }
+
+func (q *writer) Flush() { _ = q.FlushError() }
+
+// FlushError commits first: a stream's first flush is its first byte,
+// which is why a fast-starting stream passes its budget however long
+// it then runs.
+func (q *writer) FlushError() error {
+ q.commit(http.StatusOK)
+ return http.NewResponseController(q.ResponseWriter).Flush()
+}
+
+// Hijack hands the connection over; nothing may be written after, so
+// the sample is closed as a 101 without touching headers.
+func (q *writer) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ conn, rw, err := http.NewResponseController(q.ResponseWriter).Hijack()
+ if err == nil {
+ q.mu.Lock()
+ if !q.committed {
+ q.committed = true
+ q.sample.Status = http.StatusSwitchingProtocols
+ q.sample.TTFB = ms(time.Since(q.start))
+ }
+ q.mu.Unlock()
+ }
+ return conn, rw, err
+}
+
+// finish records the sample. A panic is recorded as a 500 and then
+// re-raised untouched: the recovery above this middleware owns the
+// response, and measuring must never change what a failure looks like.
+func (q *writer) finish(r *http.Request, screenIsDefault bool, lostRoute *sync.Once) {
+ p := recover()
+ q.mu.Lock()
+ committed := q.committed
+ if !committed && p != nil {
+ q.committed = true
+ q.sample.Status = http.StatusInternalServerError
+ q.sample.TTFB = ms(time.Since(q.start))
+ }
+ q.mu.Unlock()
+ if !committed && p == nil {
+ q.WriteHeader(http.StatusOK)
+ }
+ // Outside the lock: Screen is the caller's code.
+ screen := q.opts.Screen(r)
+ q.mu.Lock()
+ q.sample.Screen = screen
+ // A request that was served (not a 404 or 405, which match no
+ // route) yet reached here with no pattern had its pattern set on a
+ // copy: middleware between this and the mux called r.WithContext.
+ // Every route would then read as one "unmatched" group, so say so,
+ // once, rather than let the numbers mislead quietly.
+ lost := screenIsDefault && r.Pattern == "" &&
+ q.sample.Status != http.StatusNotFound && q.sample.Status != http.StatusMethodNotAllowed
+ q.sample.Total = ms(time.Since(q.start))
+ q.sample.Over = q.sample.Budget > 0 && q.sample.TTFB > q.sample.Budget
+ // Handed over once. From here the sample is the recorder's (add
+ // keeps its own copy of the maps), and done turns every later span
+ // and call into a no-op.
+ s := q.sample
+ q.sample = Sample{}
+ q.done = true
+ q.mu.Unlock()
+ if lost {
+ lostRoute.Do(func() {
+ q.opts.Logger.Warn("perf: a request was served but its route pattern never reached perf.Middleware; " +
+ "mount it directly around the mux, or every route groups as \"unmatched\"")
+ })
+ }
+ q.recorder.add(s, q.opts.Logger)
+ if p != nil {
+ panic(p)
+ }
+}
+
+// Doer is the one method of *http.Client that outbound calls use.
+type Doer interface {
+ Do(*http.Request) (*http.Response, error)
+}
+
+// TimeDoer wraps d so that each Do is one span named name and one count
+// in Calls[name] on the measured request the outgoing request's context
+// belongs to. On a context no measured request owns it counts into c's
+// background counts instead (a nil c drops the count). Counting is at
+// the HTTP boundary, so every page of a paginated listing is one count.
+//
+// The span stays open until the response body reaches EOF or is closed,
+// whichever comes first, so a prompt header followed by a slow body is
+// charged to name. A Do that fails ends the span at once. A nil d is
+// http.DefaultClient.
+func TimeDoer(d Doer, name string, c *Recorder) Doer {
+ if d == nil {
+ d = http.DefaultClient
+ }
+ return &timedDoer{d: d, name: name, c: c}
+}
+
+type timedDoer struct {
+ d Doer
+ name string
+ c *Recorder
+}
+
+func (t *timedDoer) Do(req *http.Request) (*http.Response, error) {
+ q := fromContext(req.Context())
+ if q == nil {
+ if t.c != nil {
+ t.c.countBackground(t.name)
+ }
+ return t.d.Do(req)
+ }
+ q.call(t.name)
+ end := q.span(t.name)
+ resp, err := t.d.Do(req)
+ if err != nil || resp == nil || resp.Body == nil || resp.Body == http.NoBody {
+ end()
+ return resp, err
+ }
+ body := &timedBody{ReadCloser: resp.Body, end: end}
+ if w, ok := resp.Body.(io.Writer); ok {
+ // A 101's body is the upgraded connection, read and written.
+ resp.Body = &timedReadWriteBody{timedBody: body, w: w}
+ } else {
+ resp.Body = body
+ }
+ return resp, nil
+}
+
+// timedBody ends its span at the first EOF or Close. end is idempotent.
+type timedBody struct {
+ io.ReadCloser
+ end func()
+}
+
+func (b *timedBody) Read(p []byte) (int, error) {
+ n, err := b.ReadCloser.Read(p)
+ if err == io.EOF {
+ b.end()
+ }
+ return n, err
+}
+
+func (b *timedBody) Close() error {
+ err := b.ReadCloser.Close()
+ b.end()
+ return err
+}
+
+type timedReadWriteBody struct {
+ *timedBody
+ w io.Writer
+}
+
+func (b *timedReadWriteBody) Write(p []byte) (int, error) { return b.w.Write(p) }
diff --git a/internal/perf/middleware_test.go b/internal/perf/middleware_test.go
new file mode 100644
index 000000000..1da404031
--- /dev/null
+++ b/internal/perf/middleware_test.go
@@ -0,0 +1,648 @@
+// These are unit tests, not acceptance: they drive the middleware with
+// a plain ServeMux and httptest, from outside the package. The console's
+// behaviour under the real server is covered by the tests that build it
+// with NewServer.
+package perf_test
+
+import (
+ "bufio"
+ "context"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/perf"
+)
+
+// quiet is a logger that drops everything, so over-budget warnings do
+// not clutter the test output.
+var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
+
+// serve runs one request through mux under the middleware and returns
+// the response and the samples recorded.
+func serve(t *testing.T, c *perf.Recorder, opts perf.Options, mux http.Handler, method, target string) (*httptest.ResponseRecorder, []perf.Sample) {
+ t.Helper()
+ if opts.Logger == nil {
+ opts.Logger = quiet
+ }
+ rec := httptest.NewRecorder()
+ perf.Middleware(c, opts)(mux).ServeHTTP(rec, httptest.NewRequest(method, target, nil))
+ return rec, c.Snapshot()
+}
+
+// only returns the one sample, failing if there is not exactly one.
+func only(t *testing.T, ss []perf.Sample) perf.Sample {
+ t.Helper()
+ if len(ss) != 1 {
+ t.Fatalf("samples = %d, want 1: %+v", len(ss), ss)
+ }
+ return ss[0]
+}
+
+// metric returns the dur of the named metric in a Server-Timing value
+// and how many times the name appears.
+func metric(t *testing.T, header, name string) (float64, int) {
+ t.Helper()
+ re := regexp.MustCompile(`(?:^|, )` + regexp.QuoteMeta(name) + `;dur=([0-9.]+)`)
+ all := re.FindAllStringSubmatch(header, -1)
+ if len(all) == 0 {
+ return 0, 0
+ }
+ v, err := strconv.ParseFloat(all[0][1], 64)
+ if err != nil {
+ t.Fatalf("parse %q: %v", all[0][1], err)
+ }
+ return v, len(all)
+}
+
+// TestServerTimingCarriesAppAndSpans: not acceptance. Two spans of one
+// name add up into one metric, and the sample is named by its pattern.
+func TestServerTimingCarriesAppAndSpans(t *testing.T) {
+ work := func(r *http.Request) { defer perf.Span(r, "db")(); time.Sleep(2 * time.Millisecond) }
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x/{id}", func(w http.ResponseWriter, r *http.Request) {
+ work(r)
+ work(r)
+ io.WriteString(w, "ok")
+ })
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x/abc")
+ st := rec.Header().Values("Server-Timing")
+ if len(st) != 1 {
+ t.Fatalf("Server-Timing values = %q, want exactly one", st)
+ }
+ if !strings.HasPrefix(st[0], "app;dur=") {
+ t.Fatalf("Server-Timing = %q, want it to start app;dur=", st[0])
+ }
+ db, n := metric(t, st[0], "db")
+ if n != 1 || db < 4 {
+ t.Fatalf("Server-Timing = %q: db appears %d times with %v, want once and at least 4", st[0], n, db)
+ }
+ if s := only(t, ss); s.Screen != "GET /x/{id}" {
+ t.Fatalf("Screen = %q, want GET /x/{id}", s.Screen)
+ }
+}
+
+// TestServerTimingSortsSpansByName: not acceptance. The header is app
+// first, then the spans in name order.
+func TestServerTimingSortsSpansByName(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ perf.Span(r, "render")()
+ perf.Span(r, "box")()
+ perf.Span(r, "db")()
+ w.WriteHeader(http.StatusNoContent)
+ })
+ var c perf.Recorder
+ rec, _ := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ re := regexp.MustCompile(`^app;dur=[0-9]+\.[0-9]{3}, box;dur=[0-9]+\.[0-9]{3}, db;dur=[0-9]+\.[0-9]{3}, render;dur=[0-9]+\.[0-9]{3}$`)
+ if st := rec.Header().Get("Server-Timing"); !re.MatchString(st) {
+ t.Fatalf("Server-Timing = %q, want app then box, db, render with three decimals", st)
+ }
+}
+
+// TestSpanContextReachesTheSample: not acceptance.
+func TestSpanContextReachesTheSample(t *testing.T) {
+ helper := func(ctx context.Context) { defer perf.SpanContext(ctx, "s3")() }
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ helper(r.Context())
+ io.WriteString(w, "ok")
+ })
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if _, n := metric(t, rec.Header().Get("Server-Timing"), "s3"); n != 1 {
+ t.Fatalf("Server-Timing = %q, want s3;dur=", rec.Header().Get("Server-Timing"))
+ }
+ if _, ok := only(t, ss).Spans["s3"]; !ok {
+ t.Fatalf("sample spans = %v, want s3", ss[0].Spans)
+ }
+}
+
+// wrapped is a ResponseWriter wrapper of the kind other middleware
+// adds, exposing the writer below through Unwrap.
+type wrapped struct{ http.ResponseWriter }
+
+func (w wrapped) Unwrap() http.ResponseWriter { return w.ResponseWriter }
+
+// TestSpanForFindsTheWriterThroughUnwrap: not acceptance.
+func TestSpanForFindsTheWriterThroughUnwrap(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ ww := wrapped{w}
+ perf.SpanFor(ww, "render")()
+ io.WriteString(ww, "ok")
+ })
+ var c perf.Recorder
+ rec, _ := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if _, n := metric(t, rec.Header().Get("Server-Timing"), "render"); n != 1 {
+ t.Fatalf("Server-Timing = %q, want render;dur=", rec.Header().Get("Server-Timing"))
+ }
+}
+
+// TestSpansOffAMeasuredRequestAreNoOps: not acceptance. A writer, request
+// or context the middleware never saw takes spans without complaint.
+func TestSpansOffAMeasuredRequestAreNoOps(t *testing.T) {
+ perf.Span(httptest.NewRequest("GET", "/", nil), "db")()
+ perf.SpanContext(context.Background(), "db")()
+ perf.SpanFor(httptest.NewRecorder(), "db")()
+ perf.SpanFor(wrapped{httptest.NewRecorder()}, "db")()
+}
+
+// TestTimeDoerSpansAndCountsEachCall: not acceptance.
+func TestTimeDoerSpansAndCountsEachCall(t *testing.T) {
+ box := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(time.Millisecond)
+ io.WriteString(w, "pong")
+ }))
+ defer box.Close()
+ var c perf.Recorder
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ d := perf.TimeDoer(http.DefaultClient, "box", &c)
+ for i := 0; i < 2; i++ {
+ req, _ := http.NewRequest("GET", box.URL, nil)
+ resp, err := d.Do(req.WithContext(r.Context()))
+ if err != nil {
+ t.Errorf("Do: %v", err)
+ return
+ }
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ io.WriteString(w, "ok")
+ })
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ s := only(t, ss)
+ if s.Spans["box"] <= 0 || s.Calls["box"] != 2 {
+ t.Fatalf("spans %v calls %v, want box positive and 2 calls", s.Spans, s.Calls)
+ }
+ if _, n := metric(t, rec.Header().Get("Server-Timing"), "box"); n != 1 {
+ t.Fatalf("Server-Timing = %q, want one box;dur=", rec.Header().Get("Server-Timing"))
+ }
+ if bg := c.Background(); len(bg) != 0 {
+ t.Fatalf("background = %v, want none", bg)
+ }
+}
+
+// TestTimeDoerSpanCoversASlowBody: not acceptance. The span runs to the
+// body's EOF, not to the response headers; a body closed unread ends it
+// at the close.
+func TestTimeDoerSpanCoversASlowBody(t *testing.T) {
+ box := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ w.(http.Flusher).Flush()
+ if r.URL.Path == "/hang" {
+ // Held until the client gives up on the body.
+ select {
+ case <-r.Context().Done():
+ case <-time.After(5 * time.Second):
+ }
+ return
+ }
+ time.Sleep(30 * time.Millisecond)
+ io.WriteString(w, "slow body")
+ }))
+ defer box.Close()
+
+ t.Run("read to EOF", func(t *testing.T) {
+ var c perf.Recorder
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ req, _ := http.NewRequestWithContext(r.Context(), "GET", box.URL+"/slow", nil)
+ resp, err := perf.TimeDoer(nil, "box", &c).Do(req)
+ if err != nil {
+ t.Errorf("Do: %v", err)
+ return
+ }
+ b, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if string(b) != "slow body" {
+ t.Errorf("body = %q", b)
+ }
+ io.WriteString(w, "ok")
+ })
+ _, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if got := only(t, ss).Spans["box"]; got < 30 {
+ t.Fatalf("box span = %v ms, want at least 30 (it must cover the body)", got)
+ }
+ })
+
+ t.Run("closed unread", func(t *testing.T) {
+ var c perf.Recorder
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ req, _ := http.NewRequestWithContext(r.Context(), "GET", box.URL+"/hang", nil)
+ resp, err := perf.TimeDoer(nil, "box", &c).Do(req)
+ if err != nil {
+ t.Errorf("Do: %v", err)
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ resp.Body.Close()
+ resp.Body.Close() // a second close ends nothing twice
+ io.WriteString(w, "ok")
+ })
+ _, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ s := only(t, ss)
+ if got := s.Spans["box"]; got < 20 || got > 2000 {
+ t.Fatalf("box span = %v ms, want it to end at the close, about 20", got)
+ }
+ if s.Calls["box"] != 1 {
+ t.Fatalf("calls = %v, want 1", s.Calls)
+ }
+ })
+}
+
+// failing is a Doer whose every call fails.
+type failing struct{}
+
+func (failing) Do(*http.Request) (*http.Response, error) { return nil, io.ErrUnexpectedEOF }
+
+// TestTimeDoerErrorEndsTheSpan: not acceptance. A failed call is still a
+// call, and its span ends at once.
+func TestTimeDoerErrorEndsTheSpan(t *testing.T) {
+ var c perf.Recorder
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ req, _ := http.NewRequestWithContext(r.Context(), "GET", "http://example.com/", nil)
+ if _, err := perf.TimeDoer(failing{}, "box", &c).Do(req); err != io.ErrUnexpectedEOF {
+ t.Errorf("err = %v, want the doer's own", err)
+ }
+ io.WriteString(w, "ok")
+ })
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if s := only(t, ss); s.Calls["box"] != 1 {
+ t.Fatalf("calls = %v, want 1", s.Calls)
+ }
+ if _, n := metric(t, rec.Header().Get("Server-Timing"), "box"); n != 1 {
+ t.Fatalf("Server-Timing = %q, want box;dur= (the span ended before the header)", rec.Header().Get("Server-Timing"))
+ }
+}
+
+// TestTimeDoerCountsBackgroundCalls: not acceptance.
+func TestTimeDoerCountsBackgroundCalls(t *testing.T) {
+ box := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "pong")
+ }))
+ defer box.Close()
+ var c perf.Recorder
+ d := perf.TimeDoer(http.DefaultClient, "box", &c)
+ for i := 0; i < 2; i++ {
+ req, _ := http.NewRequestWithContext(context.Background(), "GET", box.URL, nil)
+ resp, err := d.Do(req)
+ if err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ if got := c.Background()["box"]; got != 2 {
+ t.Fatalf("background box = %d, want 2", got)
+ }
+ if ss := c.Snapshot(); len(ss) != 0 {
+ t.Fatalf("samples = %+v, want none", ss)
+ }
+ // A nil Recorder drops the count rather than panicking.
+ req, _ := http.NewRequestWithContext(context.Background(), "GET", box.URL, nil)
+ resp, err := perf.TimeDoer(nil, "box", nil).Do(req)
+ if err != nil {
+ t.Fatalf("Do with nil recorder: %v", err)
+ }
+ resp.Body.Close()
+}
+
+// TestOverBudgetIsJudgedOnFirstByte: not acceptance.
+func TestOverBudgetIsJudgedOnFirstByte(t *testing.T) {
+ opts := perf.Options{Budget: 20 * time.Millisecond}
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /stream", func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "first")
+ w.(http.Flusher).Flush()
+ time.Sleep(50 * time.Millisecond)
+ io.WriteString(w, "rest")
+ })
+ mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(50 * time.Millisecond)
+ io.WriteString(w, "late")
+ })
+ mux.HandleFunc("POST /slow", func(w http.ResponseWriter, r *http.Request) {
+ time.Sleep(50 * time.Millisecond)
+ io.WriteString(w, "late")
+ })
+
+ var a perf.Recorder
+ _, ss := serve(t, &a, opts, mux, "GET", "/stream")
+ if s := only(t, ss); s.Over || s.Budget != 20 || s.Total < 50 {
+ t.Fatalf("stream sample = %+v, want not over, budget 20, total at least 50", s)
+ }
+ var b perf.Recorder
+ _, ss = serve(t, &b, opts, mux, "GET", "/slow")
+ if s := only(t, ss); !s.Over || s.TTFB < 50 {
+ t.Fatalf("slow GET sample = %+v, want over with ttfb at least 50", s)
+ }
+ var p perf.Recorder
+ _, ss = serve(t, &p, opts, mux, "POST", "/slow")
+ if s := only(t, ss); s.Over || s.Budget != 0 {
+ t.Fatalf("POST sample = %+v, want not over and budget 0", s)
+ }
+}
+
+// TestDefaultBudgetAppliesToReads: not acceptance. A zero Budget is
+// DefaultBudget, for GET and HEAD alike.
+func TestDefaultBudgetAppliesToReads(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) {})
+ for _, m := range []string{"GET", "HEAD"} {
+ var c perf.Recorder
+ _, ss := serve(t, &c, perf.Options{}, mux, m, "/x")
+ if s := only(t, ss); s.Budget != float64(perf.DefaultBudget/time.Millisecond) || s.Method != m {
+ t.Fatalf("%s sample = %+v, want budget %v", m, s, perf.DefaultBudget)
+ }
+ }
+}
+
+// TestUnknownMethodsFoldToOther: not acceptance.
+func TestUnknownMethodsFoldToOther(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) {})
+ var c perf.Recorder
+ _, ss := serve(t, &c, perf.Options{}, mux, "BREW", "/x")
+ if s := only(t, ss); s.Method != "OTHER" || s.Budget != 0 {
+ t.Fatalf("sample = %+v, want method OTHER and no budget", s)
+ }
+}
+
+// TestSkipLeavesHealthzUnmeasured: not acceptance.
+func TestSkipLeavesHealthzUnmeasured(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") })
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/healthz")
+ if len(ss) != 0 {
+ t.Fatalf("samples = %+v, want none", ss)
+ }
+ if st := rec.Header().Values("Server-Timing"); len(st) != 0 {
+ t.Fatalf("Server-Timing = %q, want none", st)
+ }
+ if rec.Body.String() != "ok" {
+ t.Fatalf("body = %q, want the handler still to run", rec.Body.String())
+ }
+}
+
+// TestUnmatchedPathsGroupAsUnmatched: not acceptance. A 404 is named
+// "unmatched", never by its path.
+func TestUnmatchedPathsGroupAsUnmatched(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {})
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/secret/abc123")
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("code = %d, want 404", rec.Code)
+ }
+ if s := only(t, ss); s.Screen != "unmatched" || s.Status != http.StatusNotFound {
+ t.Fatalf("sample = %+v, want screen unmatched and status 404", s)
+ }
+}
+
+// TestConnectIsUnmatched: not acceptance. ServeMux answers a CONNECT
+// with a Pattern that is a concrete path, so it is never used.
+func TestConnectIsUnmatched(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/x/", func(w http.ResponseWriter, r *http.Request) {})
+ var c perf.Recorder
+ _, ss := serve(t, &c, perf.Options{}, mux, "CONNECT", "/x/secret")
+ if s := only(t, ss); s.Screen != "unmatched" {
+ t.Fatalf("screen = %q, want unmatched", s.Screen)
+ }
+}
+
+// TestInheritedPatternIsCleared: not acceptance. An outer mux has set
+// Pattern ("/") already; the middleware clears it on the copy it passes
+// down, so the inner mux's pattern names the sample, and when a copier
+// between perf and the inner mux hides that pattern the sample reads
+// "unmatched" rather than the inherited "/".
+func TestInheritedPatternIsCleared(t *testing.T) {
+ inner := http.NewServeMux()
+ inner.HandleFunc("GET /x/{id}", func(w http.ResponseWriter, r *http.Request) {})
+ copier := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ inner.ServeHTTP(w, r.WithContext(r.Context()))
+ })
+ for _, tc := range []struct {
+ name string
+ next http.Handler
+ want string
+ }{
+ {"direct", inner, "GET /x/{id}"},
+ {"through a copier", copier, "unmatched"},
+ } {
+ var c perf.Recorder
+ outer := http.NewServeMux()
+ outer.Handle("/", perf.Middleware(&c, perf.Options{Logger: quiet})(tc.next))
+ outer.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/x/1", nil))
+ if s := only(t, c.Snapshot()); s.Screen != tc.want {
+ t.Fatalf("%s: screen = %q, want %q", tc.name, s.Screen, tc.want)
+ }
+ }
+}
+
+// TestLostRouteWarnsOnce: not acceptance. Middleware between perf and
+// the mux that copies the request hides the pattern; that is said once.
+func TestLostRouteWarnsOnce(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {})
+ copier := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mux.ServeHTTP(w, r.WithContext(r.Context()))
+ })
+ var buf strings.Builder
+ var mu sync.Mutex
+ log := slog.New(slog.NewTextHandler(lockedWriter{&mu, &buf}, nil))
+ var c perf.Recorder
+ h := perf.Middleware(&c, perf.Options{Logger: log})(copier)
+ for i := 0; i < 3; i++ {
+ h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/x", nil))
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if n := strings.Count(buf.String(), "route pattern never reached"); n != 1 {
+ t.Fatalf("lost-route warnings = %d, want 1: %s", n, buf.String())
+ }
+}
+
+type lockedWriter struct {
+ mu *sync.Mutex
+ w io.Writer
+}
+
+func (l lockedWriter) Write(b []byte) (int, error) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.w.Write(b)
+}
+
+// TestPanicIsRecordedAndReraised: not acceptance.
+func TestPanicIsRecordedAndReraised(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) { panic("boom") })
+ var c perf.Recorder
+ h := perf.Middleware(&c, perf.Options{Logger: quiet})(mux)
+ rec := httptest.NewRecorder()
+ func() {
+ defer func() {
+ if p := recover(); p != "boom" {
+ t.Fatalf("recovered %v, want boom", p)
+ }
+ }()
+ h.ServeHTTP(rec, httptest.NewRequest("GET", "/x", nil))
+ t.Fatal("ServeHTTP returned, want a panic")
+ }()
+ if s := only(t, c.Snapshot()); s.Status != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want 500", s.Status)
+ }
+ if st := rec.Header().Values("Server-Timing"); len(st) != 0 {
+ t.Fatalf("Server-Timing = %q, want none: the recovery above owns the response", st)
+ }
+}
+
+// TestLateSpanDoesNotTouchRecordedSample: not acceptance. A span a
+// goroutine ends after the handler returned changes nothing recorded.
+func TestLateSpanDoesNotTouchRecordedSample(t *testing.T) {
+ done := make(chan struct{})
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ perf.Span(r, "db")() // one span inside the handler, so the map exists
+ end := perf.Span(r, "db")
+ endCtx := perf.SpanContext(r.Context(), "late")
+ endFor := perf.SpanFor(w, "late2")
+ go func() {
+ defer close(done)
+ time.Sleep(20 * time.Millisecond)
+ end()
+ endCtx()
+ endFor()
+ perf.Span(r, "after")()
+ }()
+ io.WriteString(w, "ok")
+ })
+ var c perf.Recorder
+ rec, before := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ header := rec.Header().Get("Server-Timing")
+ <-done
+ after := c.Snapshot()
+ if !reflect.DeepEqual(before, after) {
+ t.Fatalf("sample changed after the handler returned:\nbefore %+v\nafter %+v", before, after)
+ }
+ if got := rec.Header().Get("Server-Timing"); got != header {
+ t.Fatalf("Server-Timing changed after commit: %q then %q", header, got)
+ }
+ if _, n := metric(t, header, "late"); n != 0 {
+ t.Fatalf("Server-Timing = %q, want no late span", header)
+ }
+}
+
+// TestSpanAfterFirstByteCountsButMissesTheHeader: not acceptance.
+func TestSpanAfterFirstByteCountsButMissesTheHeader(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "first")
+ perf.Span(r, "render")()
+ })
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if _, n := metric(t, rec.Header().Get("Server-Timing"), "render"); n != 0 {
+ t.Fatalf("Server-Timing = %q, want no render (it ended after the header went)", rec.Header().Get("Server-Timing"))
+ }
+ if _, ok := only(t, ss).Spans["render"]; !ok {
+ t.Fatalf("spans = %v, want render in the sample", ss[0].Spans)
+ }
+}
+
+// TestInformationalHeadersPassThrough: not acceptance. A 103 goes out
+// without committing; the real status and Server-Timing follow.
+func TestInformationalHeadersPassThrough(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusEarlyHints)
+ perf.Span(r, "db")()
+ w.WriteHeader(http.StatusAccepted)
+ })
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if s := only(t, ss); s.Status != http.StatusAccepted {
+ t.Fatalf("status = %d, want 202", s.Status)
+ }
+ if _, n := metric(t, rec.Header().Get("Server-Timing"), "db"); n != 1 {
+ t.Fatalf("Server-Timing = %q, want db (the 103 did not commit)", rec.Header().Get("Server-Timing"))
+ }
+}
+
+// TestFlushAndHijackStillWork: not acceptance.
+func TestFlushAndHijackStillWork(t *testing.T) {
+ t.Run("flush", func(t *testing.T) {
+ var flushErr error
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /x", func(w http.ResponseWriter, r *http.Request) {
+ flushErr = http.NewResponseController(w).Flush()
+ })
+ var c perf.Recorder
+ rec, ss := serve(t, &c, perf.Options{}, mux, "GET", "/x")
+ if flushErr != nil {
+ t.Fatalf("Flush: %v", flushErr)
+ }
+ if !rec.Flushed || rec.Header().Get("Server-Timing") == "" {
+ t.Fatalf("flushed %v, Server-Timing %q: want flushed with the header", rec.Flushed, rec.Header().Get("Server-Timing"))
+ }
+ if s := only(t, ss); s.Status != http.StatusOK {
+ t.Fatalf("status = %d, want 200", s.Status)
+ }
+ })
+
+ t.Run("hijack", func(t *testing.T) {
+ var c perf.Recorder
+ recorded := make(chan struct{})
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /ws", func(w http.ResponseWriter, r *http.Request) {
+ conn, rw, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ t.Errorf("Hijack: %v", err)
+ return
+ }
+ defer conn.Close()
+ rw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n")
+ rw.Flush()
+ })
+ inner := perf.Middleware(&c, perf.Options{Logger: quiet})(mux)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer close(recorded)
+ inner.ServeHTTP(w, r)
+ }))
+ defer srv.Close()
+ conn, err := net.Dial("tcp", srv.Listener.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ io.WriteString(conn, "GET /ws HTTP/1.1\r\nHost: example.com\r\nConnection: Upgrade\r\nUpgrade: test\r\n\r\n")
+ line, err := bufio.NewReader(conn).ReadString('\n')
+ if err != nil || !strings.HasPrefix(line, "HTTP/1.1 101") {
+ t.Fatalf("status line %q, err %v", line, err)
+ }
+ select {
+ case <-recorded:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the handler never returned")
+ }
+ if s := only(t, c.Snapshot()); s.Status != http.StatusSwitchingProtocols {
+ t.Fatalf("status = %d, want 101", s.Status)
+ }
+ })
+}