internal/telemetry: OTLP/HTTP tracer provider from the OTEL_* env (already set on stage and prod; unset = off), W3C propagation, one server span per request named after the ServeMux pattern, client spans on the default transport (Keycloak, ERP, LiteLLM, OIDC) and a pgx QueryTracer. Client and DB spans only inside a request, so the background loops add no traces. No raw paths, query strings, bodies, SQL parameters or client addresses in spans; outbound spans carry the host only. slog lines logged with a request context get trace_id/span_id; the access log names the route instead of the raw path (slugs are names). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
104 lines
3.3 KiB
Go
104 lines
3.3 KiB
Go
package telemetry
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/propagation"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
// skipped routes get no span: orca probes them every few seconds.
|
|
var skipped = map[string]bool{"GET /healthz": true, "GET /readyz": true}
|
|
|
|
// Middleware opens one server span per request, continuing an incoming
|
|
// traceparent. route returns the matched ServeMux pattern ("GET /v1/tenants/{id}"),
|
|
// or "" for an unmatched path; the span is named after it, never after the raw
|
|
// path.
|
|
func Middleware(route func(*http.Request) string, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
pattern := route(r)
|
|
if skipped[pattern] {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
name, path := spanName(r.Method, pattern)
|
|
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
|
ctx, span := tracer().Start(ctx, name, trace.WithSpanKind(trace.SpanKindServer), trace.WithAttributes(
|
|
attribute.String("http.request.method", r.Method),
|
|
attribute.String("http.route", path),
|
|
))
|
|
defer span.End()
|
|
rec := &statusWriter{ResponseWriter: w, code: http.StatusOK}
|
|
next.ServeHTTP(rec, r.WithContext(ctx))
|
|
span.SetAttributes(attribute.Int("http.response.status_code", rec.code))
|
|
if rec.code >= 500 {
|
|
span.SetStatus(codes.Error, http.StatusText(rec.code))
|
|
}
|
|
})
|
|
}
|
|
|
|
// spanName turns a ServeMux pattern into the span name and the http.route.
|
|
func spanName(method, pattern string) (name, path string) {
|
|
if pattern == "" {
|
|
return method + " unmatched", ""
|
|
}
|
|
path = pattern
|
|
if i := strings.IndexByte(pattern, ' '); i >= 0 {
|
|
path = pattern[i+1:]
|
|
}
|
|
return method + " " + path, path
|
|
}
|
|
|
|
type statusWriter struct {
|
|
http.ResponseWriter
|
|
code int
|
|
}
|
|
|
|
func (s *statusWriter) WriteHeader(c int) {
|
|
s.code = c
|
|
s.ResponseWriter.WriteHeader(c)
|
|
}
|
|
|
|
// Unwrap lets http.ResponseController reach the underlying writer.
|
|
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
|
|
|
|
// Transport wraps base (nil = http.DefaultTransport) with a client span and
|
|
// traceparent injection. Only the host is recorded: outbound paths carry ERP
|
|
// document names and Keycloak user ids.
|
|
func Transport(base http.RoundTripper) http.RoundTripper {
|
|
if base == nil {
|
|
base = http.DefaultTransport
|
|
}
|
|
return roundTripper{base: base}
|
|
}
|
|
|
|
type roundTripper struct{ base http.RoundTripper }
|
|
|
|
func (t roundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
if !hasParent(r.Context()) {
|
|
return t.base.RoundTrip(r)
|
|
}
|
|
ctx, span := tracer().Start(r.Context(), r.Method+" "+r.URL.Hostname(), trace.WithSpanKind(trace.SpanKindClient), trace.WithAttributes(
|
|
attribute.String("http.request.method", r.Method),
|
|
attribute.String("server.address", r.URL.Hostname()),
|
|
))
|
|
defer span.End()
|
|
r = r.Clone(ctx)
|
|
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(r.Header))
|
|
resp, err := t.base.RoundTrip(r)
|
|
if err != nil {
|
|
span.SetStatus(codes.Error, "request failed")
|
|
return resp, err
|
|
}
|
|
span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode))
|
|
if resp.StatusCode >= 500 {
|
|
span.SetStatus(codes.Error, strconv.Itoa(resp.StatusCode))
|
|
}
|
|
return resp, nil
|
|
}
|