42 Commits

Author SHA1 Message Date
340cf67515 update changelog 2025-08-27 10:33:39 -04:00
f5cb3456b1 fix otel http instrumentation span naming (#2)
Reviewed-on: #2
Co-authored-by: Ryan D McGuire <ryand_mcguire@sweetwater.com>
Co-committed-by: Ryan D McGuire <ryand_mcguire@sweetwater.com>
2025-08-27 14:32:16 +00:00
ede5bc92f7 update changelog 2025-08-26 14:53:03 -04:00
063ff0f1d0 feat: adds configurable HTTP request path exclusion from logging 2025-08-26 14:51:39 -04:00
2310ac574c update changelog 2025-08-24 11:52:08 -04:00
cb0c87d200 refactors HTTP server initialization, improves logging middleware, and updates documentation (#1)
Reviewed-on: #1
2025-08-24 15:50:34 +00:00
92e78f533a add CHANGELOG 2025-08-14 09:14:14 -04:00
d4c6ecbefd upgrade deps, pin annoying otlptranslator 2025-08-14 09:12:17 -04:00
e1d58c0094 improves godoc comments for gRPC server and logger components 2025-08-14 09:03:44 -04:00
9cee9037e4 Merge branch 'main' of gitea.libretechconsulting.com:rmcguire/go-app 2025-08-13 16:02:00 -04:00
318115690d Exports OTEL initialization function and adds extensive documentation across packages for improved clarity. 2025-08-13 16:01:51 -04:00
8b4bb890be update TODO 2025-08-10 17:46:09 -04:00
e841e11168 updates dummy health check to ensure positive duration 2025-08-02 11:01:25 -04:00
7c78416948 update go deps 2025-07-31 14:28:16 -04:00
31fc6dca16 add protovalidate support 2025-07-21 16:53:40 -04:00
41d539a607 update TODO 2025-07-20 12:55:38 -04:00
a875f0bb22 go mod updates 2025-07-20 10:59:16 -04:00
52752216fd upgrade packages 2025-05-04 10:06:01 -04:00
4f0c5fe665 fix broken startup on disabled servers 2025-03-30 11:27:41 -04:00
5c26accc34 update TODO 2025-03-26 12:58:32 -04:00
f8279d9653 fix handler strip path 2025-03-26 08:30:51 -04:00
b44b6a331c support runtime.ServeMux opts for grpc-gateway 2025-03-25 10:49:58 -04:00
adfedc9239 assert trailing slash for handler prefixes 2025-03-25 10:49:47 -04:00
89f016ed9d update TODO 2025-03-24 16:46:45 -04:00
7f60a59d42 implement grpc gateway and addl handler support 2025-03-24 16:39:11 -04:00
262f6a4232 implement grpc gateway and addl handler support 2025-03-24 16:24:03 -04:00
4e014d5ea0 start implementing gw serve mux support 2025-03-24 12:43:53 -04:00
3e319b24fd support json schema 2025-03-22 14:02:39 -04:00
f0a699029a improve server startup 2025-03-07 17:19:42 -05:00
e178956eef improve grpc lifecycle 2025-03-07 17:04:46 -05:00
c5da5f7887 improve grpc lifecycle 2025-03-07 16:45:50 -05:00
d414754e14 add grpc support 2025-03-07 15:24:54 -05:00
3b3f7f1f8b add grpc support 2025-03-07 15:24:36 -05:00
00c8e2e4fc add grpc support 2025-03-07 15:19:05 -05:00
2cf15a4837 add grpc support 2025-03-07 13:00:45 -05:00
98fba4eac8 add grpc support 2025-03-07 11:44:50 -05:00
5aa5dda111 add grpc support 2025-03-07 11:16:32 -05:00
81676c5404 add weather grpc 2025-03-07 08:42:38 -05:00
075902ecd8 add grpc support 2025-03-06 17:18:39 -05:00
a83abba4ce add grpc support 2025-03-06 17:17:59 -05:00
e11c563c3a add grpc support 2025-03-06 17:16:27 -05:00
96f9213213 Disable insecure otlpgrpcmetric, upgrades 2025-02-15 14:41:34 -05:00
35 changed files with 1350 additions and 459 deletions

24
CHANGELOG.md Normal file
View File

@@ -0,0 +1,24 @@
# v0.12.1
* feat: Implement custom OpenTelemetry span name formatting for HTTP requests.
* refactor: Streamline OpenTelemetry handler integration by removing custom wrapper.
# v0.12.0
* feat: Add support for excluding HTTP request paths from logging using configurable regular expressions.
# v0.11.1:
* docs: Add comprehensive package-level documentation for the `http` package.
* docs: Improve documentation for the `InitHTTPServer` function.
* feat: Introduce specific logging for HTTP 204 (No Content) responses, omitting body logging.
* fix: Enhance error handling and logging for empty or unreadable HTTP response bodies.
* chore: Refine HTTP response log messages for improved clarity and consistency.
* docs: Update documentation for the `Flush` method in `LoggingResponseWriter`
# v0.11.0:
* Updated `github.com/prometheus/client_golang` dependency to v1.23.0.
* Updated `google.golang.org/grpc` dependency to v1.74.2.
* Added a `replace` directive for `github.com/prometheus/otlptranslator`.
* Renamed `initOTEL` function to `InitOTEL` and added a check to prevent re-initialization.
* Improved `dummyHealthCheck` to ensure a positive random duration.
* Added comprehensive package, struct, and function comments across `pkg/app`, `pkg/config`, `pkg/logging`, `pkg/otel`, `pkg/srv/grpc`, and `pkg/srv/http` for improved clarity.
* Corrected typos in `TODO.md` for "implementing" and "support".
* Added a new item to `TODO.md` for early OpenTelemetry initialization.

11
TODO.md
View File

@@ -1,8 +1,17 @@
# TODO
- [x] Pattern for extending config
- [ ] Add ability to initialize OTEL early (before app runs)
- [ ] Spruce up the README
- [ ] Create generic interface for implementing a service
- [ ] Create config sample not called demo, so it is more easily reused
- [ ] Expand config test case to cover GRPC config
- [ ] Expand tracing
## Done
- [x] Test and troubleshoot GRPC Gateway support
- [x] Finish implementing GRPC service support
- [x] Unit tests
- [x] Pattern for extending config
- [x] HTTP Logging Middleware
- [x] Fix panic with OTEL disabled

74
go.mod
View File

@@ -1,49 +1,63 @@
module gitea.libretechconsulting.com/rmcguire/go-app
go 1.23.4
go 1.24.2
replace github.com/prometheus/otlptranslator => github.com/prometheus/otlptranslator v0.0.0-20250717125610-8549f4ab4f8f
require (
buf.build/go/protovalidate v0.14.0
github.com/caarlos0/env/v11 v11.3.1
github.com/prometheus/client_golang v1.20.5
github.com/rs/zerolog v1.33.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0
go.opentelemetry.io/otel v1.34.0
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.34.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0
go.opentelemetry.io/otel/exporters/prometheus v0.56.0
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.34.0
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.34.0
go.opentelemetry.io/otel/metric v1.34.0
go.opentelemetry.io/otel/sdk v1.34.0
go.opentelemetry.io/otel/sdk/metric v1.34.0
go.opentelemetry.io/otel/trace v1.34.0
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1
github.com/prometheus/client_golang v1.23.0
github.com/rs/zerolog v1.34.0
github.com/swaggest/jsonschema-go v0.3.78
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0
go.opentelemetry.io/otel v1.37.0
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0
go.opentelemetry.io/otel/exporters/prometheus v0.59.1
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.37.0
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.37.0
go.opentelemetry.io/otel/metric v1.37.0
go.opentelemetry.io/otel/sdk v1.37.0
go.opentelemetry.io/otel/sdk/metric v1.37.0
go.opentelemetry.io/otel/trace v1.37.0
google.golang.org/grpc v1.74.2
gopkg.in/yaml.v3 v3.0.1
)
require (
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.7-20250717185734-6c6e0d3c608e.1 // indirect
cel.dev/expr v0.24.0 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/beorn7/perks v1.0.1 // 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/felixge/httpsnoop v1.0.4 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/google/cel-go v0.26.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.0 // indirect
github.com/klauspost/compress v1.17.11 // indirect
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.62.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.65.0 // indirect
github.com/prometheus/otlptranslator v0.0.0-20250717125610-8549f4ab4f8f // indirect
github.com/prometheus/procfs v0.17.0 // indirect
github.com/stoewer/go-strcase v1.3.1 // indirect
github.com/swaggest/refl v1.4.0 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 // indirect
go.opentelemetry.io/proto/otlp v1.5.0 // indirect
golang.org/x/net v0.34.0 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.21.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250127172529-29210b9bc287 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 // indirect
google.golang.org/grpc v1.70.0 // indirect
google.golang.org/protobuf v1.36.4 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 // indirect
go.opentelemetry.io/proto/otlp v1.7.1 // indirect
golang.org/x/exp v0.0.0-20250813145105-42675adae3e6 // indirect
golang.org/x/net v0.43.0 // indirect
golang.org/x/sys v0.35.0 // indirect
golang.org/x/text v0.28.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250811230008-5f3141c8851a // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250811230008-5f3141c8851a // indirect
google.golang.org/protobuf v1.36.7 // indirect
)

217
go.sum
View File

@@ -1,41 +1,59 @@
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.7-20250717185734-6c6e0d3c608e.1 h1:/AZH8sVB6LHv8G+hZlAMCP31NevnesHwYgnlgS5Vt14=
buf.build/gen/go/bufbuild/protovalidate/protocolbuffers/go v1.36.7-20250717185734-6c6e0d3c608e.1/go.mod h1:eva/VCrd8X7xuJw+JtwCEyrCKiRRASukFqmirnWBvFU=
buf.build/go/protovalidate v0.14.0 h1:kr/rC/no+DtRyYX+8KXLDxNnI1rINz0imk5K44ZpZ3A=
buf.build/go/protovalidate v0.14.0/go.mod h1:+F/oISho9MO7gJQNYC2VWLzcO1fTPmaTA08SDYJZncA=
cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY=
cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
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/bool64/dev v0.2.39 h1:kP8DnMGlWXhGYJEZE/J0l/gVBdbuhoPGL+MJG4QbofE=
github.com/bool64/dev v0.2.39/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
github.com/bool64/shared v0.1.5 h1:fp3eUhBsrSjNCQPcSdQqZxxh9bBwrYiZ+zOKFkM0/2E=
github.com/bool64/shared v0.1.5/go.mod h1:081yz68YC9jeFB3+Bbmno2RFWvGKv1lPKkMP6MHJlPs=
github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
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/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
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/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
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/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
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.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/cel-go v0.26.0 h1:DPGjXackMpJWH680oGY4lZhYjIameYmR+/6RBdDGmaI=
github.com/google/cel-go v0.26.0/go.mod h1:A9O8OU9rdvrK5MQyrqfIxo1a0u4g3sF8KB6PUIaryMM=
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.25.1 h1:VNqngBF40hVlDloBruUehVYC3ArSgIyScOAyMRqBxRg=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1/go.mod h1:RBRO7fro65R6tjKzYgLAFo0t1QEXY1Dp+i/bvpRiqiQ=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.0 h1:VD1gqscl4nYs1YxVuSdemTrSgTKrwOWDK0FVFMqm+Cg=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.0/go.mod h1:4EgsQoS4TOhJizV+JTFg40qx1Ofh3XmXEQNBpgvNT40=
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc h1:GN2Lv3MGO7AS6PrRoT6yV5+wkrOpcszoIsO4+4ds248=
github.com/grafana/regexp v0.0.0-20240518133315-a468a5bfb3bc/go.mod h1:+JKpmjMGhpgPL+rXZ5nsZieVzvarn86asRlBg4uNGnk=
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2 h1:sGm2vDRFUrQJO/Veii4h4zG2vvqG6uWNkBHSTqXOZk0=
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2/go.mod h1:wd1YpapPLivG6nQgbf7ZkG1hhSOXDhhn4MLTknx2aAc=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 h1:X5VWvz21y3gzm9Nw/kaUeku/1+uBhcekkmy4IkffJww=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1/go.mod h1:Zanoh4+gvIgluNqcfMVTJueD4wSS5hT7zTt4Mrutd90=
github.com/iancoleman/orderedmap v0.3.0 h1:5cbR2grmZR/DiVt+VJopEhtVs9YGInGIxAoMJn+Ichc=
github.com/iancoleman/orderedmap v0.3.0/go.mod h1:XuLcCUkdL5owUCQeF2Ue9uuw1EptkJDkXXS7VoV7XGE=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
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/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
@@ -48,114 +66,97 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y=
github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
github.com/prometheus/common v0.61.0 h1:3gv/GThfX0cV2lpO7gkTUwZru38mxevy90Bj8YFSRQQ=
github.com/prometheus/common v0.61.0/go.mod h1:zr29OCN/2BsJRaFwG8QOBr41D6kkchKbpeNH7pAjb/s=
github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io=
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
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/prometheus/client_golang v1.23.0 h1:ust4zpdl9r4trLY/gSjlm07PuiBq2ynaXXlptpfy8Uc=
github.com/prometheus/client_golang v1.23.0/go.mod h1:i/o0R9ByOnHX0McrTMTyhYvKE4haaf2mW08I+jGAjEE=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.65.0 h1:QDwzd+G1twt//Kwj/Ww6E9FQq1iVMmODnILtW1t2VzE=
github.com/prometheus/common v0.65.0/go.mod h1:0gZns+BLRQ3V6NdaerOhMbwwRbNh9hkGINtQAsP5GS8=
github.com/prometheus/otlptranslator v0.0.0-20250717125610-8549f4ab4f8f h1:QQB6SuvGZjK8kdc2YaLJpYhV8fxauOsjE6jgcL6YJ8Q=
github.com/prometheus/otlptranslator v0.0.0-20250717125610-8549f4ab4f8f/go.mod h1:P8AwMgdD7XEr6QRUJ2QWLpiAZTgTE2UYgjlu3svompI=
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
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/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/stoewer/go-strcase v1.3.1 h1:iS0MdW+kVTxgMoE1LAZyMiYJFKlOzLooE4MxjirtkAs=
github.com/stoewer/go-strcase v1.3.1/go.mod h1:fAH5hQ5pehh+j3nZfvwdk2RgEgQjAoM8wodgtPmh1xo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
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/swaggest/assertjson v1.9.0 h1:dKu0BfJkIxv/xe//mkCrK5yZbs79jL7OVf9Ija7o2xQ=
github.com/swaggest/assertjson v1.9.0/go.mod h1:b+ZKX2VRiUjxfUIal0HDN85W0nHPAYUbYH5WkkSsFsU=
github.com/swaggest/jsonschema-go v0.3.78 h1:5+YFQrLxOR8z6CHvgtZc42WRy/Q9zRQQ4HoAxlinlHw=
github.com/swaggest/jsonschema-go v0.3.78/go.mod h1:4nniXBuE+FIGkOGuidjOINMH7OEqZK3HCSbfDuLRI0g=
github.com/swaggest/refl v1.4.0 h1:CftOSdTqRqs100xpFOT/Rifss5xBV/CT0S/FN60Xe9k=
github.com/swaggest/refl v1.4.0/go.mod h1:4uUVFVfPJ0NSX9FPwMPspeHos9wPFlCMGoPRllUbpvA=
github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=
github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM=
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I=
go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw=
go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I=
go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0 h1:7F29RDmnlqk6B5d+sUqemt8TBfDqxryYW5gX6L74RFA=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0/go.mod h1:ZiGDq7xwDMKmWDrN1XsXAj0iC7hns+2DhxBFSncNHSE=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.34.0 h1:ajl4QczuJVA2TU9W9AGw++86Xga/RKt//16z/yxPgdk=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.34.0/go.mod h1:Vn3/rlOJ3ntf/Q3zAI0V5lDnTbHGaUsNUeF6nZmm7pA=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 h1:Vh5HayB/0HHfOQA7Ctx69E/Y/DcQSMPpKANYVMQ7fBA=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0/go.mod h1:cpgtDBaqD/6ok/UG0jT15/uKjAY8mRA53diogHBg3UI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0 h1:OeNbIYk/2C15ckl7glBlOBp5+WlYsOElzTNmiPW/x60=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.34.0/go.mod h1:7Bept48yIeqxP2OZ9/AqIpYS94h2or0aB4FypJTc8ZM=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0 h1:5pojmb1U1AogINhN3SurB+zm/nIcusopeBNp42f45QM=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0/go.mod h1:57gTHJSE5S1tqg+EKsLPlTWhpHMsWlVmer+LA926XiA=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0 h1:tgJ0uaNS4c98WRNUEx5U3aDlrDOI5Rs+1Vifcw4DJ8U=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.34.0/go.mod h1:U7HYyW0zt/a9x5J1Kjs+r1f/d4ZHnYFclhYY2+YbeoE=
go.opentelemetry.io/otel/exporters/prometheus v0.55.0 h1:sSPw658Lk2NWAv74lkD3B/RSDb+xRFx46GjkrL3VUZo=
go.opentelemetry.io/otel/exporters/prometheus v0.55.0/go.mod h1:nC00vyCmQixoeaxF6KNyP42II/RHa9UdruK02qBmHvI=
go.opentelemetry.io/otel/exporters/prometheus v0.56.0 h1:GnCIi0QyG0yy2MrJLzVrIM7laaJstj//flf1zEJCG+E=
go.opentelemetry.io/otel/exporters/prometheus v0.56.0/go.mod h1:JQcVZtbIIPM+7SWBB+T6FK+xunlyidwLp++fN0sUaOk=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0 h1:FiOTYABOX4tdzi8A0+mtzcsTmi6WBOxk66u0f1Mj9Gs=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0/go.mod h1:xyo5rS8DgzV0Jtsht+LCEMwyiDbjpsxBpWETwFRF0/4=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.34.0 h1:czJDQwFrMbOr9Kk+BPo1y8WZIIFIK58SA1kykuVeiOU=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.34.0/go.mod h1:lT7bmsxOe58Tq+JIOkTQMCGXdu47oA+VJKLZHbaBKbs=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0 h1:W5AWUn/IVe8RFb5pZx1Uh9Laf/4+Qmm4kJL5zPuvR+0=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0/go.mod h1:mzKxJywMNBdEX8TSJais3NnsVZUaJ+bAy6UxPTng2vk=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.34.0 h1:jBpDk4HAUsrnVO1FsfCfCOTEc/MkInJmvfCHYLFiT80=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.34.0/go.mod h1:H9LUIM1daaeZaz91vZcfeM0fejXPmgCYE8ZhzqfJuiU=
go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ=
go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M=
go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM=
go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM=
go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
go.opentelemetry.io/otel/sdk/metric v1.33.0 h1:Gs5VK9/WUJhNXZgn8MR6ITatvAmKeIuCtNbsP3JkNqU=
go.opentelemetry.io/otel/sdk/metric v1.33.0/go.mod h1:dL5ykHZmm1B1nVRk9dDjChwDmt81MjVp3gLkQRwKf/Q=
go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s=
go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck=
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
go.opentelemetry.io/proto/otlp v1.4.0 h1:TA9WRvW6zMwP+Ssb6fLoUIuirti1gGbP28GcKG1jgeg=
go.opentelemetry.io/proto/otlp v1.4.0/go.mod h1:PPBWZIP98o2ElSqI35IHfu7hIhSwvc5N38Jw8pXuGFY=
go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4=
go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0 h1:rbRJ8BBoVMsQShESYZ0FkvcITu8X8QNwJogcLUmDNNw=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0/go.mod h1:ru6KHrNtNHxM4nD/vd6QrLVWgKhxPYgblq4VAtNawTQ=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY=
go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0 h1:zG8GlgXCJQd5BU98C0hZnBbElszTmUgCNCfYneaDL0A=
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0/go.mod h1:hOfBCz8kv/wuq73Mx2H2QnWokh/kHZxkh6SNF2bdKtw=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 h1:Ahq7pZmv87yiyn3jeFz/LekZmPLLdKejuO3NcK9MssM=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0/go.mod h1:MJTqhM0im3mRLw1i8uGHnCvUEeS7VwRyxlLC78PA18M=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 h1:EtFWSnwW9hGObjkIdmlnWSydO+Qs8OwzfzXLUPg4xOc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0/go.mod h1:QjUEoiGCPkvFZ/MjK6ZZfNOS6mfVEVKYE99dFhuN2LI=
go.opentelemetry.io/otel/exporters/prometheus v0.59.1 h1:HcpSkTkJbggT8bjYP+BjyqPWlD17BH9C5CYNKeDzmcA=
go.opentelemetry.io/otel/exporters/prometheus v0.59.1/go.mod h1:0FJL+gjuUoM07xzik3KPBaN+nz/CoB15kV6WLMiXZag=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.37.0 h1:6VjV6Et+1Hd2iLZEPtdV7vie80Yyqf7oikJLjQ/myi0=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.37.0/go.mod h1:u8hcp8ji5gaM/RfcOo8z9NMnf1pVLfVY7lBY2VOGuUU=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.37.0 h1:SNhVp/9q4Go/XHBkQ1/d5u9P/U+L1yaGPoi0x+mStaI=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.37.0/go.mod h1:tx8OOlGH6R4kLV67YaYO44GFXloEjGPZuMjEkaaqIp4=
go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI=
go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg=
go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc=
go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps=
go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
go.opentelemetry.io/proto/otlp v1.7.1 h1:gTOMpGDb0WTBOP8JaO72iL3auEZhVmAQg4ipjOVAtj4=
go.opentelemetry.io/proto/otlp v1.7.1/go.mod h1:b2rVh6rfI/s2pHWNlB7ILJcRALpcNDzKhACevjI+ZnE=
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/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
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/exp v0.0.0-20250813145105-42675adae3e6 h1:SbTAbRFnd5kjQXbczszQ0hdk3ctwYf3qBNH9jIsGclE=
golang.org/x/exp v0.0.0-20250813145105-42675adae3e6/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
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=
google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d h1:H8tOf8XM88HvKqLTxe755haY6r1fqqzLbEnfrmLXlSA=
google.golang.org/genproto/googleapis/api v0.0.0-20250102185135-69823020774d/go.mod h1:2v7Z7gP2ZUOGsaFyxATQSRoBnKygqVq2Cwnvom7QiqY=
google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24=
google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw=
google.golang.org/genproto/googleapis/api v0.0.0-20250127172529-29210b9bc287 h1:A2ni10G3UlplFrWdCDJTl7D7mJ7GSRm37S+PDimaKRw=
google.golang.org/genproto/googleapis/api v0.0.0-20250127172529-29210b9bc287/go.mod h1:iYONQfRdizDB8JJBybql13nArx91jcUk7zCXEsOofM4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d h1:xJJRGY7TJcvIlpSrN3K6LAWgNFUILlO+OMAqtg9aqnw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d/go.mod h1:3ENsm/5D1mzDyhpzeRi1NR784I0BcofWBoSc5QqqMK4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250106144421-5f5ef82da422 h1:3UsHvIr4Wc2aW4brOaSCmcxh9ksica6fHEr8P1XhkYw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250106144421-5f5ef82da422/go.mod h1:3ENsm/5D1mzDyhpzeRi1NR784I0BcofWBoSc5QqqMK4=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287 h1:J1H9f+LEdWAfHcez/4cvaVBox7cOYT+IU6rgqj5x++8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250127172529-29210b9bc287/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk=
google.golang.org/grpc v1.69.2 h1:U3S9QEtbXC0bYNvRtcoklF3xGtLViumSYxWykJS+7AU=
google.golang.org/grpc v1.69.2/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4=
google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ=
google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw=
google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk=
google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
google.golang.org/protobuf v1.36.2 h1:R8FeyR1/eLmkutZOM5CWghmo5itiG9z0ktFlTVLuTmU=
google.golang.org/protobuf v1.36.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
google.golang.org/protobuf v1.36.4 h1:6A3ZDJHn/eNqc1i+IdefRzy/9PokBTPvcqMySR7NNIM=
google.golang.org/protobuf v1.36.4/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
google.golang.org/genproto/googleapis/api v0.0.0-20250811230008-5f3141c8851a h1:DMCgtIAIQGZqJXMVzJF4MV8BlWoJh2ZuFiRdAleyr58=
google.golang.org/genproto/googleapis/api v0.0.0-20250811230008-5f3141c8851a/go.mod h1:y2yVLIE/CSMCPXaHnSKXxu1spLPnglFLegmgdY23uuE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250811230008-5f3141c8851a h1:tPE/Kp+x9dMSwUm/uM0JKK0IfdiJkwAbSMSeZBXXJXc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250811230008-5f3141c8851a/go.mod h1:gw1tLEfykwDz2ET4a12jcXt4couGAm7IwsVaTy0Sflo=
google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4=
google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM=
google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=
google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
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=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -1,101 +0,0 @@
package app
import (
"context"
"errors"
"net"
"net/http"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv"
)
type App struct {
AppContext context.Context
HTTP *AppHTTP
cfg *config.AppConfig
l *zerolog.Logger
tracer trace.Tracer
shutdownFuncs []shutdownFunc
appDone chan interface{}
}
type AppHTTP struct {
Funcs []srv.HTTPFunc // Handle funcs to serve
Middleware []http.Handler // Optional middleware. Next handler called by app framework.
HealthChecks []srv.HealthCheckFunc // Health-check functions to be called by health endpoint
CustomListener net.Listener // Optional listener for http server
httpDone <-chan interface{}
}
type (
healthCheckFunc func(context.Context) error
shutdownFunc func(context.Context) error
)
func (a *App) Done() <-chan interface{} {
return a.appDone
}
func (a *App) MustRun() {
if a.cfg != nil {
panic(errors.New("already ran app trying to run"))
}
// Set up app
a.cfg = config.MustFromCtx(a.AppContext)
a.l = zerolog.Ctx(a.AppContext)
a.shutdownFuncs = make([]shutdownFunc, 0)
a.appDone = make(chan interface{})
a.HTTP.httpDone = make(chan interface{})
if len(a.HTTP.Funcs) < 1 {
a.l.Warn().Msg("no http funcs provided, only serving health and metrics")
}
// Start OTEL
a.initOTEL()
var initSpan trace.Span
_, initSpan = a.tracer.Start(a.AppContext, "init")
// Start HTTP
a.initHTTP()
// Monitor app lifecycle
go a.run()
// Startup Complete
a.l.Info().
Str("name", a.cfg.Name).
Str("version", a.cfg.Version).
Str("logLevel", a.cfg.Logging.Level).
Msg("app initialized")
initSpan.SetStatus(codes.Ok, "")
initSpan.End()
}
func (a *App) initHTTP() {
var httpShutdown shutdownFunc
httpShutdown, a.HTTP.httpDone = srv.MustInitHTTPServer(
&srv.HTTPServerOpts{
Ctx: a.AppContext,
HandleFuncs: a.HTTP.Funcs,
Middleware: a.HTTP.Middleware,
HealthCheckFuncs: a.HTTP.HealthChecks,
CustomListener: a.HTTP.CustomListener,
},
)
a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown)
}
func (a *App) initOTEL() {
var otelShutdown shutdownFunc
a.AppContext, otelShutdown = otel.Init(a.AppContext)
a.shutdownFuncs = append(a.shutdownFuncs, otelShutdown)
a.tracer = otel.MustTracerFromCtx(a.AppContext)
}

29
pkg/app/app_types.go Normal file
View File

@@ -0,0 +1,29 @@
// Package app provides methods to configure, run, and stop
// a go-app.
package app
import (
"context"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/trace"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
grpcopts "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
httpopts "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
)
// App is the main application struct, holding its context, configurations,
// and various services like HTTP and gRPC.
type App struct {
AppContext context.Context
HTTP *httpopts.AppHTTP
GRPC *grpcopts.AppGRPC
cfg *config.AppConfig
l *zerolog.Logger
tracer trace.Tracer
shutdownFuncs []shutdownFunc
appDone chan any
}
type shutdownFunc func(context.Context) error

75
pkg/app/init.go Normal file
View File

@@ -0,0 +1,75 @@
package app
import (
"context"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
srvgrpc "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc"
grpcopts "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
srvhttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http"
)
func (a *App) initGRPC(ctx context.Context) error {
ctx, span := a.tracer.Start(ctx, "init.grpc")
defer span.End()
shutdown, doneChan, err := srvgrpc.InitGRPCServer(ctx,
&grpcopts.GRPCOpts{
GRPCConfig: a.cfg.GRPC,
AppGRPC: a.GRPC,
})
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return err
}
a.shutdownFuncs = append(a.shutdownFuncs, shutdown)
a.GRPC.GRPCDone = doneChan
span.SetStatus(codes.Ok, "")
return nil
}
func (a *App) initHTTP(ctx context.Context) error {
var err error
var httpShutdown shutdownFunc
_, span := a.tracer.Start(ctx, "init.http")
defer span.End()
span.SetAttributes(
attribute.Int("numHTTPFuncs", len(a.HTTP.Funcs)),
attribute.Int("numHTTPMiddlewares", len(a.HTTP.Middleware)),
attribute.Int("numHTTPHealthChecks", len(a.HTTP.HealthChecks)),
)
a.HTTP.Ctx = a.AppContext
httpShutdown, a.HTTP.HTTPDone, err = srvhttp.InitHTTPServer(a.HTTP)
a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
return err
}
func (a *App) InitOTEL() {
if a.tracer != nil {
a.l.Debug().Msg("superfluous call of already configured app otel")
return
}
var otelShutdown shutdownFunc
a.AppContext, otelShutdown = otel.Init(a.AppContext)
a.shutdownFuncs = append(a.shutdownFuncs, otelShutdown)
a.tracer = otel.MustTracerFromCtx(a.AppContext)
}

