observe.go83 lines, 2.9 KB
| 1 | package httpx |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/prometheus/client_golang/prometheus" |
| 11 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 12 | "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" |
| 13 | "go.opentelemetry.io/otel/attribute" |
| 14 | "go.opentelemetry.io/otel/trace" |
| 15 | ) |
| 16 | |
| 17 | // requestDuration holds all three RED metrics: its count is the rate, its |
| 18 | // code label the errors, and its buckets the duration. |
| 19 | var requestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{ |
| 20 | Name: "http_request_duration_seconds", |
| 21 | Help: "How long HTTP requests took, by method, route and status code.", |
| 22 | // A millisecond to ten seconds: every timeout we have is shorter. |
| 23 | Buckets: []float64{.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}, |
| 24 | }, []string{"method", "route", "code"}) |
| 25 | |
| 26 | type routeKey struct{} |
| 27 | |
| 28 | // Observe traces each request, and measures it. It must be the outermost |
| 29 | // middleware, so everything inside, like the access log, sees the span. |
| 30 | // A public server passes otelhttp.WithPublicEndpointFn: it starts new |
| 31 | // traces, whatever the client sends. |
| 32 | func Observe(opts ...otelhttp.Option) Middleware { |
| 33 | opts = append(opts, otelhttp.WithFilter(func(r *http.Request) bool { return !quiet(r) })) |
| 34 | traced := otelhttp.NewMiddleware("http", opts...) |
| 35 | return func(next http.Handler) http.Handler { |
| 36 | return traced(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 37 | if quiet(r) { |
| 38 | next.ServeHTTP(w, r) |
| 39 | return |
| 40 | } |
| 41 | start := time.Now() |
| 42 | route := new(string) |
| 43 | rec := &statusRecorder{ResponseWriter: w} |
| 44 | next.ServeHTTP(rec, r.WithContext(context.WithValue(r.Context(), routeKey{}, route))) |
| 45 | |
| 46 | // Label by route, never by path: /v1/wallets/{id} is one series, |
| 47 | // while every wallet ID would be a series of its own. |
| 48 | if *route == "" { |
| 49 | *route = "unmatched" |
| 50 | } |
| 51 | if rec.status == 0 { |
| 52 | rec.status = http.StatusOK |
| 53 | } |
| 54 | span := trace.SpanFromContext(r.Context()) |
| 55 | span.SetName(r.Method + " " + *route) |
| 56 | span.SetAttributes(attribute.String("http.route", *route)) |
| 57 | requestDuration.WithLabelValues(r.Method, *route, strconv.Itoa(rec.status)). |
| 58 | Observe(time.Since(start).Seconds()) |
| 59 | })) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // Routes wraps a ServeMux, and tells Observe which pattern matched, like |
| 64 | // /v1/wallets/{id}. With a mux inside a mux, the innermost one wins. |
| 65 | func Routes(mux *http.ServeMux) http.Handler { |
| 66 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 67 | mux.ServeHTTP(w, r) // which sets r.Pattern |
| 68 | route, ok := r.Context().Value(routeKey{}).(*string) |
| 69 | if i := strings.Index(r.Pattern, "/"); ok && *route == "" && i >= 0 { |
| 70 | *route = r.Pattern[i:] // without the method |
| 71 | } |
| 72 | }) |
| 73 | } |
| 74 | |
| 75 | // quiet requests come from machines, every few seconds: health checks and |
| 76 | // metric scrapes. Traced and logged, they'd drown out the real traffic. |
| 77 | func quiet(r *http.Request) bool { |
| 78 | switch r.URL.Path { |
| 79 | case "/healthz", "/readyz", "/metrics": |
| 80 | return true |
| 81 | } |
| 82 | return false |
| 83 | } |