CI / test (push) Failing after 43s
- Admin pprof is opt-in (AdminConfig.EnablePprof) - Client spans drop the URL query string; HostFunc bounds the host label - Config.HTTP/HTTPClient/GRPC configure the Observer's instrumentation - A panic after a partial HTTP response counts as 500 - GaugeFunc, CounterFunc and RegisterDBStats panic on duplicates - Abandoned client gRPC streams are recorded as Canceled - OTEL_EXPORTER_OTLP_PROTOCOL selects the protocol when unset - Health reports are cached for 1s; hung checks are not restarted - Environment is exported as deployment.environment.name Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
133 lines
4.0 KiB
Go
133 lines
4.0 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
|
|
|
|
// HostFunc returns the host metric label, default: the request URL host.
|
|
// When hosts come from users (webhooks, fetch-by-URL) return a fixed
|
|
// value such as "external" to keep metric cardinality bounded.
|
|
HostFunc func(*http.Request) string
|
|
}
|
|
|
|
func (c *HTTPClientConfig) defaults() {
|
|
if c.TracerProvider == nil {
|
|
c.TracerProvider = otel.GetTracerProvider()
|
|
}
|
|
if c.Propagator == nil {
|
|
c.Propagator = otel.GetTextMapPropagator()
|
|
}
|
|
if c.HostFunc == nil {
|
|
c.HostFunc = func(r *http.Request) string { return r.URL.Host }
|
|
}
|
|
}
|
|
|
|
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 clientTransport struct {
|
|
base http.RoundTripper
|
|
tracer trace.Tracer
|
|
propagator propagation.TextMapPropagator
|
|
metrics *httpClientMetrics
|
|
hostFunc func(*http.Request) string
|
|
}
|
|
|
|
// 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 := &clientTransport{
|
|
base: base,
|
|
tracer: cfg.TracerProvider.Tracer(tracerName),
|
|
propagator: cfg.Propagator,
|
|
hostFunc: cfg.HostFunc,
|
|
}
|
|
if cfg.Metrics != nil {
|
|
t.metrics = newHTTPClientMetrics(cfg.Metrics, cfg.Buckets)
|
|
}
|
|
return t
|
|
}
|
|
|
|
// RoundTrip implements http.RoundTripper.
|
|
func (t *clientTransport) 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 := t.hostFunc(req)
|
|
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 and without the
|
|
// query string, which often carries tokens and signatures.
|
|
func redactURL(req *http.Request) string {
|
|
u := *req.URL
|
|
u.User = nil
|
|
u.RawQuery = ""
|
|
return u.String()
|
|
}
|