72
pkg/app/monitor.go Normal file
View File

@@ -0,0 +1,72 @@
package app
import (
"context"
"sync"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
)
// Watches contexts and channels for the
// app to be finished and calls shutdown once
// the app is done
func (a *App) monitor() {
select {
case <-a.AppContext.Done():
a.l.Warn().Str("reason", a.AppContext.Err().Error()).
Msg("shutting down on context done")
case <-a.HTTP.HTTPDone: // TODO: return error on this channel
a.l.Warn().Msg("shutting down early on http server done")
case err := <-a.GRPC.GRPCDone:
a.l.Warn().Err(err).Msg("shutting down early on grpc server done")
}
a.Shutdown() // Run through all shutdown funcs
a.appDone <- nil // Notify app
}
// Shutdown is typically invoked when AppContext is done
// or Server has exited. Not intended to be called
// manually
func (a *App) Shutdown() {
now := time.Now()
doneCtx, cncl := context.WithTimeout(context.Background(), 15*time.Second)
defer func() {
if doneCtx.Err() == context.DeadlineExceeded {
a.l.Err(doneCtx.Err()).
Dur("shutdownTime", time.Since(now)).
Msg("app shutdown aborted")
} else {
a.l.Info().
Int("shutdownFuncsCalled", len(a.shutdownFuncs)).
Dur("shutdownTime", time.Since(now)).
Msg("app shutdown normally")
}
cncl()
}()
doneCtx, span := a.tracer.Start(doneCtx, "shutdown")
defer span.End()
span.SetAttributes(attribute.Int("shutdown.funcs", len(a.shutdownFuncs)))
var wg sync.WaitGroup
wg.Add(len(a.shutdownFuncs))
for _, f := range a.shutdownFuncs {
go func() {
defer wg.Done()
err := f(doneCtx)
if err != nil {
span.SetStatus(codes.Error, "shutdown failed")
span.RecordError(err)
a.l.Err(err).Send()
}
}()
}
wg.Wait()
}

