Skip to content
quarry Artifact [7bfc46e8ff]
Login

Artifact [7bfc46e8ff]

Artifact 7bfc46e8ffe4ce7c1df4e9f9ee887b90b9d384b260b2ec0eb1cd8540b031b88e:


package web

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"craftdesign.group/quarry/internal/obs"
)

// A live stream is not a slow page. chat, the timeline and the ops
// panel hold a connection open for as long as the reader keeps the tab,
// so a stream's "duration" is that tab's lifetime. The fleet recorded
// timeline.sse at a p95 of 435 SECONDS, which headed the slowest-routes
// panel and buried every real finding under it.
//
// The second consequence was worse: every stream crosses the render
// budget by design, so the first-crossing alert fired on connections
// that were working perfectly — the muted-channel failure that rule
// exists to prevent, defeated from inside the same feature.
func TestStreamsAreNotRecordedAsRenders(t *testing.T) {
	for _, ct := range []string{
		"text/event-stream",
		"text/event-stream; charset=utf-8", // the charset must not defeat it
	} {
		if !isStream(ct) {
			t.Errorf("isStream(%q) = false, want true", ct)
		}
	}
	for _, ct := range []string{"text/html; charset=utf-8", "application/json", ""} {
		if isStream(ct) {
			t.Errorf("isStream(%q) = true, want false — an ordinary page must still be measured", ct)
		}
	}
}

// End to end through the middleware: a streaming handler files nothing,
// an ordinary one files a render.
func TestWithTimerSkipsStreamsAndKeepsPages(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /stream", func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/event-stream")
		w.Write([]byte("data: hi\n\n"))
	})
	mux.HandleFunc("GET /page", func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write([]byte("<p>hi</p>"))
	})

	// The middleware records into the process recorder; swap in a fresh
	// one so this test reads only its own traffic.
	saved := obs.Default
	obs.Default = obs.NewRecorder(16, nil)
	defer func() { obs.Default = saved }()

	h := withTimer(mux, mux)
	for _, path := range []string{"/stream", "/page", "/page"} {
		h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", path, nil))
	}

	snap := obs.Default.Snapshot()
	for _, p := range snap.Paths {
		if p.Path == "GET /stream" {
			t.Errorf("a stream was filed as a render: %+v", p)
		}
	}
	var pages int
	for _, p := range snap.Paths {
		if p.Path == "GET /page" {
			pages = p.N
		}
	}
	if pages != 2 {
		t.Errorf("ordinary renders recorded = %d, want 2 — the fix must not silence real pages", pages)
	}
}