| 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) |
| + } |
| + }) |
| +} |