View File

@@ -1,67 +1,63 @@
package app
import (
"context"
"sync"
"time"
"errors"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/codes"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
)
// Watches contexts and channels for the
// app to be finished and calls shutdown once
// the app is done
func (a *App) run() {
select {
case <-a.AppContext.Done():
a.l.Warn().Str("reason", a.AppContext.Err().Error()).
Msg("shutting down on context done")
case <-a.HTTP.httpDone:
a.l.Warn().Msg("shutting down early on http server done")
}
a.Shutdown()
a.appDone <- nil
func (a *App) Done() <-chan any {
return a.appDone
}
// Typically invoked when AppContext is done
// or Server has exited. Not intended to be called
// manually
func (a *App) Shutdown() {
now := time.Now()
doneCtx, cncl := context.WithTimeout(context.Background(), 15*time.Second)
defer func() {
if doneCtx.Err() == context.DeadlineExceeded {
a.l.Err(doneCtx.Err()).
Dur("shutdownTime", time.Since(now)).
Msg("app shutdown aborted")
} else {
a.l.Info().
Int("shutdownFuncsCalled", len(a.shutdownFuncs)).
Dur("shutdownTime", time.Since(now)).
Msg("app shutdown normally")
}
cncl()
}()
doneCtx, span := a.tracer.Start(doneCtx, "shutdown")
defer span.End()
var wg sync.WaitGroup
wg.Add(len(a.shutdownFuncs))
for _, f := range a.shutdownFuncs {
go func() {
defer wg.Done()
err := f(doneCtx)
if err != nil {
span.SetStatus(codes.Error, "shutdown failed")
span.RecordError(err)
a.l.Err(err).Send()
}
}()
func (a *App) MustRun() {
if a.cfg != nil {
panic(errors.New("already ran app trying to run"))
}
wg.Wait()
// Set up app
a.cfg = config.MustFromCtx(a.AppContext)
a.l = zerolog.Ctx(a.AppContext)
a.shutdownFuncs = make([]shutdownFunc, 0)
a.appDone = make(chan any)
a.HTTP.HTTPDone = make(chan any)
if !a.cfg.HTTPEnabled() && !a.cfg.GRPCEnabled() {
panic(errors.New("neither http nor grpc enabled, nothing to do"))
}
if len(a.HTTP.Funcs) < 1 {
a.l.Warn().Msg("no http funcs provided, only serving health and metrics")
}
// Start OTEL
// Registers a NO-OP provider if not enabled
a.InitOTEL()
// With OTEL ready, create an init span to track startup
ctx, initSpan := a.tracer.Start(a.AppContext, "init")
defer initSpan.End()
// Prepare GRPC first. The GRPC server may update its opts
// with a prepared GRPC-Gateway runtime.ServeMux if any of its services
// have added GRPC-Gateway handlers. If present, serve under api path
a.runGRPC(ctx)
// Second, prepare and run HTTP server, embedding grpc-gateway
// runtime.ServeMux if set by runGRPC()
a.runHTTP(ctx)
// Monitor app lifecycle
go a.monitor()
// Startup Complete
a.l.Info().
Str("name", a.cfg.Name).
Str("version", a.cfg.Version).
Str("logLevel", a.cfg.Logging.Level).
Msg("app initialized")
initSpan.SetStatus(codes.Ok, "")
}

47
pkg/app/run_grpc.go Normal file
View File

@@ -0,0 +1,47 @@
package app
import (
"context"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
optsgrpc "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
optshttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
)
func (a *App) runGRPC(ctx context.Context) {
if a.GRPC == nil {
a.GRPC = &optsgrpc.AppGRPC{
GRPCDone: make(chan error),
}
}
if !a.cfg.GRPCEnabled() {
zerolog.Ctx(ctx).Info().Msg("skipping disabled GRPC server")
return
}
span := trace.SpanFromContext(ctx)
if err := a.initGRPC(ctx); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
span.AddEvent("grpc server started")
span.SetAttributes(attribute.Int("grpc.services", len(a.GRPC.Services)))
if a.GRPC.GetGatewayMux() != nil {
if a.HTTP.Handlers == nil {
a.HTTP.Handlers = make([]optshttp.HTTPHandler, 0, 1)
}
a.HTTP.Handlers = append(a.HTTP.Handlers, optshttp.HTTPHandler{
Prefix: a.cfg.GRPC.GRPCGatewayPath,
StripPrefix: true,
Handler: a.GRPC.GetGatewayMux(),
})
span.AddEvent("GRPC Gateway Mux Registered")
}
}

33
pkg/app/run_http.go Normal file
View File

@@ -0,0 +1,33 @@
package app
import (
"context"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
optshttp "gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
)
func (a *App) runHTTP(ctx context.Context) {
if a.HTTP == nil {
a.HTTP = &optshttp.AppHTTP{
HTTPDone: make(chan any),
}
}
if !a.cfg.HTTPEnabled() {
zerolog.Ctx(ctx).Info().Msg("skipping disabled HTTP Server")
return
}
span := trace.SpanFromContext(ctx)
if err := a.initHTTP(ctx); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
span.AddEvent("http server started")
span.SetAttributes(attribute.Int("http.handlers", len(a.HTTP.Funcs)))
}

40
pkg/app/schema.go Normal file
View File

@@ -0,0 +1,40 @@
package app
import (
"encoding/json"
js "github.com/swaggest/jsonschema-go"
)
// Schema generates json schema for app's config.AppConfig
func (a *App) Schema() ([]byte, error) {
r := js.Reflector{}
s, err := r.Reflect(*a.cfg)
if err != nil {
return nil, err
}
return json.MarshalIndent(s, "", " ")
}
// CustomSchema generates json schema for custom config
// which embeds *config.AppConfig into it
// Panics if no *config.AppConfig is embedded into custom
// config type
//
// See swaggest/jsonschema-go for struct tag docs
func CustomSchema[T any](target T) ([]byte, error) {
if err := HasAppConfig(target); err != nil {
panic(err.Error())
}
r := js.Reflector{}
s, err := r.Reflect(target)
if err != nil {
return nil, err
}
return json.MarshalIndent(s, "", " ")
}

View File

@@ -9,7 +9,7 @@ import (
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/logging"
)
// Helper function to return a context loaded up with
// MustSetupConfigAndLogging is a helper function to return a context loaded up with
// config.AppConfig and a logger
func MustSetupConfigAndLogging(ctx context.Context) context.Context {
ctx, err := config.LoadConfig(ctx)
@@ -24,7 +24,7 @@ func MustSetupConfigAndLogging(ctx context.Context) context.Context {
return ctx
}
// Unmarshal config into a custom type
// MustSetupConfigAndLoggingInto will unmarshal config into a custom type
// Type MUST include *config.AppConfig
// Stored in context as *config.AppConfig but can be asserted back
func MustSetupConfigAndLoggingInto[T any](ctx context.Context, into T) (context.Context, T) {

View File

@@ -13,13 +13,13 @@ import (
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
)
// Used to unmarshal config and environment into a custom type
// MustLoadConfigInto is used to unmarshal config and environment into a custom type
// that overloads *config.AppConfig. Will perform normal env
// substitutions for AppConfig, but env overrides for custom type
// are up to the caller.
func MustLoadConfigInto[T any](ctx context.Context, into T) (context.Context, T) {
// Step 1: Check our custom type for required *config.AppConfig
if err := hasAppConfig(into); err != nil {
if err := HasAppConfig(into); err != nil {
panic(err)
}
@@ -66,7 +66,7 @@ func setAppConfig[T any](target T, appConfig *config.AppConfig) error {
}
// Replace *config.AppConfig
for i := 0; i < v.NumField(); i++ {
for i := range v.NumField() {
field := v.Field(i)
if field.Type() == reflect.TypeOf((*config.AppConfig)(nil)) {
if !field.CanSet() {
@@ -80,7 +80,7 @@ func setAppConfig[T any](target T, appConfig *config.AppConfig) error {
return errors.New("no *config.AppConfig field found in target struct")
}
func hasAppConfig[T any](target T) error {
func HasAppConfig[T any](target T) error {
v := reflect.ValueOf(target)
if v.Kind() != reflect.Ptr || v.IsNil() {
return errors.New("target must be a non-nil pointer to a struct")
@@ -92,7 +92,7 @@ func hasAppConfig[T any](target T) error {
}
hasAppConfig := false
for i := 0; i < v.NumField(); i++ {
for i := range v.NumField() {
field := v.Type().Field(i)
if field.Type == reflect.TypeOf((*config.AppConfig)(nil)) {
hasAppConfig = true

View File

@@ -1,3 +1,7 @@
// Package config provides types and methods for managing
// app config. A go-app configuration can be extended by any type
// that embeds AppConfig, and has helpers to generate json
// schema merged with the custom type's fields
package config
import (
@@ -6,6 +10,7 @@ import (
"flag"
"fmt"
"os"
"regexp"
"runtime/debug"
"time"
@@ -13,15 +18,15 @@ import (
"gopkg.in/yaml.v3"
)
// To be set by ldflags in go build command or
// retrieved from build meta below
// Version is to be set by ldflags in go build command or
// retrieved from build meta below.
var Version = "(devel)"
// Calling this will try to load from config if -config is
// LoadConfig will try to load from config if -config is
// provided as a file, and will apply any environment overrides
// on-top of configuration defaults.
// Config is stored in returned context, and can be retrieved
// using config.FromCtx(ctx)
// using config.FromCtx(ctx).
func LoadConfig(ctx context.Context) (context.Context, error) {
configPath := flag.String("config", "", "Path to the configuration file")
flag.Parse()
@@ -40,6 +45,8 @@ func LoadConfig(ctx context.Context) (context.Context, error) {
return ctx, nil
}
// loadConfig loads the application configuration from the specified path,
// applying environment variable overrides.
func loadConfig(configPath string) (*AppConfig, error) {
cfg := *DefaultConfig
@@ -69,6 +76,8 @@ func loadConfig(configPath string) (*AppConfig, error) {
return &cfg, nil
}
// prepareConfig enriches and validates the AppConfig, parsing duration strings
// for HTTP timeouts.
func prepareConfig(cfg *AppConfig) error {
var errs error
@@ -97,15 +106,23 @@ func prepareConfig(cfg *AppConfig) error {
}
}
// Prepare user-provided expressions, panic up-front if invalid
cfg.HTTP.excludeRegexps = make([]*regexp.Regexp, len(cfg.HTTP.LogExcludePathRegexps))
for i, re := range cfg.HTTP.LogExcludePathRegexps {
cfg.HTTP.excludeRegexps[i] = regexp.MustCompile(re)
}
return errs
}
// Returns read timeout, write timeout, and idle timeout, in that order
// nil if unset
// Timeouts returns read timeout, write timeout, and idle timeout, in that order.
// Returns nil if unset.
func (h *HTTPConfig) Timeouts() (*time.Duration, *time.Duration, *time.Duration) {
return h.rT, h.wT, h.iT
}
// getVersion returns the application version, preferring the build info version
// over the compile-time set Version variable.
func getVersion() string {
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "(devel)" {
return info.Main.Version

View File

@@ -22,12 +22,20 @@ var testDefaultConfig = &AppConfig{
TimeFormat: TimeFormatLong,
},
HTTP: &HTTPConfig{
Enabled: true,
Listen: "127.0.0.1:8080",
LogRequests: false,
ReadTimeout: "10s",
WriteTimeout: "10s",
IdleTimeout: "1m",
},
GRPC: &GRPCConfig{
Enabled: false,
Listen: "127.0.0.1:8081",
LogRequests: false,
EnableReflection: true,
EnableInstrumentation: true,
},
OTEL: &OTELConfig{
Enabled: true,
PrometheusEnabled: true,

View File

@@ -9,10 +9,12 @@ type appConfigKey uint8
const appConfigCtxKey appConfigKey = iota
func (a *AppConfig) AddToCtx(ctx context.Context) context.Context {
return context.WithValue(ctx, appConfigCtxKey, a)
// AddToCtx adds the AppConfig to the provided context.
func (ac *AppConfig) AddToCtx(ctx context.Context) context.Context {
return context.WithValue(ctx, appConfigCtxKey, ac)
}
// MustFromCtx retrieves the AppConfig from the context, or panics if not found.
func MustFromCtx(ctx context.Context) *AppConfig {
cfg, err := FromCtx(ctx)
if err != nil {
@@ -21,6 +23,7 @@ func MustFromCtx(ctx context.Context) *AppConfig {
return cfg
}
// FromCtx retrieves the AppConfig from the context.
func FromCtx(ctx context.Context) (*AppConfig, error) {
ctxData := ctx.Value(appConfigCtxKey)
if ctxData == nil {

View File

@@ -1,96 +1,48 @@
package config
import "time"
// Default Settings
// DefaultConfig provides a default application configuration.
var DefaultConfig = &AppConfig{
Environment: "development",
Version: getVersion(),
Logging: &LogConfig{
Enabled: true,
Level: "info",
Format: LogFormatJSON,
Output: "stderr",
TimeFormat: TimeFormatLong,
},
HTTP: &HTTPConfig{
Listen: "127.0.0.1:8080",
LogRequests: false,
ReadTimeout: "10s",
WriteTimeout: "10s",
IdleTimeout: "1m",
},
OTEL: &OTELConfig{
Enabled: true,
PrometheusEnabled: true,
PrometheusPath: "/metrics",
StdoutEnabled: false,
MetricIntervalSecs: 30,
},
Logging: defaultLoggingConfig,
HTTP: defaultHTTPConfig,
OTEL: defaultOTELConfig,
GRPC: defaultGRPCConfig,
}
type AppConfig struct {
Name string `yaml:"name,omitempty" env:"APP_NAME"`
Environment string `yaml:"environment,omitempty" env:"APP_ENVIRONMENT"`
Name string `yaml:"name,omitempty" env:"APP_NAME" json:"name,omitempty"`
Environment string `yaml:"environment,omitempty" env:"APP_ENVIRONMENT" json:"environment,omitempty"`
// This should either be set by ldflags, such as with
// go build -ldflags "-X gitea.libretechconsulting.com/rmcguire/go-app/pkg/config.Version=$(VERSION)"
// or allow this to use build meta. Will default to (devel)
Version string `yaml:"version,omitempty" env:"APP_VERSION"`
Logging *LogConfig `yaml:"logging,omitempty"`
HTTP *HTTPConfig `yaml:"http,omitempty"`
OTEL *OTELConfig `yaml:"otel,omitempty"`
Version string `yaml:"version,omitempty" env:"APP_VERSION" json:"version,omitempty"`
Logging *LogConfig `yaml:"logging,omitempty" json:"logging,omitempty"`
HTTP *HTTPConfig `yaml:"http,omitempty" json:"http,omitempty"`
OTEL *OTELConfig `yaml:"otel,omitempty" json:"otel,omitempty"`
GRPC *GRPCConfig `yaml:"grpc,omitempty" json:"grpc,omitempty"`
}
// Logging Configuration
type LogConfig struct {
Enabled bool `yaml:"enabled,omitempty" env:"APP_LOG_ENABLED"`
Level string `yaml:"level,omitempty" env:"APP_LOG_LEVEL"`
Format LogFormat `yaml:"format,omitempty" env:"APP_LOG_FORMAT"`
Output LogOutput `yaml:"output,omitempty" env:"APP_LOG_OUTPUT"`
TimeFormat TimeFormat `yaml:"timeFormat,omitempty" env:"APP_LOG_TIME_FORMAT"`
// HTTPEnabled returns true if HTTP is enabled in the AppConfig.
func (ac *AppConfig) HTTPEnabled() bool {
if ac.HTTP != nil && ac.HTTP.Enabled {
return true
}
return false
}
type LogFormat string
const (
LogFormatConsole LogFormat = "console"
LogFormatJSON LogFormat = "json"
)
type TimeFormat string
const (
TimeFormatShort TimeFormat = "short"
TimeFormatLong TimeFormat = "long"
TimeFormatUnix TimeFormat = "unix"
TimeFormatRFC3339 TimeFormat = "rfc3339"
TimeFormatOff TimeFormat = "off"
)
type LogOutput string
const (
LogOutputStdout LogOutput = "stdout"
LogOutputStderr LogOutput = "stderr"
)
// HTTP Configuration
type HTTPConfig struct {
Listen string `yaml:"listen,omitempty" env:"APP_HTTP_LISTEN"`
LogRequests bool `yaml:"logRequests" env:"APP_HTTP_LOG_REQUESTS"`
ReadTimeout string `yaml:"readTimeout" env:"APP_HTTP_READ_TIMEOUT"` // Go duration (e.g. 10s)
WriteTimeout string `yaml:"writeTimeout" env:"APP_HTTP_WRITE_TIMEOUT"` // Go duration (e.g. 10s)
IdleTimeout string `yaml:"idleTimeout" env:"APP_HTTP_IDLE_TIMEOUT"` // Go duration (e.g. 10s)
rT *time.Duration
wT *time.Duration
iT *time.Duration
// GRPCEnabled returns true if gRPC is enabled in the AppConfig.
func (ac *AppConfig) GRPCEnabled() bool {
if ac.GRPC != nil && ac.GRPC.Enabled {
return true
}
return false
}
// OTEL Configuration
type OTELConfig struct {
Enabled bool `yaml:"enabled,omitempty" env:"APP_OTEL_ENABLED"`
PrometheusEnabled bool `yaml:"prometheusEnabled,omitempty" env:"APP_OTEL_PROMETHEUS_ENABLED"`
PrometheusPath string `yaml:"prometheusPath,omitempty" env:"APP_OTEL_PROMETHEUS_PATH"`
StdoutEnabled bool `yaml:"stdoutEnabled,omitempty" env:"APP_OTEL_STDOUT_ENABLED"`
MetricIntervalSecs int `yaml:"metricIntervalSecs,omitempty" env:"APP_OTEL_METRIC_INTERVAL_SECS"`
// OTELEnabled returns true if OpenTelemetry is enabled in the AppConfig.
func (ac *AppConfig) OTELEnabled() bool {
if ac.OTEL != nil && ac.OTEL.Enabled {
return true
}
return false
}

21
pkg/config/types_grpc.go Normal file
View File

@@ -0,0 +1,21 @@
package config
var defaultGRPCConfig = &GRPCConfig{
Enabled: false,
Listen: "127.0.0.1:8081",
LogRequests: false,
EnableReflection: true,
EnableInstrumentation: true,
}
type GRPCConfig struct {
Enabled bool `yaml:"enabled" env:"APP_GRPC_ENABLED" json:"enabled,omitempty"`
Listen string `yaml:"listen" env:"APP_GRPC_LISTEN" json:"listen,omitempty"`
LogRequests bool `yaml:"logRequests" env:"APP_GRPC_LOG_REQUESTS" json:"logRequests,omitempty"`
EnableProtovalidate bool `yaml:"enableProtovalidate" env:"APP_GRPC_ENABLE_PROTOVALIDATE" json:"enableProtovalidate,omitempty" default:"false" description:"Add a chain unary and streaming interceptor for buf.build/go/protovalidate"`
EnableReflection bool `yaml:"enableReflection" env:"APP_GRPC_ENABLE_REFLECTION" json:"enableReflection,omitempty"`
EnableInstrumentation bool `yaml:"enableInstrumentation" env:"APP_GRPC_ENABLE_INSTRUMENTATION" json:"enableInstrumentation,omitempty"` // requires OTEL
EnableGRPCGateway bool `yaml:"enableGRPCGateway" json:"enableGRPCGateway,omitempty" env:"APP_GRPC_ENABLE_GATEWAY" default:"true"`
GRPCGatewayPath string `yaml:"grpcGatewayPath" json:"grpcGatewayPath,omitempty" env:"APP_GRPC_GATEWAY_PATH" default:"/grpc-api"`
}

40
pkg/config/types_http.go Normal file
View File

@@ -0,0 +1,40 @@
package config
import (
"regexp"
"sync"
"time"
)
var defaultHTTPConfig = &HTTPConfig{
Enabled: true,
Listen: "127.0.0.1:8080",
LogRequests: false,
ReadTimeout: "10s",
WriteTimeout: "10s",
IdleTimeout: "1m",
}
// HTTPConfig provides HTTP server Configuration
type HTTPConfig struct {
Enabled bool `yaml:"enabled" env:"APP_HTTP_ENABLED" json:"enabled,omitempty"`
Listen string `yaml:"listen,omitempty" env:"APP_HTTP_LISTEN" json:"listen,omitempty"`
LogRequests bool `yaml:"logRequests" env:"APP_HTTP_LOG_REQUESTS" json:"logRequests,omitempty"`
LogExcludePathRegexps []string `yaml:"logExcludePathRegexps" env:"APP_HTTP_LOG_EXCLUDE_PATH_REGEXPS" json:"logExcludePathRegexps,omitempty"`
ReadTimeout string `yaml:"readTimeout" env:"APP_HTTP_READ_TIMEOUT" json:"readTimeout,omitempty"` // Go duration (e.g. 10s)
WriteTimeout string `yaml:"writeTimeout" env:"APP_HTTP_WRITE_TIMEOUT" json:"writeTimeout,omitempty"` // Go duration (e.g. 10s)
IdleTimeout string `yaml:"idleTimeout" env:"APP_HTTP_IDLE_TIMEOUT" json:"idleTimeout,omitempty"` // Go duration (e.g. 10s)
excludeRegexps []*regexp.Regexp
rT *time.Duration
wT *time.Duration
iT *time.Duration
lock sync.RWMutex
}
func (h *HTTPConfig) GetExcludeRegexps() []*regexp.Regexp {
h.lock.RLock()
defer h.lock.RUnlock()
return h.excludeRegexps
}

View File

@@ -0,0 +1,42 @@
package config
var defaultLoggingConfig = &LogConfig{
Enabled: true,
Level: "info",
Format: LogFormatJSON,
Output: "stderr",
TimeFormat: TimeFormatLong,
}
// LogConfig provides Logging Configuration
type LogConfig struct {
Enabled bool `yaml:"enabled,omitempty" env:"APP_LOG_ENABLED" json:"enabled,omitempty"`
Level string `yaml:"level,omitempty" env:"APP_LOG_LEVEL" json:"level,omitempty"`
Format LogFormat `yaml:"format,omitempty" env:"APP_LOG_FORMAT" json:"format,omitempty"`
Output LogOutput `yaml:"output,omitempty" env:"APP_LOG_OUTPUT" json:"output,omitempty"`
TimeFormat TimeFormat `yaml:"timeFormat,omitempty" env:"APP_LOG_TIME_FORMAT" json:"timeFormat,omitempty"`
}
type LogFormat string
const (
LogFormatConsole LogFormat = "console"
LogFormatJSON LogFormat = "json"
)
type TimeFormat string
const (
TimeFormatShort TimeFormat = "short"
TimeFormatLong TimeFormat = "long"
TimeFormatUnix TimeFormat = "unix"
TimeFormatRFC3339 TimeFormat = "rfc3339"
TimeFormatOff TimeFormat = "off"
)
type LogOutput string
const (
LogOutputStdout LogOutput = "stdout"
LogOutputStderr LogOutput = "stderr"
)

18
pkg/config/types_otel.go Normal file
View File

@@ -0,0 +1,18 @@
package config
var defaultOTELConfig = &OTELConfig{
Enabled: true,
PrometheusEnabled: true,
PrometheusPath: "/metrics",
StdoutEnabled: false,
MetricIntervalSecs: 30,
}
// OtelConfig provides OTEL Configuration
type OTELConfig struct {
Enabled bool `yaml:"enabled,omitempty" env:"APP_OTEL_ENABLED" json:"enabled,omitempty"`
PrometheusEnabled bool `yaml:"prometheusEnabled,omitempty" env:"APP_OTEL_PROMETHEUS_ENABLED" json:"prometheusEnabled,omitempty"`
PrometheusPath string `yaml:"prometheusPath,omitempty" env:"APP_OTEL_PROMETHEUS_PATH" json:"prometheusPath,omitempty"`
StdoutEnabled bool `yaml:"stdoutEnabled,omitempty" env:"APP_OTEL_STDOUT_ENABLED" json:"stdoutEnabled,omitempty"`
MetricIntervalSecs int `yaml:"metricIntervalSecs,omitempty" env:"APP_OTEL_METRIC_INTERVAL_SECS" json:"metricIntervalSecs,omitempty"`
}

View File

@@ -1,3 +1,5 @@
// Package logging provides a centralized logging utility using zerolog,
// with configurable output formats and log levels.
package logging
import (
@@ -38,7 +40,7 @@ func configureLogger(cfg *config.LogConfig) (*zerolog.Logger, error) {
TimeFormat: zerolog.TimeFieldFormat,
}
if cfg.TimeFormat == config.TimeFormatOff {
consoleWriter.FormatTimestamp = func(_ interface{}) string {
consoleWriter.FormatTimestamp = func(_ any) string {
return ""
}
}

View File

@@ -1,3 +1,4 @@
// Package otel provides OpenTelemetry initialization and configuration for tracing and metrics.
package otel
import (
@@ -22,7 +23,7 @@ import (
"go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
traceSDK "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
trace "go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
)
@@ -39,12 +40,13 @@ var (
const defMetricInterval = 15 * time.Second
// Init prepares otel, loading a tracer and meter stored in appp context.
// Context must carry config.AppConfig
func Init(ctx context.Context) (context.Context, func(context.Context) error) {
cfg := config.MustFromCtx(ctx)
// Nothing to do here if not enabled
if !cfg.OTEL.Enabled {
if !cfg.OTELEnabled() {
opentelemetry.SetMeterProvider(noopMetric.NewMeterProvider())
opentelemetry.SetTracerProvider(noop.NewTracerProvider())
// Won't function with noop providers
@@ -170,7 +172,7 @@ func newResource(ctx context.Context) *resource.Resource {
attributes := []attribute.KeyValue{
semconv.ServiceName(cfg.Name),
semconv.ServiceVersion(cfg.Version),
semconv.DeploymentEnvironment(cfg.Environment),
semconv.DeploymentEnvironmentName(cfg.Environment),
semconv.K8SPodName(os.Getenv("HOSTNAME")),
}
@@ -201,7 +203,7 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
host, set := os.LookupEnv("OTEL_EXPORTER_OTLP_ENDPOINT")
var otlpExporter *otlpmetricgrpc.Exporter
if set && host != "" {
if exp, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithInsecure()); err != nil {
if exp, err := otlpmetricgrpc.New(ctx); err != nil {
return nil, fmt.Errorf("otlpmetricgrpc.New: %w", err)
} else {
otlpExporter = exp
@@ -232,7 +234,7 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
return meterProvider, nil
}
// Creates a new tracer from the global opentelemetry provider
// NewTracer creates a new tracer from the global opentelemetry provider
func NewTracer(options ...trace.TracerOption) trace.Tracer {
return opentelemetry.GetTracerProvider().Tracer(
os.Getenv("OTEL_SERVICE_NAME"),

65
pkg/srv/grpc/gateway.go Normal file
View File

@@ -0,0 +1,65 @@
package grpc
import (
"context"
"errors"
"fmt"
"net"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
)
func (a *appGRPCServer) registerServiceGatewayHandlers(ctx context.Context, service *opts.GRPCService) {
if len(service.GwRegistrationFuncs) < 1 {
return
} else if a.gatewayMux == nil {
a.gatewayMux = runtime.NewServeMux(a.opts.GRPCGatewayOpts...)
}
ctx, span := a.tracer.Start(ctx, "appgrpc.init.prepare.service.gwHandlers", trace.WithAttributes(
attribute.String("service", service.Name),
attribute.Int("gwHandlers", len(service.GwRegistrationFuncs)),
))
defer span.End()
clientConn := a.GetClientConn(ctx)
var errs error
for _, registerGW := range service.GwRegistrationFuncs {
errs = errors.Join(errs, registerGW(ctx, a.gatewayMux, clientConn))
a.logger.Debug().Any("fwo", a.gatewayMux.GetForwardResponseOptions()).
Msg("calling gateway registration func")
}
if errs != nil {
panic(errs)
}
}
func (a *appGRPCServer) GetClientConn(ctx context.Context) *grpc.ClientConn {
span := trace.SpanFromContext(ctx)
host, port, err := net.SplitHostPort(a.opts.Listen)
if err != nil {
panic(err)
}
if host == "" || host == "0.0.0.0" {
host = "localhost"
}
clientConn, err := grpc.NewClient(fmt.Sprintf("%s:%s", host, port), a.opts.GRPCDialOpts...)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
panic(err)
}
return clientConn
}

102
pkg/srv/grpc/grpc.go Normal file
View File

@@ -0,0 +1,102 @@
// Package grpc provides a gRPC server implementation with OpenTelemetry integration
// and gRPC Gateway for RESTful API exposure.
package grpc
import (
"context"
"strings"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/rs/zerolog"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
appotel "gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
)
type appGRPCServer struct {
ctx context.Context
tracer trace.Tracer
meter metric.Meter
opts *opts.GRPCOpts
serverOpts []grpc.ServerOption
logger *zerolog.Logger
server *grpc.Server
gatewayMux *runtime.ServeMux
shutdownFunc func(context.Context) error
doneChan chan error
}
// InitGRPCServer initializes and starts a gRPC server.
// It returns a shutdown function, a channel to signal completion or error,
// and an error if the server fails to start.
func InitGRPCServer(ctx context.Context, opts *opts.GRPCOpts) (
func(context.Context) error, <-chan error, error,
) {
appGRPC := &appGRPCServer{
ctx: ctx,
tracer: appotel.GetTracer(ctx, "grpc"),
meter: appotel.GetMeter(ctx, "grpc"),
opts: opts,
serverOpts: make([]grpc.ServerOption, 0),
logger: zerolog.Ctx(ctx),
doneChan: make(chan error),
}
ctx, span := appGRPC.tracer.Start(ctx, "appgrpc.init")
defer span.End()
// Prepare grpc.Server for use
if err := appGRPC.prepGRPCServer(ctx); err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "failed to prepare GRPC Server")
return nil, nil, err
}
// Load span with server info
span.SetAttributes(appGRPC.getServerAttributes()...)
err := appGRPC.runGRPCServer(ctx)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, "failed to start GRPC Server")
return nil, nil, err
}
appGRPC.logger.Debug().Msg("GRPC Server Started")
span.SetStatus(codes.Ok, "")
return appGRPC.shutdownFunc, appGRPC.doneChan, nil
}
// Convert grpc.ServiceInfo map to []attribute.KeyValue
func (a *appGRPCServer) getServerAttributes() []attribute.KeyValue {
var attrs []attribute.KeyValue
for serviceName, info := range a.server.GetServiceInfo() {
// Add the service name
attrs = append(attrs, attribute.String("grpc.service", serviceName))
// Convert methods into a comma-separated string
var methods []string
for _, method := range info.Methods {
methods = append(methods, method.Name)
}
// Add methods if present
if len(methods) > 0 {
attrs = append(attrs, attribute.String("grpc.service.methods", strings.Join(methods, ",")))
}
// If metadata is a string, store it
if metadata, ok := info.Metadata.(string); ok && metadata != "" {
attrs = append(attrs, attribute.String("grpc.service.metadata", metadata))
}
}
return attrs
}

51
pkg/srv/grpc/logger.go Normal file
View File

@@ -0,0 +1,51 @@
package grpc
import (
"context"
grpclogging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// GRPCLogger is a grpc logging middleware compatible logger
// implementation using a zerolog logger, either from
// the global logger or a context logger.
type GRPCLogger struct {
logger zerolog.Logger
}
// NewGRPCLogger returns a grpcLogger using the global zerolog Logger.
func NewGRPCLogger() *GRPCLogger {
return &GRPCLogger{logger: log.Logger}
}
// NewGRPCContextLogger returns a grpcLogger using the zerolog logger in the provided context.
func NewGRPCContextLogger(ctx context.Context) *GRPCLogger {
logger := log.Ctx(ctx)
return &GRPCLogger{logger: *logger}
}
// Log logs the fields for given log level. We can assume users (middleware library) will put fields in pairs and
// those will be unique.
func (l *GRPCLogger) Log(ctx context.Context, level grpclogging.Level, msg string, fields ...any) {
var event *zerolog.Event
switch level {
case grpclogging.LevelDebug:
event = l.logger.Debug()
case grpclogging.LevelInfo:
event = l.logger.Info()
case grpclogging.LevelWarn:
event = l.logger.Warn()
case grpclogging.LevelError:
event = l.logger.Error()
default:
event = l.logger.Warn().
Int("unknowngrpcloglevel", int(level))
}
event.Ctx(ctx)
event.Fields(fields)
event.Msg(msg)
}

View File

@@ -0,0 +1,43 @@
package opts
import (
"context"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
)
type GRPCOpts struct {
*config.GRPCConfig // Settings configurable by env or yaml
*AppGRPC // Settings provided in code
}
type AppGRPC struct {
Services []*GRPCService
UnaryInterceptors []grpc.UnaryServerInterceptor
StreamInterceptors []grpc.StreamServerInterceptor
GRPCOpts []grpc.ServerOption
GRPCDialOpts []grpc.DialOption // Map ServerOptions to DialOpts for GRPC Gateway support
GRPCGatewayOpts []runtime.ServeMuxOption // Configure grpc-gateway ServeMux
GRPCDone <-chan error
gatewayMux *runtime.ServeMux
}
type GRPCService struct {
Name string // Descriptive name of service
Type *grpc.ServiceDesc // Type (from protoc generated code)
Service any // Implementation of GRPCService.Type (ptr)
GwRegistrationFuncs []GwRegistrationFunc // Gateway regustration handler funcs
}
type GwRegistrationFunc func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error
func (a *AppGRPC) SetGatewayMux(mux *runtime.ServeMux) {
a.gatewayMux = mux
}
func (a *AppGRPC) GetGatewayMux() *runtime.ServeMux {
return a.gatewayMux
}

126
pkg/srv/grpc/prepare.go Normal file
View File

@@ -0,0 +1,126 @@
package grpc
import (
"context"
"errors"
"buf.build/go/protovalidate"
grpclogging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
protovalidate_middleware "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/protovalidate"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
func (a *appGRPCServer) prepGRPCServer(spanCtx context.Context) error {
ctx, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare")
defer span.End()
if len(a.opts.Services) < 1 {
err := errors.New("refusing to create grpc server with no services")
a.logger.Err(err).Send()
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return err
}
// Prepare GRPC Server Opts
a.prepareOTEL(ctx)
a.prepareLogging(ctx)
a.prepareProtovalidate(ctx)
// Chain interceptors for unary RPCs
a.serverOpts = append(a.serverOpts,
grpc.ChainUnaryInterceptor(a.opts.UnaryInterceptors...))
span.SetAttributes(attribute.Int("grpc.server.unaryinterceptors",
len(a.opts.UnaryInterceptors)))
// Chain interceptors for streaming RPCs
a.serverOpts = append(a.serverOpts,
grpc.ChainStreamInterceptor(a.opts.StreamInterceptors...))
span.SetAttributes(attribute.Int("grpc.server.streaminterceptors",
len(a.opts.StreamInterceptors)))
// Prepare GRPC Server
a.server = grpc.NewServer(a.serverOpts...)
span.SetAttributes(attribute.Int("grpc.server.serveropts", len(a.serverOpts)))
// Load given services into server registry
a.registerGRPCServices(ctx)
span.SetAttributes(attribute.Int("grpc.server.grpcservices", len(a.opts.Services)))
// If a grpc-gateway mux was created, store it in opts
// so it can be used by AppHTTP
if a.gatewayMux != nil {
a.opts.SetGatewayMux(a.gatewayMux)
span.SetAttributes(attribute.Bool("grpc.server.grpcgateway.enabled", true))
} else {
span.SetAttributes(attribute.Bool("grpc.server.grpcgateway.enabled", false))
}
// Enable reflection if desired
if a.opts.EnableReflection {
reflection.Register(a.server)
}
span.SetAttributes(attribute.Bool("grpc.server.reflection", a.opts.EnableReflection))
span.SetStatus(codes.Ok, "")
return nil
}
// prepareProtovalidate() adds interceptors for buf.build protovalidate
func (a *appGRPCServer) prepareProtovalidate(spanCtx context.Context) {
_, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare.protovalidate", trace.WithAttributes(
attribute.Bool("grpc.server.protovalidate", a.opts.EnableProtovalidate)))
defer span.End()
if !a.opts.EnableProtovalidate {
return
}
validator, err := protovalidate.New()
if err != nil {
span.RecordError(err)
}
a.opts.UnaryInterceptors = append(a.opts.UnaryInterceptors,
protovalidate_middleware.UnaryServerInterceptor(validator))
a.opts.StreamInterceptors = append(a.opts.StreamInterceptors,
protovalidate_middleware.StreamServerInterceptor(validator))
}
func (a *appGRPCServer) prepareOTEL(spanCtx context.Context) {
_, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare.otel", trace.WithAttributes(
attribute.Bool("grpc.server.instrumented", a.opts.EnableInstrumentation)))
defer span.End()
if a.opts.EnableInstrumentation {
a.serverOpts = append(a.serverOpts,
grpc.StatsHandler(
otelgrpc.NewServerHandler(
otelgrpc.WithTracerProvider(otel.GetTracerProvider()),
otelgrpc.WithMeterProvider(otel.GetMeterProvider()),
)))
span.SetStatus(codes.Ok, "")
}
}
func (a *appGRPCServer) prepareLogging(spanCtx context.Context) {
_, span := a.tracer.Start(spanCtx, "appgrpc.init.prepare.logging", trace.WithAttributes(
attribute.Bool("grpc.server.instrumentated", a.opts.LogRequests),
attribute.String("grpc.server.loglevel", a.logger.GetLevel().String())))
defer span.End()
if a.opts.LogRequests {
a.opts.UnaryInterceptors = append(a.opts.UnaryInterceptors,
grpclogging.UnaryServerInterceptor(NewGRPCContextLogger(a.ctx)))
a.opts.StreamInterceptors = append(a.opts.StreamInterceptors,
grpclogging.StreamServerInterceptor(NewGRPCContextLogger(a.ctx)))
span.SetStatus(codes.Ok, "")
}
}

66
pkg/srv/grpc/run.go Normal file
View File

@@ -0,0 +1,66 @@
package grpc
import (
"context"
"net"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
)
func (a *appGRPCServer) runGRPCServer(spanCtx context.Context) error {
_, span := a.tracer.Start(spanCtx, "appgrpc.init.start")
defer span.End()
span.SetAttributes(
semconv.RPCSystemGRPC,
semconv.NetworkProtocolName("grpc"),
semconv.ServerAddress(a.opts.Listen),
)
a.shutdownFunc = a.getShutdownFunc()
l, err := net.Listen("tcp", a.opts.Listen)
if err != nil {
a.logger.Err(err).Send()
span.RecordError(err)
span.SetStatus(codes.Error, "failed to acquire net listener")
return err
}
span.AddEvent("network listener acquired")
// Launch GRPC Server
go func() {
if err := a.server.Serve(l); err != nil {
a.logger.Err(err).Send()
a.doneChan <- err
}
}()
span.AddEvent("grpc server goroutine launched")
span.SetStatus(codes.Ok, "")
return nil
}
func (a *appGRPCServer) getShutdownFunc() func(context.Context) error {
return func(ctx context.Context) error {
stoppedChan := make(chan any)
go func() {
a.server.GracefulStop()
stoppedChan <- nil
}()
select {
case <-stoppedChan:
a.logger.Warn().Msg("GRPC server shut down gracefully")
return nil
case <-ctx.Done():
a.logger.Warn().Msg("GRPC server shut down hard")
a.server.Stop()
return ctx.Err()
}
}
}

35
pkg/srv/grpc/services.go Normal file
View File

@@ -0,0 +1,35 @@
package grpc
import (
"context"
"fmt"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/grpc/opts"
)
func (a *appGRPCServer) registerGRPCServices(ctx context.Context) {
ctx, span := a.tracer.Start(ctx, "appgrpc.init.prepare.services", trace.WithAttributes(
attribute.Int("numServices", len(a.opts.Services)),
))
defer span.End()
for _, service := range a.opts.Services {
a.registerGRPCService(ctx, service)
if a.opts.EnableGRPCGateway {
a.registerServiceGatewayHandlers(ctx, service)
}
}
span.SetStatus(codes.Ok, "")
}
func (a *appGRPCServer) registerGRPCService(ctx context.Context, service *opts.GRPCService) {
span := trace.SpanFromContext(ctx)
span.AddEvent(fmt.Sprintf("registered %s service", service.Name))
a.server.RegisterService(service.Type, service.Service)
}

View File

@@ -1,4 +1,7 @@
package srv
// Package http provides functionality for setting up and managing HTTP servers.
// It includes features for health checks, Prometheus metrics, OpenTelemetry
// tracing, and custom middleware integration.
package http
import (
"context"
@@ -7,6 +10,8 @@ import (
"net"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
@@ -17,49 +22,31 @@ import (
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/otel"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
)
var (
httpMeter metric.Meter
httpTracer trace.Tracer
defReadTimeout = 10 * time.Second
defWriteTimeout = 10 * time.Second
defIdleTimeout = 15 * time.Second
httpMeter metric.Meter
httpTracer trace.Tracer
httpPatternWithMethodRegexp = regexp.MustCompile(`(\w+) .*`)
defReadTimeout = 10 * time.Second
defWriteTimeout = 10 * time.Second
defIdleTimeout = 15 * time.Second
)
type HTTPFunc struct {
Path string
HandlerFunc http.HandlerFunc
}
type HTTPServerOpts struct {
Ctx context.Context
HandleFuncs []HTTPFunc
Middleware []http.Handler
HealthCheckFuncs []HealthCheckFunc
CustomListener net.Listener
}
func prepHTTPServer(opts *HTTPServerOpts) *http.Server {
func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
var (
cfg = config.MustFromCtx(opts.Ctx)
l = zerolog.Ctx(opts.Ctx)
mux = &http.ServeMux{}
)
// NOTE: Wraps handle func with otelhttp handler and
// inserts route tag
otelHandleFunc := func(pattern string, handlerFunc func(http.ResponseWriter, *http.Request)) {
handler := otelhttp.WithRouteTag(pattern, http.HandlerFunc(handlerFunc))
mux.Handle(pattern, handler) // Associate pattern with handler
}
healthChecks := handleHealthCheckFunc(opts.Ctx, opts.HealthChecks...)
mux.HandleFunc("/health", healthChecks)
mux.HandleFunc("/", healthChecks)
healthChecks := handleHealthCheckFunc(opts.Ctx, opts.HealthCheckFuncs...)
otelHandleFunc("/health", healthChecks)
otelHandleFunc("/", healthChecks)
for _, f := range opts.HandleFuncs {
otelHandleFunc(f.Path, f.HandlerFunc)
for _, f := range opts.Funcs {
mux.HandleFunc(f.Path, f.HandlerFunc)
}
// Prometheus metrics endpoint
@@ -69,9 +56,25 @@ func prepHTTPServer(opts *HTTPServerOpts) *http.Server {
Msg("mounted prometheus metrics endpoint")
}
// Add OTEL, skip health-check spans
// NOTE: Add any other span exclusions here
// Inject extra handlers if given
// Used for grpc-gateway runtime.ServeMux handlers
for _, h := range opts.Handlers {
// prefix must end in / to route sub-paths
if !strings.HasSuffix(h.Prefix, "/") {
h.Prefix = h.Prefix + "/"
}
// if enabled, the path prefix is stripped before
// requests are sent to the handler
if h.StripPrefix {
h.Handler = http.StripPrefix(h.Prefix[:len(h.Prefix)-1], h.Handler)
}
mux.Handle(h.Prefix, otelhttp.WithRouteTag(h.Prefix, h.Handler))
}
// Add OTEL instrumentation, filter noise, set span names
handler := otelhttp.NewHandler(mux, "/",
// TODO: Make configurable similar to config.http.LogExcludePathRegexps
otelhttp.WithFilter(func(r *http.Request) bool {
switch r.URL.Path {
case "/health":
@@ -81,6 +84,18 @@ func prepHTTPServer(opts *HTTPServerOpts) *http.Server {
default:
return true
}
}),
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
endpoint := r.URL.Path
if _, pattern := mux.Handler(r); pattern != "" {
endpoint = pattern
}
if httpPatternWithMethodRegexp.MatchString(endpoint) {
return endpoint
}
return fmt.Sprintf("%s %s", r.Method, endpoint)
}))
// Set timeouts from defaults, override
@@ -128,25 +143,13 @@ func prepHTTPServer(opts *HTTPServerOpts) *http.Server {
}
}
// Returns a shutdown func and a done channel if the
// server aborts abnormally. Panics on error.
func MustInitHTTPServer(opts *HTTPServerOpts) (
func(context.Context) error, <-chan interface{},
) {
shutdownFunc, doneChan, err := InitHTTPServer(opts)
if err != nil {
panic(err)
}
return shutdownFunc, doneChan
}
// Returns a shutdown func and a done channel if the
// server aborts abnormally. Returns error on failure to start
func InitHTTPServer(opts *HTTPServerOpts) (
func(context.Context) error, <-chan interface{}, error,
// InitHTTPServer returns a shutdown func and a done channel if the
// server aborts abnormally. Returns error on failure to start.
func InitHTTPServer(opts *opts.AppHTTP) (
func(context.Context) error, <-chan any, error,
) {
l := zerolog.Ctx(opts.Ctx)
doneChan := make(chan interface{})
doneChan := make(chan any)
var server *http.Server

View File

@@ -1,4 +1,4 @@
package srv
package http
import (
"context"
@@ -9,11 +9,11 @@ import (
"time"
"github.com/rs/zerolog"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/srv/http/opts"
)
type HealthCheckFunc func(context.Context) error
func handleHealthCheckFunc(ctx context.Context, hcFuncs ...HealthCheckFunc) func(w http.ResponseWriter, r *http.Request) {
func handleHealthCheckFunc(ctx context.Context, hcFuncs ...opts.HealthCheckFunc) func(w http.ResponseWriter, r *http.Request) {
// Return http handle func
return func(w http.ResponseWriter, r *http.Request) {
var (
@@ -55,7 +55,7 @@ func handleHealthCheckFunc(ctx context.Context, hcFuncs ...HealthCheckFunc) func
}
func dummyHealthCheck(ctx context.Context) error {
workFor := rand.Intn(750)
workFor := rand.Intn(740) + 10 // ensure positive
ticker := time.NewTicker(time.Duration(time.Duration(workFor) * time.Millisecond))
select {

View File

@@ -1,14 +1,17 @@
package srv
package http
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"time"
"github.com/rs/zerolog"
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
)
var ExcludeFromLogging = regexp.MustCompile(`\/(ready|live|metrics)$`)
@@ -20,12 +23,22 @@ type LoggingResponseWriter struct {
}
func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
appConfig := config.MustFromCtx(appCtx)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ExcludeFromLogging.Match([]byte(r.URL.Path)) {
next.ServeHTTP(w, r)
return
}
// User-configurable logging exclusions
for _, re := range appConfig.HTTP.GetExcludeRegexps() {
if re.MatchString(r.URL.Path) {
next.ServeHTTP(w, r)
return
}
}
log := zerolog.Ctx(appCtx)
start := time.Now()
@@ -41,29 +54,42 @@ func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
Dur("duration", time.Since(start)).
Msg("http request served")
// Log response body
// Log response with body if not 204
if lrr.statusCode == http.StatusNoContent {
trcLog := log.Trace().
Str("path", r.URL.Path).
Int("statusCode", lrr.statusCode)
trcLog.Msg("http response (no content)") // Explicitly log 204
return // No body to log for 204 No Content
}
trcLog := log.Trace().
Str("path", r.URL.Path).
Int("statusCode", lrr.statusCode)
// Check if it's JSON
firstByte, err := lrr.body.ReadByte()
if err != nil {
trcLog.Err(errors.New("invalid response body")).Send()
return
if err == io.EOF {
// Body is empty, which might be valid for some non-204 responses.
trcLog.Msg("http response (empty body)")
} else {
// Other error reading the body. Wrap the original error for context.
trcLog.Err(fmt.Errorf("error reading response body: %w", err)).Send()
}
return // No further body processing if there was an error or it was empty
}
lrr.body.UnreadByte()
lrr.body.UnreadByte() // Put the byte back for Bytes() to read
if firstByte == '{' {
trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
} else {
trcLog = trcLog.Bytes("response", lrr.body.Bytes())
}
trcLog.Msg("response payload")
trcLog.Msg("http response")
})
}
// Implement Flush to support the http.Flusher interface
// Flush implements the http.Flusher interface to allow flushing buffered data.
func (w *LoggingResponseWriter) Flush() {
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush()

View File

@@ -0,0 +1,30 @@
package opts
import (
"context"
"net"
"net/http"
)
type AppHTTP struct {
Ctx context.Context
Funcs []HTTPFunc // Handler funcs, will be wrapped with OTEL
Middleware []http.Handler // Middleware (e.g. request logging)
Handlers []HTTPHandler // Raw Handler/Mux to add, optional prefix stripping
HealthChecks []HealthCheckFunc
CustomListener net.Listener
HTTPDone <-chan any
}
type HTTPFunc struct {
Path string
HandlerFunc http.HandlerFunc
}
type HTTPHandler struct {
Prefix string // path prefix under which to serve this handler/mux
StripPrefix bool // strip path before sending to handler/mux
Handler http.Handler
}
type HealthCheckFunc func(context.Context) error