HTTP server middleware, HTTP client transport and gRPC server/client interceptors (unary and stream) providing spans, context propagation, RED metrics with uniform names and access logs. Labels are kept low-cardinality (route templates, normalized methods). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
124 lines
3.6 KiB
Go
124 lines
3.6 KiB
Go
package obsx
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"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"
|
|
)
|
|
|
|
// HTTPClientConfig configures the instrumented HTTP client transport.
|
|
type HTTPClientConfig struct {
|
|
Metrics *Metrics // nil disables metrics
|
|
TracerProvider trace.TracerProvider // nil: global provider
|
|
Propagator propagation.TextMapPropagator // nil: global propagator
|
|
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
|
|
}
|
|
|
|
func (c *HTTPClientConfig) defaults() {
|
|
if c.TracerProvider == nil {
|
|
c.TracerProvider = otel.GetTracerProvider()
|
|
}
|
|
if c.Propagator == nil {
|
|
c.Propagator = otel.GetTextMapPropagator()
|
|
}
|
|
}
|
|
|
|
type httpClientMetrics struct {
|
|
requests *prometheus.CounterVec
|
|
duration *prometheus.HistogramVec
|
|
}
|
|
|
|
func newHTTPClientMetrics(m *Metrics, buckets []float64) *httpClientMetrics {
|
|
m = m.base()
|
|
return &httpClientMetrics{
|
|
requests: m.Counter("http_client_requests_total",
|
|
"Total number of outgoing HTTP requests.", "method", "host", "code"),
|
|
duration: m.Histogram("http_client_request_duration_seconds",
|
|
"Duration of outgoing HTTP requests until response headers are received.", buckets, "method", "host", "code"),
|
|
}
|
|
}
|
|
|
|
type transport struct {
|
|
base http.RoundTripper
|
|
tracer trace.Tracer
|
|
propagator propagation.TextMapPropagator
|
|
metrics *httpClientMetrics
|
|
}
|
|
|
|
// NewHTTPTransport wraps base (http.DefaultTransport when nil) with client
|
|
// spans, trace context propagation and metrics:
|
|
// http_client_requests_total and http_client_request_duration_seconds
|
|
// (labels method, host, code; code is "error" for transport failures).
|
|
func NewHTTPTransport(base http.RoundTripper, cfg HTTPClientConfig) http.RoundTripper {
|
|
cfg.defaults()
|
|
if base == nil {
|
|
base = http.DefaultTransport
|
|
}
|
|
t := &transport{
|
|
base: base,
|
|
tracer: cfg.TracerProvider.Tracer(instrumentationName),
|
|
propagator: cfg.Propagator,
|
|
}
|
|
if cfg.Metrics != nil {
|
|
t.metrics = newHTTPClientMetrics(cfg.Metrics, cfg.Buckets)
|
|
}
|
|
return t
|
|
}
|
|
|
|
// RoundTrip implements http.RoundTripper.
|
|
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
start := time.Now()
|
|
method := normalizeMethod(req.Method)
|
|
|
|
ctx, span := t.tracer.Start(req.Context(), method,
|
|
trace.WithSpanKind(trace.SpanKindClient),
|
|
trace.WithAttributes(
|
|
attribute.String("http.request.method", method),
|
|
attribute.String("server.address", req.URL.Hostname()),
|
|
attribute.String("url.full", redactURL(req)),
|
|
),
|
|
)
|
|
defer span.End()
|
|
|
|
// RoundTrippers must not modify the caller's request.
|
|
req = req.Clone(ctx)
|
|
t.propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))
|
|
|
|
resp, err := t.base.RoundTrip(req)
|
|
|
|
code := "error"
|
|
if err != nil {
|
|
failSpan(span, err)
|
|
} else {
|
|
code = strconv.Itoa(resp.StatusCode)
|
|
span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode))
|
|
if resp.StatusCode >= 400 {
|
|
span.SetStatus(codes.Error, http.StatusText(resp.StatusCode))
|
|
}
|
|
}
|
|
|
|
if t.metrics != nil {
|
|
host := req.URL.Host
|
|
t.metrics.requests.WithLabelValues(method, host, code).Inc()
|
|
observe(ctx, t.metrics.duration.WithLabelValues(method, host, code), time.Since(start).Seconds())
|
|
}
|
|
return resp, err
|
|
}
|
|
|
|
// redactURL returns the request URL without user credentials.
|
|
func redactURL(req *http.Request) string {
|
|
if req.URL.User == nil {
|
|
return req.URL.String()
|
|
}
|
|
u := *req.URL
|
|
u.User = nil
|
|
return u.String()
|
|
}
|