From 1c404d6474cc3ae3eb93a4c008ee5a1883438f56 Mon Sep 17 00:00:00 2001 From: oabrivard Date: Sat, 7 Feb 2026 23:49:38 +0100 Subject: [PATCH] Finished Task 7: Observability --- backend/go.work.sum | 47 ++-- backend/shared/go.mod | 30 ++- backend/shared/go.sum | 88 ++++++-- .../infra/observability/logging/logger.go | 13 +- .../observability/logging/logger_test.go | 9 + .../infra/observability/metrics/http.go | 12 + .../infra/observability/metrics/http_test.go | 21 ++ .../infra/observability/metrics/prometheus.go | 24 +- .../observability/metrics/prometheus_test.go | 21 ++ .../infra/observability/tracing/tracer.go | 210 ++++++++++++++++-- .../observability/tracing/tracer_test.go | 105 ++++++++- 11 files changed, 506 insertions(+), 74 deletions(-) create mode 100644 backend/shared/infra/observability/metrics/http.go create mode 100644 backend/shared/infra/observability/metrics/http_test.go diff --git a/backend/go.work.sum b/backend/go.work.sum index 6f05271..1ed8589 100644 --- a/backend/go.work.sum +++ b/backend/go.work.sum @@ -1,45 +1,46 @@ +cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= github.com/alecthomas/kingpin/v2 v2.4.0/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE= github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= -github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk= -github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= -github.com/alicebob/miniredis/v2 v2.33.0 h1:uvTF0EDeu9RLnUEG27Db5I68ESoIxTiXbNUiji6lZrA= -github.com/alicebob/miniredis/v2 v2.33.0/go.mod h1:MhP4a3EU7aENRi9aO+tHfTBZicLqQevyi/DJpoj6mi0= -github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= -github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= -github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/cncf/xds/go v0.0.0-20251022180443-0feb69152e9f/go.mod h1:HlzOvOjVBOfTGSRXRyY0OiCS/3J1akRGQQpRO/7zyF4= +github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329/go.mod h1:Alz8LEClvR7xKsrq3qzoc4N0guvVNSS8KmSChGYr9hs= +github.com/envoyproxy/go-control-plane/envoy v1.35.0/go.mod h1:09qwbGVuSWWAyN5t/b3iyVfz5+z8QWGrzkoqm/8SbEs= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= +github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= -github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= -github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= -github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= -github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0= -github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= -github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw= github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU= -github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= -github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= +go.opentelemetry.io/contrib/detectors/gcp v1.38.0/go.mod h1:SU+iU7nu5ud4oCb3LQOhIZ3nRLj6FNVrKgtflbaf2ts= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg= golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek= +golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/backend/shared/go.mod b/backend/shared/go.mod index c697291..d88306d 100644 --- a/backend/shared/go.mod +++ b/backend/shared/go.mod @@ -13,7 +13,11 @@ require ( github.com/prometheus/client_golang v1.20.5 github.com/redis/go-redis/v9 v9.7.0 github.com/rs/zerolog v1.33.0 - github.com/stretchr/testify v1.10.0 + github.com/stretchr/testify v1.11.1 + go.opentelemetry.io/otel v1.40.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0 + go.opentelemetry.io/otel/sdk v1.40.0 + go.opentelemetry.io/otel/trace v1.40.0 ) require ( @@ -21,18 +25,21 @@ require ( github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect github.com/andybalholm/brotli v1.1.0 // indirect github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/gofiber/utils/v2 v2.0.0-beta.4 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.7 // 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 github.com/klauspost/compress v1.17.9 // indirect - github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect @@ -45,12 +52,19 @@ require ( github.com/valyala/fasthttp v1.55.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect - golang.org/x/crypto v0.32.0 // indirect - golang.org/x/net v0.34.0 // indirect - golang.org/x/sync v0.10.0 // indirect - golang.org/x/sys v0.29.0 // indirect - golang.org/x/text v0.21.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 // indirect + go.opentelemetry.io/otel/metric v1.40.0 // indirect + go.opentelemetry.io/proto/otlp v1.9.0 // indirect + golang.org/x/crypto v0.47.0 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.40.0 // indirect + golang.org/x/text v0.33.0 // indirect golang.org/x/time v0.9.0 // indirect - google.golang.org/protobuf v1.34.2 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 // indirect + google.golang.org/grpc v1.78.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/backend/shared/go.sum b/backend/shared/go.sum index c3ef931..688b25c 100644 --- a/backend/shared/go.sum +++ b/backend/shared/go.sum @@ -3,23 +3,34 @@ github.com/MicahParks/jwkset v0.11.0/go.mod h1:U2oRhRaLgDCLjtpGL2GseNKGmZtLs/3O7 github.com/MicahParks/keyfunc/v3 v3.7.0 h1:pdafUNyq+p3ZlvjJX1HWFP7MA3+cLpDtg69U3kITJGM= github.com/MicahParks/keyfunc/v3 v3.7.0/go.mod h1:z66bkCviwqfg2YUp+Jcc/xRE9IXLcMq6DrgV/+Htru0= github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a h1:HbKu58rmZpUGpz5+4FfNmIU+FmZg2P3Xaj2v2bfNWmk= +github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= github.com/alicebob/miniredis/v2 v2.33.0 h1:uvTF0EDeu9RLnUEG27Db5I68ESoIxTiXbNUiji6lZrA= +github.com/alicebob/miniredis/v2 v2.33.0/go.mod h1:MhP4a3EU7aENRi9aO+tHfTBZicLqQevyi/DJpoj6mi0= github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +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/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= @@ -35,20 +46,30 @@ github.com/gofiber/utils/v2 v2.0.0-beta.4 h1:1gjbVFFwVwUb9arPcqiB6iEjHBwo7cHsyS4 github.com/gofiber/utils/v2 v2.0.0-beta.4/go.mod h1:sdRsPU1FXX6YiDGGxd+q2aPJRMzpsxdzCXo9dz+xtOY= github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8= github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +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.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 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/grpc-ecosystem/grpc-gateway/v2 v2.27.7 h1:X+2YciYSxvMQK0UZ7sg45ZVabVZBeBuvMkmuI2V3Fak= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.7/go.mod h1:lW34nIZuQ8UDPdkon5fmfp2l3+ZkQ2me/+oecHYLOII= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= +github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -71,16 +92,17 @@ github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65 github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8= github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasthttp v1.55.0 h1:Zkefzgt6a7+bVKHnu/YaYSOPfNYNisSVBo/unVCf8k8= @@ -88,22 +110,52 @@ github.com/valyala/fasthttp v1.55.0/go.mod h1:NkY9JtkrpPKmgwV3HTaS2HWaJss9RSIsRV github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= -golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= -golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms= +go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 h1:QKdN8ly8zEMrByybbQgv8cWBcdAarwmIPZ6FThrWXJs= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0/go.mod h1:bTdK1nhqF76qiPoCCdyFIV+N/sRHYXYCTQc+3VCi3MI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0 h1:wVZXIWjQSeSmMoxF74LzAnpVQOAFDo3pPji9Y4SOFKc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0/go.mod h1:khvBS2IggMFNwZK/6lEeHg/W57h/IX6J4URh57fuI40= +go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g= +go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc= +go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8= +go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE= +go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4AtAlbuWdCYw= +go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg= +go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw= +go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA= +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.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8= +golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= -golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= +golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= -google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +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-20260128011058-8636f8732409 h1:merA0rdPeUV3YIIfHHcH4qBkiQAc1nfCKSI7lB4cV2M= +google.golang.org/genproto/googleapis/api v0.0.0-20260128011058-8636f8732409/go.mod h1:fl8J1IvUjCilwZzQowmw2b7HQB2eAuYBabMXzWurF+I= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 h1:H86B94AW+VfJWDqFeEbBPhEtHzJwJfTbgE2lZa54ZAQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= +google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc= +google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U= +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= diff --git a/backend/shared/infra/observability/logging/logger.go b/backend/shared/infra/observability/logging/logger.go index 9d95748..991d740 100644 --- a/backend/shared/infra/observability/logging/logger.go +++ b/backend/shared/infra/observability/logging/logger.go @@ -11,11 +11,16 @@ import ( // Config holds the configuration for the logger. type Config struct { - Level string + // Level is the zerolog level string (e.g. debug, info, warn, error). + Level string + // Environment controls output format: development uses console, others use JSON. Environment string + // ServiceName is injected in every log event as the service field. ServiceName string - Version string - Output io.Writer + // Version is injected in every log event as the version field. + Version string + // Output defaults to stdout when nil. + Output io.Writer } // DefaultConfig returns a default configuration. @@ -63,7 +68,7 @@ func NewLogger(config Config) *Logger { logger = zerolog.New(output).With().Timestamp().Logger() } - // Add service metadata + // Add service metadata to every log line. logger = logger.With(). Str("service", config.ServiceName). Str("version", config.Version). diff --git a/backend/shared/infra/observability/logging/logger_test.go b/backend/shared/infra/observability/logging/logger_test.go index 87fa3f3..b83c729 100644 --- a/backend/shared/infra/observability/logging/logger_test.go +++ b/backend/shared/infra/observability/logging/logger_test.go @@ -30,3 +30,12 @@ func TestLogger_WithFields(t *testing.T) { require.NotNil(t, withFields) require.NotNil(t, logger.Zerolog()) } + +// TestDefaultConfig_Stable verifies defaults remain unchanged. +func TestDefaultConfig_Stable(t *testing.T) { + cfg := DefaultConfig() + require.Equal(t, "info", cfg.Level) + require.Equal(t, "development", cfg.Environment) + require.Equal(t, "knowfoolery", cfg.ServiceName) + require.Equal(t, "0.0.0", cfg.Version) +} diff --git a/backend/shared/infra/observability/metrics/http.go b/backend/shared/infra/observability/metrics/http.go new file mode 100644 index 0000000..7932b25 --- /dev/null +++ b/backend/shared/infra/observability/metrics/http.go @@ -0,0 +1,12 @@ +package metrics + +import ( + "net/http" + + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +// Handler returns a standard Prometheus metrics HTTP handler. +func Handler() http.Handler { + return promhttp.Handler() +} diff --git a/backend/shared/infra/observability/metrics/http_test.go b/backend/shared/infra/observability/metrics/http_test.go new file mode 100644 index 0000000..9f27fc1 --- /dev/null +++ b/backend/shared/infra/observability/metrics/http_test.go @@ -0,0 +1,21 @@ +package metrics + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestHandler verifies Handler returns a usable HTTP handler. +func TestHandler(t *testing.T) { + h := Handler() + require.NotNil(t, h) + + req := httptest.NewRequest(http.MethodGet, "/metrics", nil) + rr := httptest.NewRecorder() + + h.ServeHTTP(rr, req) + require.Equal(t, http.StatusOK, rr.Code) +} diff --git a/backend/shared/infra/observability/metrics/prometheus.go b/backend/shared/infra/observability/metrics/prometheus.go index ca2d08c..8b37e6c 100644 --- a/backend/shared/infra/observability/metrics/prometheus.go +++ b/backend/shared/infra/observability/metrics/prometheus.go @@ -2,8 +2,12 @@ package metrics import ( + "strconv" + "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" + + "knowfoolery/backend/shared/infra/utils/envutil" ) // Config holds the configuration for metrics. @@ -204,6 +208,22 @@ func NewMetrics(config Config) *Metrics { // ConfigFromEnv creates a Config from environment variables. func ConfigFromEnv() Config { - // TODO: Implement environment variable parsing - return DefaultConfig() + cfg := DefaultConfig() + cfg.ServiceName = envutil.String("METRICS_SERVICE_NAME", cfg.ServiceName) + cfg.Enabled = parseBoolEnv("METRICS_ENABLED", cfg.Enabled) + return cfg +} + +func parseBoolEnv(key string, fallback bool) bool { + value := envutil.String(key, "") + if value == "" { + return fallback + } + + parsed, err := strconv.ParseBool(value) + if err != nil { + return fallback + } + + return parsed } diff --git a/backend/shared/infra/observability/metrics/prometheus_test.go b/backend/shared/infra/observability/metrics/prometheus_test.go index bbe9c4d..8f5ee7b 100644 --- a/backend/shared/infra/observability/metrics/prometheus_test.go +++ b/backend/shared/infra/observability/metrics/prometheus_test.go @@ -19,3 +19,24 @@ func TestNewMetrics_WithCustomRegistry(t *testing.T) { require.NotNil(t, m.DBConnectionsActive) require.NotNil(t, m.ScoreDistribution) } + +// TestConfigFromEnvDefaults verifies default env behavior. +func TestConfigFromEnvDefaults(t *testing.T) { + t.Setenv("METRICS_ENABLED", "") + t.Setenv("METRICS_SERVICE_NAME", "") + + cfg := ConfigFromEnv() + def := DefaultConfig() + + require.Equal(t, def, cfg) +} + +// TestConfigFromEnvOverrides verifies valid env overrides. +func TestConfigFromEnvOverrides(t *testing.T) { + t.Setenv("METRICS_ENABLED", "false") + t.Setenv("METRICS_SERVICE_NAME", "admin-service") + + cfg := ConfigFromEnv() + require.False(t, cfg.Enabled) + require.Equal(t, "admin-service", cfg.ServiceName) +} diff --git a/backend/shared/infra/observability/tracing/tracer.go b/backend/shared/infra/observability/tracing/tracer.go index 6fc2950..dd02fe9 100644 --- a/backend/shared/infra/observability/tracing/tracer.go +++ b/backend/shared/infra/observability/tracing/tracer.go @@ -4,6 +4,19 @@ package tracing import ( "context" "fmt" + "net/url" + "strconv" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.26.0" + oteltrace "go.opentelemetry.io/otel/trace" + + "knowfoolery/backend/shared/infra/utils/envutil" ) // Config holds the configuration for the tracer. @@ -11,6 +24,8 @@ type Config struct { ServiceName string ServiceVersion string Environment string + OTLPEndpoint string + // JaegerEndpoint is a deprecated legacy alias kept for backward compatibility. JaegerEndpoint string SampleRate float64 Enabled bool @@ -22,6 +37,7 @@ func DefaultConfig() Config { ServiceName: "knowfoolery", ServiceVersion: "0.0.0", Environment: "development", + OTLPEndpoint: "http://localhost:4318/v1/traces", JaegerEndpoint: "http://localhost:14268/api/traces", SampleRate: 1.0, // Sample all traces in development Enabled: false, @@ -29,43 +45,87 @@ func DefaultConfig() Config { } // Tracer provides distributed tracing functionality. -// This is a placeholder that should be implemented with OpenTelemetry. type Tracer struct { - config Config + config Config + provider *sdktrace.TracerProvider + tracer oteltrace.Tracer + enabled bool } // NewTracer creates a new Tracer. -// Note: Actual implementation should use OpenTelemetry SDK. func NewTracer(config Config) (*Tracer, error) { if !config.Enabled { - return &Tracer{config: config}, nil + return &Tracer{ + config: config, + tracer: otel.Tracer(config.ServiceName), + enabled: false, + }, nil + } + + sampleRate := config.SampleRate + if sampleRate < 0 || sampleRate > 1 { + sampleRate = 1.0 + } + + endpoint := config.OTLPEndpoint + if endpoint == "" { + endpoint = config.JaegerEndpoint + } + + exporter, err := newOTLPHTTPExporter(endpoint) + if err != nil { + return nil, fmt.Errorf("create otlp exporter: %w", err) + } + + res, err := resource.New( + context.Background(), + resource.WithAttributes( + semconv.ServiceName(config.ServiceName), + semconv.ServiceVersion(config.ServiceVersion), + attribute.String("deployment.environment", config.Environment), + ), + ) + if err != nil { + return nil, fmt.Errorf("create tracer resource: %w", err) } - // TODO: Initialize OpenTelemetry tracer provider - // Example implementation: - // - Create Jaeger exporter - // - Create tracer provider with batching - // - Set global tracer provider - // - Configure resource with service info + provider := sdktrace.NewTracerProvider( + sdktrace.WithBatcher(exporter), + sdktrace.WithSampler(sdktrace.TraceIDRatioBased(sampleRate)), + sdktrace.WithResource(res), + ) - return &Tracer{config: config}, nil + otel.SetTracerProvider(provider) + + return &Tracer{ + config: config, + provider: provider, + tracer: otel.Tracer(config.ServiceName), + enabled: true, + }, nil } // Shutdown gracefully shuts down the tracer. func (t *Tracer) Shutdown(ctx context.Context) error { - if !t.config.Enabled { + if !t.enabled || t.provider == nil { return nil } - // TODO: Shutdown tracer provider + if err := t.provider.Shutdown(ctx); err != nil { + return fmt.Errorf("shutdown tracer provider: %w", err) + } + return nil } // StartSpan starts a new span. -// This is a placeholder that should be implemented with OpenTelemetry. func (t *Tracer) StartSpan(ctx context.Context, name string) (context.Context, Span) { - // TODO: Start actual OpenTelemetry span - return ctx, &noopSpan{} + if !t.enabled || t.tracer == nil { + return ctx, &noopSpan{} + } + + spanCtx, span := t.tracer.Start(ctx, name) + return spanCtx, &otelSpan{span: span} } // Span represents a tracing span. @@ -85,6 +145,41 @@ func (s *noopSpan) End() {} func (s *noopSpan) SetAttribute(key string, value interface{}) {} func (s *noopSpan) RecordError(err error) {} +// otelSpan wraps an OpenTelemetry span with the local Span interface. +type otelSpan struct { + span oteltrace.Span +} + +func (s *otelSpan) End() { + s.span.End() +} + +func (s *otelSpan) SetAttribute(key string, value interface{}) { + switch v := value.(type) { + case string: + s.span.SetAttributes(attribute.String(key, v)) + case int: + s.span.SetAttributes(attribute.Int(key, v)) + case int64: + s.span.SetAttributes(attribute.Int64(key, v)) + case float64: + s.span.SetAttributes(attribute.Float64(key, v)) + case bool: + s.span.SetAttributes(attribute.Bool(key, v)) + default: + s.span.SetAttributes(attribute.String(key, fmt.Sprint(value))) + } +} + +func (s *otelSpan) RecordError(err error) { + if err == nil { + return + } + + s.span.RecordError(err) + s.span.SetStatus(codes.Error, err.Error()) +} + // TraceServiceOperation traces a service operation. func TraceServiceOperation(ctx context.Context, tracer *Tracer, serviceName, operation string, fn func(context.Context) error) error { @@ -122,6 +217,85 @@ func TraceDatabaseOperation(ctx context.Context, tracer *Tracer, operation, // ConfigFromEnv creates a Config from environment variables. func ConfigFromEnv() Config { - // TODO: Implement environment variable parsing - return DefaultConfig() + cfg := DefaultConfig() + + cfg.Enabled = parseBoolEnv("TRACING_ENABLED", cfg.Enabled) + cfg.ServiceName = envutil.String("TRACING_SERVICE_NAME", cfg.ServiceName) + cfg.ServiceVersion = envutil.String("TRACING_SERVICE_VERSION", cfg.ServiceVersion) + cfg.Environment = envutil.String("TRACING_ENVIRONMENT", cfg.Environment) + legacyEndpoint := envutil.String("TRACING_JAEGER_ENDPOINT", "") + if legacyEndpoint != "" { + cfg.JaegerEndpoint = legacyEndpoint + } + cfg.OTLPEndpoint = envutil.String("TRACING_OTLP_ENDPOINT", "") + if cfg.OTLPEndpoint == "" && legacyEndpoint != "" { + cfg.OTLPEndpoint = legacyEndpoint + } + if cfg.OTLPEndpoint == "" { + cfg.OTLPEndpoint = DefaultConfig().OTLPEndpoint + } + cfg.SampleRate = parseFloatEnv("TRACING_SAMPLE_RATE", cfg.SampleRate) + + return cfg +} + +func newOTLPHTTPExporter(endpoint string) (sdktrace.SpanExporter, error) { + parsed, err := url.Parse(endpoint) + if err != nil { + return nil, fmt.Errorf("parse endpoint: %w", err) + } + if parsed.Scheme == "" || parsed.Host == "" { + return nil, fmt.Errorf("endpoint must be absolute URL, got %q", endpoint) + } + if parsed.Scheme != "http" && parsed.Scheme != "https" { + return nil, fmt.Errorf("unsupported endpoint scheme %q", parsed.Scheme) + } + + urlPath := parsed.EscapedPath() + if urlPath == "" || urlPath == "/" { + urlPath = "/v1/traces" + } + + options := []otlptracehttp.Option{ + otlptracehttp.WithEndpoint(parsed.Host), + otlptracehttp.WithURLPath(urlPath), + } + if parsed.Scheme == "http" { + options = append(options, otlptracehttp.WithInsecure()) + } + + exporter, err := otlptracehttp.New(context.Background(), options...) + if err != nil { + return nil, err + } + + return exporter, nil +} + +func parseBoolEnv(key string, fallback bool) bool { + value := envutil.String(key, "") + if value == "" { + return fallback + } + + parsed, err := strconv.ParseBool(value) + if err != nil { + return fallback + } + + return parsed +} + +func parseFloatEnv(key string, fallback float64) float64 { + value := envutil.String(key, "") + if value == "" { + return fallback + } + + parsed, err := strconv.ParseFloat(value, 64) + if err != nil { + return fallback + } + + return parsed } diff --git a/backend/shared/infra/observability/tracing/tracer_test.go b/backend/shared/infra/observability/tracing/tracer_test.go index 6607580..3a9b43e 100644 --- a/backend/shared/infra/observability/tracing/tracer_test.go +++ b/backend/shared/infra/observability/tracing/tracer_test.go @@ -1,6 +1,6 @@ package tracing -// Tests for tracing helpers invoking operations and propagating errors. +// Tests for tracing initialization, config parsing, and helper wrappers. import ( "context" @@ -10,6 +10,45 @@ import ( "github.com/stretchr/testify/require" ) +// TestNewTracer_Disabled verifies disabled mode initializes and safely starts spans. +func TestNewTracer_Disabled(t *testing.T) { + cfg := DefaultConfig() + cfg.Enabled = false + + tracer, err := NewTracer(cfg) + require.NoError(t, err) + require.NotNil(t, tracer) + + ctx, span := tracer.StartSpan(context.Background(), "test") + require.NotNil(t, ctx) + require.NotNil(t, span) + require.NotPanics(t, func() { + span.SetAttribute("k", "v") + span.RecordError(errors.New("boom")) + span.End() + }) +} + +// TestNewTracer_Enabled verifies enabled mode initializes tracer components. +func TestNewTracer_Enabled(t *testing.T) { + cfg := DefaultConfig() + cfg.Enabled = true + + tracer, err := NewTracer(cfg) + require.NoError(t, err) + require.NotNil(t, tracer) + require.NoError(t, tracer.Shutdown(context.Background())) +} + +// TestShutdown_Disabled verifies shutdown is a no-op when tracing is disabled. +func TestShutdown_Disabled(t *testing.T) { + tracer, err := NewTracer(DefaultConfig()) + require.NoError(t, err) + + err = tracer.Shutdown(context.Background()) + require.NoError(t, err) +} + // TestTraceServiceOperation verifies tracing wraps a service operation and returns errors. func TestTraceServiceOperation(t *testing.T) { tracer, err := NewTracer(DefaultConfig()) @@ -35,3 +74,67 @@ func TestTraceDatabaseOperation(t *testing.T) { require.NoError(t, err) require.True(t, called) } + +// TestConfigFromEnvDefaults verifies defaults are used when env vars are absent or empty. +func TestConfigFromEnvDefaults(t *testing.T) { + t.Setenv("TRACING_ENABLED", "") + t.Setenv("TRACING_SERVICE_NAME", "") + t.Setenv("TRACING_SERVICE_VERSION", "") + t.Setenv("TRACING_ENVIRONMENT", "") + t.Setenv("TRACING_OTLP_ENDPOINT", "") + t.Setenv("TRACING_JAEGER_ENDPOINT", "") + t.Setenv("TRACING_SAMPLE_RATE", "") + + cfg := ConfigFromEnv() + def := DefaultConfig() + + require.Equal(t, def, cfg) +} + +// TestConfigFromEnvOverrides verifies valid env vars override defaults. +func TestConfigFromEnvOverrides(t *testing.T) { + t.Setenv("TRACING_ENABLED", "true") + t.Setenv("TRACING_SERVICE_NAME", "gateway") + t.Setenv("TRACING_SERVICE_VERSION", "1.2.3") + t.Setenv("TRACING_ENVIRONMENT", "production") + t.Setenv("TRACING_OTLP_ENDPOINT", "https://otel-collector:4318/v1/traces") + t.Setenv("TRACING_JAEGER_ENDPOINT", "http://jaeger:14268/api/traces") + t.Setenv("TRACING_SAMPLE_RATE", "0.25") + + cfg := ConfigFromEnv() + require.True(t, cfg.Enabled) + require.Equal(t, "gateway", cfg.ServiceName) + require.Equal(t, "1.2.3", cfg.ServiceVersion) + require.Equal(t, "production", cfg.Environment) + require.Equal(t, "https://otel-collector:4318/v1/traces", cfg.OTLPEndpoint) + require.Equal(t, "http://jaeger:14268/api/traces", cfg.JaegerEndpoint) + require.Equal(t, 0.25, cfg.SampleRate) +} + +// TestConfigFromEnvInvalidSampleRate verifies invalid sample rate falls back to default. +func TestConfigFromEnvInvalidSampleRate(t *testing.T) { + t.Setenv("TRACING_SAMPLE_RATE", "not-a-float") + + cfg := ConfigFromEnv() + require.Equal(t, DefaultConfig().SampleRate, cfg.SampleRate) +} + +// TestConfigFromEnvLegacyEndpointFallback verifies legacy env var is used when OTLP endpoint is unset. +func TestConfigFromEnvLegacyEndpointFallback(t *testing.T) { + t.Setenv("TRACING_OTLP_ENDPOINT", "") + t.Setenv("TRACING_JAEGER_ENDPOINT", "http://legacy:14268/api/traces") + + cfg := ConfigFromEnv() + require.Equal(t, "http://legacy:14268/api/traces", cfg.OTLPEndpoint) + require.Equal(t, "http://legacy:14268/api/traces", cfg.JaegerEndpoint) +} + +// TestConfigFromEnvEndpointPrecedence verifies OTLP endpoint has precedence over legacy Jaeger endpoint. +func TestConfigFromEnvEndpointPrecedence(t *testing.T) { + t.Setenv("TRACING_OTLP_ENDPOINT", "https://collector:4318/v1/traces") + t.Setenv("TRACING_JAEGER_ENDPOINT", "http://legacy:14268/api/traces") + + cfg := ConfigFromEnv() + require.Equal(t, "https://collector:4318/v1/traces", cfg.OTLPEndpoint) + require.Equal(t, "http://legacy:14268/api/traces", cfg.JaegerEndpoint) +}