package obsx import ( "bufio" "fmt" "io" "log/slog" "net" "net/http" "strconv" "strings" "time" "github.com/prometheus/client_golang/prometheus" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" ) // routeUnmatched is the route label for requests whose route is unknown. // Raw paths are never used as labels to keep metric cardinality bounded. const routeUnmatched = "unmatched" // HTTPServerConfig configures the HTTP server middleware. type HTTPServerConfig struct { Metrics *Metrics // nil disables metrics Logger *slog.Logger // nil disables access logs TracerProvider trace.TracerProvider // nil: global provider // Propagator extracts the incoming trace context; nil: global propagator. // Sampling follows the caller's decision, so on endpoints reachable by // untrusted clients set propagation.NewCompositeTextMapPropagator() to // ignore incoming trace headers. Propagator propagation.TextMapPropagator // RouteFunc returns the low-cardinality route template of a request // (e.g. "/users/{id}"). It is called after the handler has run. The // default uses http.Request.Pattern set by http.ServeMux; when the // middleware wraps an *http.ServeMux directly the pattern is resolved even // if inner middleware replaced the request. Unknown routes are reported // as "unmatched". // // For chi: func(r *http.Request) string { return chi.RouteContext(r.Context()).RoutePattern() } RouteFunc func(r *http.Request) string Skip func(r *http.Request) bool // requests for which Skip returns true are not instrumented Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets TraceIDHeader string // if set, the trace ID is returned in this response header, e.g. "X-Trace-Id" } func (c *HTTPServerConfig) defaults() { if c.TracerProvider == nil { c.TracerProvider = otel.GetTracerProvider() } if c.Propagator == nil { c.Propagator = otel.GetTextMapPropagator() } } type httpServerMetrics struct { requests *prometheus.CounterVec duration *prometheus.HistogramVec inflight prometheus.Gauge } func newHTTPServerMetrics(m *Metrics, buckets []float64) *httpServerMetrics { m = m.base() return &httpServerMetrics{ requests: m.Counter("http_server_requests_total", "Total number of HTTP requests handled by the server.", "method", "route", "code"), duration: m.Histogram("http_server_request_duration_seconds", "Duration of HTTP requests handled by the server.", buckets, "method", "route", "code"), inflight: m.Gauge("http_server_requests_in_flight", "Number of HTTP requests currently being handled by the server.").WithLabelValues(), } } // NewHTTPMiddleware returns middleware that instruments HTTP handlers with // tracing (incoming context extraction, server spans), RED metrics and access // logs. It is compatible with any router accepting func(http.Handler) http.Handler. // // Metrics: http_server_requests_total, http_server_request_duration_seconds // (labels method, route, code) and http_server_requests_in_flight. // // Panics are recorded as 500 responses and re-raised. func NewHTTPMiddleware(cfg HTTPServerConfig) func(http.Handler) http.Handler { cfg.defaults() var metrics *httpServerMetrics if cfg.Metrics != nil { metrics = newHTTPServerMetrics(cfg.Metrics, cfg.Buckets) } tracer := cfg.TracerProvider.Tracer(tracerName) return func(next http.Handler) http.Handler { routeFunc := cfg.RouteFunc if routeFunc == nil { mux, _ := next.(*http.ServeMux) routeFunc = func(r *http.Request) string { return patternRoute(r, mux) } } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if cfg.Skip != nil && cfg.Skip(r) { next.ServeHTTP(w, r) return } start := time.Now() method := normalizeMethod(r.Method) ctx := cfg.Propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) ctx, span := tracer.Start(ctx, method, trace.WithSpanKind(trace.SpanKindServer), trace.WithAttributes( attribute.String("http.request.method", method), attribute.String("url.path", r.URL.Path), attribute.String("url.scheme", requestScheme(r)), attribute.String("server.address", r.Host), attribute.String("client.address", clientIP(r.RemoteAddr)), attribute.String("user_agent.original", r.UserAgent()), ), ) if cfg.TraceIDHeader != "" && span.SpanContext().HasTraceID() { w.Header().Set(cfg.TraceIDHeader, span.SpanContext().TraceID().String()) } if metrics != nil { metrics.inflight.Inc() } rw := &responseWriter{ResponseWriter: w} r = r.WithContext(ctx) defer func() { rec := recover() status := rw.status switch { case rec != nil: // also after a partial response: the connection is aborted status = http.StatusInternalServerError case status == 0: status = http.StatusOK } route := routeFunc(r) if route == "" { route = routeUnmatched } code := strconv.Itoa(status) elapsed := time.Since(start) if route != routeUnmatched { span.SetName(method + " " + route) span.SetAttributes(attribute.String("http.route", route)) } span.SetAttributes( attribute.Int("http.response.status_code", status), attribute.Int64("http.response.body.size", rw.size), ) if rec != nil { span.RecordError(fmt.Errorf("panic: %v", rec), trace.WithStackTrace(true)) } if status >= 500 { span.SetStatus(codes.Error, http.StatusText(status)) } if metrics != nil { metrics.inflight.Dec() metrics.requests.WithLabelValues(method, route, code).Inc() observe(ctx, metrics.duration.WithLabelValues(method, route, code), elapsed.Seconds()) } if cfg.Logger != nil { level := slog.LevelInfo if status >= 500 { level = slog.LevelError } attrs := []slog.Attr{ slog.String("method", r.Method), slog.String("path", r.URL.Path), slog.String("route", route), slog.Int("status", status), durationAttr(elapsed), slog.Int64("size", rw.size), slog.String("remote", clientIP(r.RemoteAddr)), } if rec != nil { attrs = append(attrs, slog.Any("panic", rec)) } cfg.Logger.LogAttrs(ctx, level, "http request", attrs...) } span.End() if rec != nil { panic(rec) } }() next.ServeHTTP(rw, r) }) } } // patternRoute derives the route from the ServeMux pattern ("GET /users/{id}" // becomes "/users/{id}"). If the request was copied by inner middleware the // pattern is resolved through mux, when known. func patternRoute(r *http.Request, mux *http.ServeMux) string { pattern := r.Pattern if pattern == "" && mux != nil { _, pattern = mux.Handler(r) } if pattern == "" { return routeUnmatched } if i := strings.IndexAny(pattern, " \t"); i >= 0 { pattern = strings.TrimLeft(pattern[i:], " \t") } return pattern } // normalizeMethod maps non-standard methods to "OTHER" to bound cardinality. func normalizeMethod(m string) string { switch m { case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace: return m default: return "OTHER" } } func requestScheme(r *http.Request) string { if r.TLS != nil { return "https" } return "http" } func clientIP(remoteAddr string) string { if host, _, err := net.SplitHostPort(remoteAddr); err == nil { return host } return remoteAddr } // responseWriter captures the status code and body size. It supports // http.Flusher, http.Hijacker, io.ReaderFrom and http.ResponseController // (via Unwrap). type responseWriter struct { http.ResponseWriter status int size int64 wroteHeader bool } func (w *responseWriter) WriteHeader(code int) { if !w.wroteHeader && code >= 200 { w.status = code w.wroteHeader = true } w.ResponseWriter.WriteHeader(code) } func (w *responseWriter) Write(b []byte) (int, error) { if !w.wroteHeader { w.WriteHeader(http.StatusOK) } n, err := w.ResponseWriter.Write(b) w.size += int64(n) return n, err } func (w *responseWriter) ReadFrom(src io.Reader) (int64, error) { if !w.wroteHeader { w.WriteHeader(http.StatusOK) } n, err := io.Copy(w.ResponseWriter, src) w.size += n return n, err } func (w *responseWriter) Flush() { if !w.wroteHeader { w.WriteHeader(http.StatusOK) } _ = http.NewResponseController(w.ResponseWriter).Flush() } func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack() if err == nil && !w.wroteHeader { w.status = http.StatusSwitchingProtocols w.wroteHeader = true } return conn, rw, err } func (w *responseWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }