feat(telemetry): traces to SigNoz for requests, outbound calls and SQL
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
This commit is contained in:
1 parent
5fff4dd581
commit
65ad1b52f6
12 files changed
+703
-12
No files matched your search
@@ -83,7 +83,7 @@ jobs:
|
||||
# own test binary — and including it triggers a covdata-tool error
|
||||
# on packages with no _test.go files. -coverpkg makes the server's
|
||||
# exercise of store/* count toward coverage.
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/...
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/... ./internal/telemetry/...
|
||||
|
||||
- name: coverage gate
|
||||
run: |
|
||||
|
||||
+23
-1
@@ -13,6 +13,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/buildinfo"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
@@ -22,11 +23,12 @@ import (
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/secretbox"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/server"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
|
||||
"git.breakpilot.com/platform/tenant-registry/migrations"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
logger := slog.New(telemetry.NewLogHandler(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
cfg, err := config.Load()
|
||||
@@ -35,6 +37,21 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Traces to SigNoz when OTEL_EXPORTER_OTLP_ENDPOINT is set; every outbound
|
||||
// client without its own transport (Keycloak, ERP, LiteLLM, OIDC) goes
|
||||
// through the traced default transport.
|
||||
shutdownTelemetry, err := telemetry.Setup(context.Background(), telemetry.Info{
|
||||
Service: "tenant-registry", Version: buildinfo.Version, Commit: buildinfo.Commit, Env: cfg.Env,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("telemetry setup failed", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
http.DefaultTransport = telemetry.Transport(http.DefaultTransport)
|
||||
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") != "" {
|
||||
slog.Info("tracing enabled", "endpoint", os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"))
|
||||
}
|
||||
|
||||
bootCtx, cancelBoot := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancelBoot()
|
||||
|
||||
@@ -203,6 +220,11 @@ func main() {
|
||||
slog.Error("shutdown failed", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
flushCtx, cancelFlush := context.WithTimeout(context.Background(), telemetry.ShutdownTimeout)
|
||||
defer cancelFlush()
|
||||
if err := shutdownTelemetry(flushCtx); err != nil {
|
||||
slog.Warn("telemetry flush failed", "err", err)
|
||||
}
|
||||
slog.Info("bye")
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,10 @@ require (
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/minio/minio-go/v7 v7.0.95
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0
|
||||
go.opentelemetry.io/otel v1.41.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0
|
||||
go.opentelemetry.io/otel/sdk v1.41.0
|
||||
go.opentelemetry.io/otel/trace v1.41.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
@@ -20,6 +24,7 @@ require (
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/containerd/errdefs v1.0.0 // indirect
|
||||
github.com/containerd/errdefs/pkg v0.3.0 // indirect
|
||||
@@ -41,6 +46,7 @@ require (
|
||||
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/gorilla/mux v1.8.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
@@ -79,13 +85,17 @@ require (
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
|
||||
go.opentelemetry.io/otel v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.41.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/grpc v1.79.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -8,6 +8,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
@@ -70,6 +72,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1/go.mod h1:CTcgfjxhaUtsLipnLoQRWCrjYXycRz/g5+RWDuYgPrE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
@@ -77,6 +81,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6 h1:D/V0gu4zQ3cL2WKeVNVM4r2gLxGGf6McLwgXzRTo2RQ=
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
@@ -182,14 +188,22 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6h
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
|
||||
go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c=
|
||||
go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ=
|
||||
go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps=
|
||||
go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs=
|
||||
go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.36.0 h1:r0ntwwGosWGaa0CrSt8cuNuTcccMXERFwHX4dThiPis=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4=
|
||||
go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8=
|
||||
go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.41.0 h1:siZQIYBAUd1rlIWQT2uCxWJxcCO7q3TriaMlf08rXw8=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.41.0/go.mod h1:HNBuSvT7ROaGtGI50ArdRLUnvRTRGniSUZbxiWxSO8Y=
|
||||
go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0=
|
||||
go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
@@ -208,6 +222,16 @@ golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=
|
||||
google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -58,15 +58,15 @@ func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
|
||||
}
|
||||
|
||||
// logRequest is the access-log middleware: one structured line per request.
|
||||
func logRequest(log *slog.Logger) func(http.Handler) http.Handler {
|
||||
func logRequest(log *slog.Logger, route func(*http.Request) string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rr := &statusRecorder{ResponseWriter: w, code: 200}
|
||||
next.ServeHTTP(rr, r)
|
||||
log.Info("http",
|
||||
log.InfoContext(r.Context(), "http",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"route", route(r),
|
||||
"status", rr.code,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"remote", clientIP(r),
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -229,7 +230,16 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/documents/{doc}/download", s.downloadTenantDocument)
|
||||
|
||||
root.Handle("/", s.requireAuth(s.requireMember(s.requireAuthz(mux))))
|
||||
return logRequest(s.Log)(root)
|
||||
// The matched pattern names the span and the access-log line; the raw path
|
||||
// carries slugs and stays out of both.
|
||||
route := func(r *http.Request) string {
|
||||
if _, p := root.Handler(r); p != "/" {
|
||||
return p
|
||||
}
|
||||
_, p := mux.Handler(r)
|
||||
return p
|
||||
}
|
||||
return telemetry.Middleware(route, logRequest(s.Log, route)(root))
|
||||
}
|
||||
|
||||
// requireAuth gates the INTERNAL_SERVICE_ONLY routes. With Auth nil
|
||||
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
|
||||
)
|
||||
|
||||
// Postgres — pgxpool-backed Store. The schema this expects is produced by
|
||||
@@ -29,6 +31,7 @@ func NewPostgres(ctx context.Context, dsn string) (*Postgres, error) {
|
||||
cfg.MaxConns = 20
|
||||
cfg.MinConns = 2
|
||||
cfg.MaxConnLifetime = time.Hour
|
||||
cfg.ConnConfig.Tracer = telemetry.QueryTracer{} // spans only inside a traced request
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// maxStatement caps db.query.text; the statements are ours and use $n
|
||||
// placeholders, parameters are never recorded.
|
||||
const maxStatement = 2000
|
||||
|
||||
// QueryTracer is a pgx.QueryTracer: one span per query inside a request.
|
||||
type QueryTracer struct{}
|
||||
|
||||
type spanKey struct{}
|
||||
|
||||
func (QueryTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
if !hasParent(ctx) {
|
||||
return ctx
|
||||
}
|
||||
op := operation(data.SQL)
|
||||
ctx, span := tracer().Start(ctx, "db "+op, trace.WithSpanKind(trace.SpanKindClient), trace.WithAttributes(
|
||||
attribute.String("db.system.name", "postgresql"),
|
||||
attribute.String("db.operation.name", op),
|
||||
attribute.String("db.query.text", truncate(strings.TrimSpace(data.SQL), maxStatement)),
|
||||
))
|
||||
// Marked so TraceQueryEnd never ends a span it did not start (the parent).
|
||||
return context.WithValue(ctx, spanKey{}, span)
|
||||
}
|
||||
|
||||
func (QueryTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
span, ok := ctx.Value(spanKey{}).(trace.Span)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if data.Err != nil && data.Err != pgx.ErrNoRows {
|
||||
span.SetStatus(codes.Error, "query failed")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
// operation is the statement's first keyword (SELECT, INSERT, WITH, …).
|
||||
func operation(sql string) string {
|
||||
f := strings.Fields(sql)
|
||||
if len(f) == 0 {
|
||||
return "QUERY"
|
||||
}
|
||||
return strings.ToUpper(f[0])
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// LogHandler adds trace_id and span_id to every record logged with a context
|
||||
// that belongs to a trace (slog.InfoContext and friends), so SigNoz links the
|
||||
// line to its trace.
|
||||
type LogHandler struct{ slog.Handler }
|
||||
|
||||
func NewLogHandler(h slog.Handler) *LogHandler { return &LogHandler{Handler: h} }
|
||||
|
||||
func (h *LogHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
|
||||
r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()))
|
||||
}
|
||||
return h.Handler.Handle(ctx, r)
|
||||
}
|
||||
|
||||
func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &LogHandler{Handler: h.Handler.WithAttrs(attrs)}
|
||||
}
|
||||
|
||||
func (h *LogHandler) WithGroup(name string) slog.Handler {
|
||||
return &LogHandler{Handler: h.Handler.WithGroup(name)}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Package telemetry sends traces to SigNoz over OTLP/HTTP
|
||||
// (research/observability/2026-10-28-instrumentation-portal-registry-db.md).
|
||||
//
|
||||
// Setup reads the standard variables: OTEL_EXPORTER_OTLP_ENDPOINT (unset = off,
|
||||
// nothing is exported), OTEL_EXPORTER_OTLP_HEADERS (the bearer token),
|
||||
// OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES.
|
||||
//
|
||||
// Privacy rule for every span: no raw paths (slugs are names), no query
|
||||
// strings, no bodies, no SQL parameters, no client addresses. Server spans
|
||||
// carry the route template, client spans the host only.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const scope = "git.breakpilot.com/platform/tenant-registry"
|
||||
|
||||
// Info names the running build in the resource.
|
||||
type Info struct {
|
||||
Service string // default service.name when OTEL_SERVICE_NAME is unset
|
||||
Version string
|
||||
Commit string
|
||||
Env string // dev | stage | prod
|
||||
}
|
||||
|
||||
// Setup installs the global tracer provider and the W3C propagator. Without
|
||||
// OTEL_EXPORTER_OTLP_ENDPOINT it installs only the propagator and returns a
|
||||
// no-op shutdown, so a dev run or an unconfigured deployment works unchanged.
|
||||
func Setup(ctx context.Context, info Info) (shutdown func(context.Context) error, err error) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == "" {
|
||||
return func(context.Context) error { return nil }, nil
|
||||
}
|
||||
exp, err := otlptracehttp.New(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tp, err := newProvider(ctx, info, sdktrace.WithBatcher(exp))
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, exp.Shutdown(ctx))
|
||||
}
|
||||
otel.SetTracerProvider(tp)
|
||||
return tp.Shutdown, nil
|
||||
}
|
||||
|
||||
// newProvider builds the provider; tests pass a span recorder instead of the
|
||||
// exporter.
|
||||
func newProvider(ctx context.Context, info Info, opts ...sdktrace.TracerProviderOption) (*sdktrace.TracerProvider, error) {
|
||||
attrs := []attribute.KeyValue{
|
||||
attribute.String("service.name", info.Service),
|
||||
attribute.String("service.version", info.Version),
|
||||
}
|
||||
if info.Commit != "" {
|
||||
attrs = append(attrs, attribute.String("vcs.ref.head.revision", info.Commit))
|
||||
}
|
||||
if info.Env != "" {
|
||||
attrs = append(attrs, attribute.String("deployment.environment", info.Env))
|
||||
}
|
||||
// Later options win: the environment overrides the defaults above.
|
||||
res, err := resource.New(ctx, resource.WithAttributes(attrs...), resource.WithFromEnv(), resource.WithTelemetrySDK())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opts = append([]sdktrace.TracerProviderOption{sdktrace.WithResource(res)}, opts...)
|
||||
return sdktrace.NewTracerProvider(opts...), nil
|
||||
}
|
||||
|
||||
// ShutdownTimeout bounds the final flush on SIGTERM.
|
||||
const ShutdownTimeout = 5 * time.Second
|
||||
|
||||
func tracer() trace.Tracer { return otel.Tracer(scope) }
|
||||
|
||||
// hasParent reports whether ctx already belongs to a trace. Client and DB
|
||||
// spans are only created inside one: background loops (outbox, reconcile,
|
||||
// mail) poll every few seconds and would otherwise flood SigNoz with
|
||||
// single-span traces.
|
||||
func hasParent(ctx context.Context) bool {
|
||||
return trace.SpanContextFromContext(ctx).IsValid()
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// record installs a recording provider for one test.
|
||||
func record(t *testing.T) *tracetest.SpanRecorder {
|
||||
t.Helper()
|
||||
rec := tracetest.NewSpanRecorder()
|
||||
tp, err := newProvider(context.Background(), Info{Service: "tenant-registry"}, sdktrace.WithSpanProcessor(rec))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prev := otel.GetTracerProvider()
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
return rec
|
||||
}
|
||||
|
||||
func attr(s sdktrace.ReadOnlySpan, key string) (attribute.Value, bool) {
|
||||
for _, kv := range s.Attributes() {
|
||||
if string(kv.Key) == key {
|
||||
return kv.Value, true
|
||||
}
|
||||
}
|
||||
return attribute.Value{}, false
|
||||
}
|
||||
|
||||
// inSpan returns a context inside a recorded parent span.
|
||||
func inSpan(t *testing.T) (context.Context, trace.Span) {
|
||||
t.Helper()
|
||||
return otel.Tracer("test").Start(context.Background(), "parent")
|
||||
}
|
||||
|
||||
func TestSetupWithoutEndpointIsNoop(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
|
||||
shutdown, err := Setup(context.Background(), Info{Service: "tenant-registry"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := shutdown(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := otel.GetTextMapPropagator().(propagation.TraceContext); !ok {
|
||||
t.Fatalf("propagator = %T, want TraceContext", otel.GetTextMapPropagator())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetupWithEndpoint(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:1")
|
||||
prev := otel.GetTracerProvider()
|
||||
t.Cleanup(func() { otel.SetTracerProvider(prev) })
|
||||
shutdown, err := Setup(context.Background(), Info{Service: "tenant-registry", Version: "v0.1.9", Commit: "abc", Env: "stage"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := otel.GetTracerProvider().(*sdktrace.TracerProvider); !ok {
|
||||
t.Fatalf("provider = %T, want the SDK provider", otel.GetTracerProvider())
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), ShutdownTimeout)
|
||||
defer cancel()
|
||||
_ = shutdown(ctx) // nothing was recorded, so nothing to send
|
||||
}
|
||||
|
||||
func TestSetupWithBadResourceEnv(t *testing.T) {
|
||||
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://127.0.0.1:1")
|
||||
t.Setenv("OTEL_RESOURCE_ATTRIBUTES", "broken")
|
||||
if _, err := Setup(context.Background(), Info{Service: "tenant-registry"}); err == nil {
|
||||
t.Fatal("want an error for a malformed OTEL_RESOURCE_ATTRIBUTES")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceEnvOverridesDefaults(t *testing.T) {
|
||||
t.Setenv("OTEL_SERVICE_NAME", "tenant-registry-stage")
|
||||
t.Setenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment=prod")
|
||||
tp, err := newProvider(context.Background(), Info{Service: "tenant-registry", Version: "v1", Commit: "c0ffee", Env: "stage"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, kv := range tpResource(tp) {
|
||||
got[string(kv.Key)] = kv.Value.Emit()
|
||||
}
|
||||
want := map[string]string{"service.name": "tenant-registry-stage", "deployment.environment": "prod", "service.version": "v1", "vcs.ref.head.revision": "c0ffee"}
|
||||
for k, v := range want {
|
||||
if got[k] != v {
|
||||
t.Errorf("%s = %q, want %q", k, got[k], v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tpResource reads the resource through a recorded span.
|
||||
func tpResource(tp *sdktrace.TracerProvider) []attribute.KeyValue {
|
||||
rec := tracetest.NewSpanRecorder()
|
||||
tp.RegisterSpanProcessor(rec)
|
||||
_, s := tp.Tracer("t").Start(context.Background(), "x")
|
||||
s.End()
|
||||
return rec.Ended()[0].Resource().Attributes()
|
||||
}
|
||||
|
||||
func TestMiddlewareNamesSpanByRoute(t *testing.T) {
|
||||
rec := record(t)
|
||||
route := func(r *http.Request) string {
|
||||
switch r.URL.Path {
|
||||
case "/healthz":
|
||||
return "GET /healthz"
|
||||
case "/v1/tenants/by-slug/acme":
|
||||
return "GET /v1/tenants/by-slug/{slug}"
|
||||
case "/boom":
|
||||
return "GET /boom"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var inner trace.SpanContext
|
||||
h := Middleware(route, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/v1/tenants/by-slug/acme" {
|
||||
inner = trace.SpanContextFromContext(r.Context())
|
||||
}
|
||||
if r.URL.Path == "/boom" {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
}))
|
||||
|
||||
parent, ps := inSpan(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/tenants/by-slug/acme?x=1", nil)
|
||||
otel.GetTextMapPropagator().Inject(parent, propagation.HeaderCarrier(req.Header))
|
||||
ps.End()
|
||||
h.ServeHTTP(httptest.NewRecorder(), req)
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/boom", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/nope/acme", nil))
|
||||
|
||||
var server []sdktrace.ReadOnlySpan
|
||||
for _, s := range rec.Ended() {
|
||||
if s.SpanKind() == trace.SpanKindServer {
|
||||
server = append(server, s)
|
||||
}
|
||||
}
|
||||
if len(server) != 3 {
|
||||
t.Fatalf("server spans = %d, want 3 (healthz is skipped)", len(server))
|
||||
}
|
||||
s := server[0]
|
||||
if s.Name() != "GET /v1/tenants/by-slug/{slug}" {
|
||||
t.Errorf("name = %q", s.Name())
|
||||
}
|
||||
if s.Parent().TraceID() != ps.SpanContext().TraceID() {
|
||||
t.Error("incoming traceparent not continued")
|
||||
}
|
||||
if inner.SpanID() != s.SpanContext().SpanID() {
|
||||
t.Error("handler context does not carry the server span")
|
||||
}
|
||||
for _, kv := range s.Attributes() {
|
||||
if strings.Contains(kv.Value.Emit(), "acme") || strings.Contains(kv.Value.Emit(), "x=1") {
|
||||
t.Errorf("attribute %s leaks the raw path or query: %q", kv.Key, kv.Value.Emit())
|
||||
}
|
||||
}
|
||||
if v, _ := attr(s, "http.response.status_code"); v.AsInt64() != 200 {
|
||||
t.Errorf("status = %d", v.AsInt64())
|
||||
}
|
||||
if server[1].Status().Code != codes.Error {
|
||||
t.Error("a 500 must mark the span as an error")
|
||||
}
|
||||
if server[2].Name() != "GET unmatched" {
|
||||
t.Errorf("unmatched name = %q", server[2].Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusWriterUnwrap(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
if (&statusWriter{ResponseWriter: rr}).Unwrap() != rr {
|
||||
t.Fatal("Unwrap must return the wrapped writer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransport(t *testing.T) {
|
||||
rec := record(t)
|
||||
var gotTraceparent string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotTraceparent = r.Header.Get("traceparent")
|
||||
if r.URL.Path == "/fail" {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
client := &http.Client{Transport: Transport(nil)}
|
||||
|
||||
get := func(ctx context.Context, path string) error {
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Outside a trace: no span, no header.
|
||||
if err := get(context.Background(), "/ok"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gotTraceparent != "" || len(rec.Ended()) != 0 {
|
||||
t.Fatal("no span and no traceparent outside a trace")
|
||||
}
|
||||
|
||||
ctx, parent := inSpan(t)
|
||||
if err := get(ctx, "/customer/acme?token=1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := get(ctx, "/fail"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parent.End()
|
||||
if !strings.Contains(gotTraceparent, parent.SpanContext().TraceID().String()) {
|
||||
t.Errorf("traceparent %q does not carry the trace", gotTraceparent)
|
||||
}
|
||||
spans := rec.Ended()
|
||||
c := spans[0]
|
||||
if c.SpanKind() != trace.SpanKindClient || c.Name() != "GET 127.0.0.1" {
|
||||
t.Errorf("client span = %v %q", c.SpanKind(), c.Name())
|
||||
}
|
||||
for _, kv := range c.Attributes() {
|
||||
if strings.Contains(kv.Value.Emit(), "acme") || strings.Contains(kv.Value.Emit(), "token") {
|
||||
t.Errorf("attribute %s leaks the path or query", kv.Key)
|
||||
}
|
||||
}
|
||||
if spans[1].Status().Code != codes.Error {
|
||||
t.Error("a 502 must mark the client span as an error")
|
||||
}
|
||||
|
||||
// Transport failure.
|
||||
ctx, parent = inSpan(t)
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:1/", nil)
|
||||
if _, err := client.Do(req); err == nil {
|
||||
t.Fatal("want a connection error")
|
||||
}
|
||||
parent.End()
|
||||
failed := rec.Ended()[len(rec.Ended())-2]
|
||||
if failed.Status().Code != codes.Error {
|
||||
t.Error("a failed request must mark the client span as an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryTracer(t *testing.T) {
|
||||
rec := record(t)
|
||||
var qt QueryTracer
|
||||
|
||||
// Outside a trace: untouched context, End is a no-op.
|
||||
ctx := qt.TraceQueryStart(context.Background(), nil, pgx.TraceQueryStartData{SQL: "SELECT 1"})
|
||||
qt.TraceQueryEnd(ctx, nil, pgx.TraceQueryEndData{})
|
||||
if len(rec.Ended()) != 0 {
|
||||
t.Fatal("no span outside a trace")
|
||||
}
|
||||
|
||||
parentCtx, parent := inSpan(t)
|
||||
for _, q := range []struct {
|
||||
sql string
|
||||
err error
|
||||
}{
|
||||
{"\n select id from tenants where slug = $1", nil},
|
||||
{"INSERT INTO audit VALUES ($1)", errors.New("boom")},
|
||||
{"SELECT * FROM t WHERE id = $1", pgx.ErrNoRows},
|
||||
{"", nil},
|
||||
} {
|
||||
c := qt.TraceQueryStart(parentCtx, nil, pgx.TraceQueryStartData{SQL: q.sql, Args: []any{"acme"}})
|
||||
qt.TraceQueryEnd(c, nil, pgx.TraceQueryEndData{Err: q.err})
|
||||
}
|
||||
if !parent.(sdktrace.ReadOnlySpan).EndTime().IsZero() {
|
||||
t.Fatal("TraceQueryEnd ended the parent span")
|
||||
}
|
||||
parent.End()
|
||||
|
||||
spans := rec.Ended()
|
||||
if spans[0].Name() != "db SELECT" {
|
||||
t.Errorf("name = %q", spans[0].Name())
|
||||
}
|
||||
if v, _ := attr(spans[0], "db.query.text"); v.AsString() != "select id from tenants where slug = $1" {
|
||||
t.Errorf("db.query.text = %q", v.AsString())
|
||||
}
|
||||
for _, kv := range spans[0].Attributes() {
|
||||
if strings.Contains(kv.Value.Emit(), "acme") {
|
||||
t.Error("query parameters must not be recorded")
|
||||
}
|
||||
}
|
||||
if spans[1].Status().Code != codes.Error {
|
||||
t.Error("a failed query must mark the span as an error")
|
||||
}
|
||||
if spans[2].Status().Code == codes.Error {
|
||||
t.Error("ErrNoRows is not an error")
|
||||
}
|
||||
if spans[3].Name() != "db QUERY" {
|
||||
t.Errorf("empty SQL name = %q", spans[3].Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
if got := truncate(strings.Repeat("a", maxStatement+5), maxStatement); len(got) != maxStatement {
|
||||
t.Fatalf("len = %d", len(got))
|
||||
}
|
||||
if truncate("abc", 5) != "abc" {
|
||||
t.Fatal("short strings stay")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogHandlerAddsTraceIDs(t *testing.T) {
|
||||
record(t)
|
||||
var buf bytes.Buffer
|
||||
log := slog.New(NewLogHandler(slog.NewJSONHandler(&buf, nil))).With("svc", "tr").WithGroup("g")
|
||||
|
||||
log.InfoContext(context.Background(), "outside")
|
||||
if strings.Contains(buf.String(), "trace_id") {
|
||||
t.Fatal("no trace_id outside a trace")
|
||||
}
|
||||
ctx, span := inSpan(t)
|
||||
defer span.End()
|
||||
buf.Reset()
|
||||
log.InfoContext(ctx, "inside")
|
||||
if !strings.Contains(buf.String(), span.SpanContext().TraceID().String()) || !strings.Contains(buf.String(), `"svc":"tr"`) {
|
||||
t.Fatalf("line = %s", buf.String())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user