Antonio Mika
·
2026-10-25
1package router
2
3import (
4 "bufio"
5 "context"
6 "net"
7 "net/http"
8 "strconv"
9 "time"
10
11 lru "github.com/hashicorp/golang-lru/v2"
12 "github.com/prometheus/client_golang/prometheus"
13 "github.com/prometheus/client_golang/prometheus/promauto"
14)
15
16// UserMetricsOpts tells UserMetrics who a request belongs to when no
17// handler called SetUser, such as a response served from a cache.
18type UserMetricsOpts struct {
19 // SiteUser names the owner of the site a request is for, without
20 // checking that the user exists.
21 SiteUser func(r *http.Request) string
22 // TrustSuccess counts a SiteUser as real once its site returns a
23 // success, for a proxy that can't look users up. Only safe when every
24 // route on a site's host fails for a site that doesn't exist.
25 TrustSuccess bool
26}
27
28// UserMetrics counts HTTP requests, latency and response bytes for each
29// site owner. Every app shares the metric names and sets the app label, so
30// queries can aggregate across services.
31type UserMetrics struct {
32 requests *prometheus.CounterVec
33 duration *prometheus.HistogramVec
34 bytes *prometheus.CounterVec
35 opts UserMetricsOpts
36 // known holds the users a handler or a successful response confirmed.
37 // A name from the Host header alone never becomes a label, so made-up
38 // subdomains can't add series.
39 known *lru.Cache[string, struct{}]
40}
41
42func NewUserMetrics(app string, reg prometheus.Registerer, opts UserMetricsOpts) *UserMetrics {
43 auto := promauto.With(reg)
44 known, _ := lru.New[string, struct{}](16384)
45 return &UserMetrics{
46 requests: auto.NewCounterVec(prometheus.CounterOpts{
47 Namespace: "pico",
48 Subsystem: "http",
49 ConstLabels: prometheus.Labels{"app": app},
50 Name: "requests_total",
51 Help: "Number of HTTP requests handled.",
52 }, []string{"user", "status", "method"}),
53 duration: auto.NewHistogramVec(prometheus.HistogramOpts{
54 Namespace: "pico",
55 Subsystem: "http",
56 ConstLabels: prometheus.Labels{"app": app},
57 Name: "request_duration_seconds",
58 Help: "Duration of HTTP requests in seconds.",
59 Buckets: prometheus.DefBuckets,
60 }, []string{"user", "status", "method"}),
61 bytes: auto.NewCounterVec(prometheus.CounterOpts{
62 Namespace: "pico",
63 Subsystem: "http",
64 ConstLabels: prometheus.Labels{"app": app},
65 Name: "response_bytes_total",
66 Help: "Number of response body bytes sent.",
67 }, []string{"user"}),
68 opts: opts,
69 known: known,
70 }
71}
72
73type ctxUserKey struct{}
74
75// SetUser records name as the user a request belongs to. Handlers call it
76// once they've found the user in the database.
77func SetUser(r *http.Request, name string) {
78 if user, ok := r.Context().Value(ctxUserKey{}).(*string); ok {
79 *user = name
80 }
81}
82
83func (m *UserMetrics) Handler(next http.Handler) http.Handler {
84 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
85 start := time.Now()
86 var user string
87 mw := &metricsWriter{ResponseWriter: w}
88 next.ServeHTTP(mw, r.WithContext(context.WithValue(r.Context(), ctxUserKey{}, &user)))
89
90 status := mw.Status()
91 user = m.resolveUser(r, user, status)
92 labels := []string{user, strconv.Itoa(status), metricMethod(r.Method)}
93 m.requests.WithLabelValues(labels...).Inc()
94 m.duration.WithLabelValues(labels...).Observe(time.Since(start).Seconds())
95 m.bytes.WithLabelValues(user).Add(float64(mw.bytes))
96 })
97}
98
99func (m *UserMetrics) resolveUser(r *http.Request, user string, status int) string {
100 if user != "" {
101 m.known.Add(user, struct{}{})
102 return user
103 }
104 if m.opts.SiteUser == nil {
105 return ""
106 }
107 user = m.opts.SiteUser(r)
108 if user == "" {
109 return ""
110 }
111 if m.known.Contains(user) {
112 return user
113 }
114 if m.opts.TrustSuccess && (status >= 200 && status < 300 || status == http.StatusNotModified) {
115 m.known.Add(user, struct{}{})
116 return user
117 }
118 return ""
119}
120
121// metricMethod keeps clients from adding series with made-up methods.
122func metricMethod(method string) string {
123 switch method {
124 case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
125 http.MethodDelete, http.MethodOptions, http.MethodConnect, http.MethodTrace:
126 return method
127 }
128 return "OTHER"
129}
130
131type metricsWriter struct {
132 http.ResponseWriter
133 status int
134 bytes int64
135}
136
137func (w *metricsWriter) WriteHeader(code int) {
138 // Informational responses like 103 Early Hints precede the real status.
139 if w.status == 0 && (code >= 200 || code == http.StatusSwitchingProtocols) {
140 w.status = code
141 }
142 w.ResponseWriter.WriteHeader(code)
143}
144
145func (w *metricsWriter) Write(b []byte) (int, error) {
146 if w.status == 0 {
147 w.status = http.StatusOK
148 }
149 n, err := w.ResponseWriter.Write(b)
150 w.bytes += int64(n)
151 return n, err
152}
153
154func (w *metricsWriter) Status() int {
155 if w.status == 0 {
156 return http.StatusOK
157 }
158 return w.status
159}
160
161func (w *metricsWriter) Flush() {
162 _ = http.NewResponseController(w.ResponseWriter).Flush()
163}
164
165// Hijack lets websockets upgrade through the middleware.
166func (w *metricsWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
167 conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack()
168 if err == nil && w.status == 0 {
169 w.status = http.StatusSwitchingProtocols
170 }
171 return conn, rw, err
172}
173
174func (w *metricsWriter) Unwrap() http.ResponseWriter {
175 return w.ResponseWriter
176}