Add HTTPMiddleware, HTTPTransport and LogHandler; extend TracerConfig with Insecure, Headers and Attributes; install W3C propagators; parent-based sampling; end-to-end OTLP export tests; update dependencies (Go 1.26). Breaking since v0.2.0: the OTLP connection uses TLS unless Insecure is set. Co-Authored-By: Claude <noreply@anthropic.com>
148 lines
4.8 KiB
Go
148 lines
4.8 KiB
Go
package obsx
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
// HTTPMiddleware returns server middleware that traces every request
|
|
// (continuing the trace from incoming headers) and, when m is not nil, records
|
|
// the http_requests_total{method,route,status} counter and the
|
|
// http_request_duration_seconds{method,route} histogram.
|
|
//
|
|
// The route is the matched http.ServeMux pattern (Request.Pattern), so wrap
|
|
// the mux itself; unmatched requests are reported as route "unmatched".
|
|
// Call it once per Metrics: the metrics are registered on each call.
|
|
func HTTPMiddleware(m *Metrics) func(http.Handler) http.Handler {
|
|
var requests *prometheus.CounterVec
|
|
var duration *prometheus.HistogramVec
|
|
if m != nil {
|
|
requests = m.Counter("http_requests_total", "Total HTTP requests served.", "method", "route", "status")
|
|
duration = m.Histogram("http_request_duration_seconds", "HTTP request duration in seconds.", nil, "method", "route")
|
|
}
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
method := knownMethod(r.Method)
|
|
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
|
ctx, span := otel.Tracer(tracerName).Start(ctx, method,
|
|
trace.WithSpanKind(trace.SpanKindServer),
|
|
trace.WithAttributes(semconv.HTTPRequestMethodKey.String(method), semconv.URLPath(r.URL.Path)),
|
|
)
|
|
defer span.End()
|
|
|
|
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
|
r = r.WithContext(ctx)
|
|
defer func() {
|
|
// A panic propagates to net/http, which answers 500 or drops the connection.
|
|
p := recover()
|
|
if p != nil {
|
|
sw.status = http.StatusInternalServerError
|
|
}
|
|
route := r.Pattern // set by ServeMux on this request during ServeHTTP
|
|
if route == "" {
|
|
route = "unmatched"
|
|
} else {
|
|
span.SetName(route)
|
|
span.SetAttributes(semconv.HTTPRoute(route))
|
|
}
|
|
span.SetAttributes(semconv.HTTPResponseStatusCode(sw.status))
|
|
if sw.status >= 500 {
|
|
span.SetStatus(codes.Error, http.StatusText(sw.status))
|
|
}
|
|
if m != nil {
|
|
requests.WithLabelValues(method, route, strconv.Itoa(sw.status)).Inc()
|
|
duration.WithLabelValues(method, route).Observe(time.Since(start).Seconds())
|
|
}
|
|
if p != nil {
|
|
panic(p)
|
|
}
|
|
}()
|
|
next.ServeHTTP(sw, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
// knownMethod bounds label cardinality: clients can send arbitrary methods.
|
|
func knownMethod(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
|
|
}
|
|
return "OTHER"
|
|
}
|
|
|
|
type statusWriter struct {
|
|
http.ResponseWriter
|
|
status int
|
|
wrote bool
|
|
}
|
|
|
|
func (w *statusWriter) WriteHeader(code int) {
|
|
if !w.wrote {
|
|
w.status, w.wrote = code, true
|
|
}
|
|
w.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (w *statusWriter) Write(b []byte) (int, error) {
|
|
w.wrote = true
|
|
return w.ResponseWriter.Write(b)
|
|
}
|
|
|
|
// Flush keeps streaming handlers (SSE) working through the wrapper.
|
|
func (w *statusWriter) Flush() {
|
|
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
|
f.Flush()
|
|
}
|
|
}
|
|
|
|
// Unwrap gives http.ResponseController access to Hijack, deadlines, etc.
|
|
func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|
|
|
|
// HTTPTransport wraps base (nil means http.DefaultTransport) so that every
|
|
// outgoing request gets a client span and carries the trace context headers.
|
|
func HTTPTransport(base http.RoundTripper) http.RoundTripper {
|
|
if base == nil {
|
|
base = http.DefaultTransport
|
|
}
|
|
return transport{base}
|
|
}
|
|
|
|
type transport struct{ base http.RoundTripper }
|
|
|
|
// shortcut: the span ends when response headers arrive, not when the body is
|
|
// fully read; wrap resp.Body if body transfer time must be in the span.
|
|
func (t transport) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
method := knownMethod(r.Method)
|
|
ctx, span := otel.Tracer(tracerName).Start(r.Context(), method,
|
|
trace.WithSpanKind(trace.SpanKindClient),
|
|
trace.WithAttributes(semconv.HTTPRequestMethodKey.String(method), semconv.ServerAddress(r.URL.Host)),
|
|
)
|
|
defer span.End()
|
|
|
|
r = r.Clone(ctx) // RoundTrippers must not modify the caller's request
|
|
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(r.Header))
|
|
|
|
resp, err := t.base.RoundTrip(r)
|
|
if err != nil {
|
|
span.RecordError(err)
|
|
span.SetStatus(codes.Error, err.Error())
|
|
return nil, err
|
|
}
|
|
span.SetAttributes(semconv.HTTPResponseStatusCode(resp.StatusCode))
|
|
if resp.StatusCode >= 400 {
|
|
span.SetStatus(codes.Error, http.StatusText(resp.StatusCode))
|
|
}
|
|
return resp, nil
|
|
}
|