diff --git a/main.go b/main.go index da833f1..52e1a47 100644 --- a/main.go +++ b/main.go @@ -136,6 +136,7 @@ func main() { // routes mux := relay.Router() mux.Handle("/njump/static/", http.StripPrefix("/njump/", http.FileServer(http.FS(static)))) + mux.HandleFunc("/debug/metrics", renderMetrics) sub := http.NewServeMux() sub.HandleFunc("/services/oembed", renderOEmbed) diff --git a/metrics.go b/metrics.go new file mode 100644 index 0000000..45f7e92 --- /dev/null +++ b/metrics.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "net/http" +) + +func renderMetrics(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; version=0.0.4") + w.Header().Set("Cache-Control", "no-store") + + fmt.Fprintln(w, "# HELP queue_in_course_size Number of in-flight requests tracked by the queue middleware.") + fmt.Fprintln(w, "# TYPE queue_in_course_size gauge") + fmt.Fprintf(w, "queue_in_course_size %d\n", inCourse.Size()) +} diff --git a/metrics_test.go b/metrics_test.go new file mode 100644 index 0000000..ff5148d --- /dev/null +++ b/metrics_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestRenderMetricsReportsQueueSize(t *testing.T) { + resetQueueState(t) + + const sampleSize = 3 + for i := 0; i < sampleSize; i++ { + inCourse.Store(uint64(i+1), struct{}{}) + } + + req := httptest.NewRequest(http.MethodGet, "/debug/metrics", nil) + rec := httptest.NewRecorder() + + renderMetrics(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("expected status 200, got %d", rec.Code) + } + + body := rec.Body.String() + if !strings.Contains(body, "queue_in_course_size 3") { + t.Fatalf("expected metric output to contain size 3, got %q", body) + } +} diff --git a/opengraph_test.go b/opengraph_test.go index 1e09565..56dddcd 100644 --- a/opengraph_test.go +++ b/opengraph_test.go @@ -3,6 +3,7 @@ package main import ( "fmt" "io" + "net/http" "net/http/httptest" "os" "strings" @@ -32,13 +33,12 @@ func TestMain(m *testing.M) { func TestHomePage(t *testing.T) { r := httptest.NewRequest("GET", "/", nil) w := httptest.NewRecorder() - renderEvent(w, r) + renderHomepage(w, r) if w.Code != 200 { t.Fatal("homepage is not 200") } - if !strings.Contains(w.Body.String(), "