Compare commits
29 Commits
Author | SHA1 | Date | |
---|---|---|---|
52752216fd | |||
4f0c5fe665 | |||
5c26accc34 | |||
f8279d9653 | |||
b44b6a331c | |||
adfedc9239 | |||
89f016ed9d | |||
7f60a59d42 | |||
262f6a4232 | |||
4e014d5ea0 | |||
3e319b24fd | |||
f0a699029a | |||
e178956eef | |||
c5da5f7887 | |||
d414754e14 | |||
3b3f7f1f8b | |||
00c8e2e4fc | |||
2cf15a4837 | |||
98fba4eac8 | |||
5aa5dda111 | |||
81676c5404 | |||
075902ecd8 | |||
a83abba4ce | |||
e11c563c3a | |||
96f9213213 | |||
ae00c64684 | |||
004c1b1ee6 | |||
861214be5d | |||
896225effc |
7
TODO.md
7
TODO.md
@ -1,8 +1,13 @@
|
||||
# TODO
|
||||
|
||||
- [x] Pattern for extending config
|
||||
- [ ] Expand config test case to cover GRPC config
|
||||
- [ ] Expand tracing
|
||||
|
||||
## Done
|
||||
|
||||
- [x] Test and troubleshoot GRPC Gateway supprot
|
||||
- [x] Finish implementing GRPC service support
|
||||
- [x] Unit tests
|
||||
- [x] Pattern for extending config
|
||||
- [x] HTTP Logging Middleware
|
||||
- [x] Fix panic with OTEL disabled
|
||||
|
59
go.mod
59
go.mod
@ -1,22 +1,27 @@
|
||||
module gitea.libretechconsulting.com/rmcguire/go-app
|
||||
|
||||
go 1.23.4
|
||||
go 1.24.2
|
||||
|
||||
require (
|
||||
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.58.0
|
||||
go.opentelemetry.io/otel v1.33.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.33.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.33.0
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.55.0
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.33.0
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.33.0
|
||||
go.opentelemetry.io/otel/metric v1.33.0
|
||||
go.opentelemetry.io/otel/sdk v1.33.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.33.0
|
||||
go.opentelemetry.io/otel/trace v1.33.0
|
||||
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.2
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3
|
||||
github.com/prometheus/client_golang v1.22.0
|
||||
github.com/rs/zerolog v1.34.0
|
||||
github.com/swaggest/jsonschema-go v0.3.73
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.60.0
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0
|
||||
go.opentelemetry.io/otel v1.35.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.57.0
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.35.0
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.35.0
|
||||
go.opentelemetry.io/otel/metric v1.35.0
|
||||
go.opentelemetry.io/otel/sdk v1.35.0
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0
|
||||
go.opentelemetry.io/otel/trace v1.35.0
|
||||
google.golang.org/grpc v1.72.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
@ -28,22 +33,20 @@ require (
|
||||
github.com/go-logr/logr v1.4.2 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1 // indirect
|
||||
github.com/klauspost/compress v1.17.11 // 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.61.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.63.0 // indirect
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
github.com/swaggest/refl v1.3.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.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-20250106144421-5f5ef82da422 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250106144421-5f5ef82da422 // indirect
|
||||
google.golang.org/grpc v1.69.2 // indirect
|
||||
google.golang.org/protobuf v1.36.2 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.6.0 // indirect
|
||||
golang.org/x/net v0.39.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250428153025-10db94c68c34 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34 // indirect
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
)
|
||||
|
147
go.sum
147
go.sum
@ -1,5 +1,9 @@
|
||||
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=
|
||||
@ -19,21 +23,24 @@ github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre
|
||||
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/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/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
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.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI=
|
||||
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=
|
||||
@ -46,78 +53,82 @@ 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/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.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
|
||||
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
|
||||
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.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k=
|
||||
github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18=
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
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/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.73 h1:gU1pBzF3pkZ1GDD3dRMdQoCjrA0sldJ+QcM7aSSPgvc=
|
||||
github.com/swaggest/jsonschema-go v0.3.73/go.mod h1:qp+Ym2DIXHlHzch3HKz50gPf2wJhKOrAB/VYqLS2oJU=
|
||||
github.com/swaggest/refl v1.3.1 h1:XGplEkYftR7p9cz1lsiwXMM2yzmOymTE9vneVVpaOh4=
|
||||
github.com/swaggest/refl v1.3.1/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/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw=
|
||||
go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I=
|
||||
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/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/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/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/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/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/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/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/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/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s=
|
||||
go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck=
|
||||
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.60.0 h1:x7wzEgXfnzJcHDwStJT+mxOz4etr2EcexjqhBvmoakw=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.60.0/go.mod h1:rg+RlpR5dKwaS95IyyZqj5Wd4E13lk/msnTS0Xl9lJM=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ=
|
||||
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
|
||||
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0 h1:QcFwRrZLc82r8wODjvyCbP7Ifp3UANaBSmhDSFjnqSc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.35.0/go.mod h1:CXIWhUomyWBG/oY2/r/kLp6K/cmx9e/7DLpBuuGdLCA=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0 h1:m639+BofXTvcY1q8CGs4ItwQarYtJPOWmVobfM1HpVI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.35.0/go.mod h1:LjReUci/F4BUyv+y4dwnq3h/26iNOeC3wAIqgvTIZVo=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.57.0 h1:AHh/lAP1BHrY5gBwk8ncc25FXWm/gmmY3BX258z5nuk=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.57.0/go.mod h1:QpFWz1QxqevfjwzYdbMb4Y1NnlJvqSGwyuU0B4iuc9c=
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.35.0 h1:PB3Zrjs1sG1GBX51SXyTSoOTqcDglmsk7nT6tkKPb/k=
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.35.0/go.mod h1:U2R3XyVPzn0WX7wOIypPuptulsMcPDPs/oiSVOMVnHY=
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.35.0 h1:T0Ec2E+3YZf5bgTNQVet8iTDW7oIk03tXHq+wkwIDnE=
|
||||
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.35.0/go.mod h1:30v2gqH+vYGJsesLWFov8u47EpYTcIQcBjKpI6pJThg=
|
||||
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
|
||||
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w=
|
||||
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
|
||||
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
|
||||
go.opentelemetry.io/proto/otlp v1.6.0 h1:jQjP+AQyTf+Fe7OKj/MfkDrmK4MNVtw2NpXsf9fefDI=
|
||||
go.opentelemetry.io/proto/otlp v1.6.0/go.mod h1:cicgGehlFuNdgZkcALOCh3VE6K/u2tAjzlRhDwmVpZc=
|
||||
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/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY=
|
||||
golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E=
|
||||
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/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/grpc v1.69.2 h1:U3S9QEtbXC0bYNvRtcoklF3xGtLViumSYxWykJS+7AU=
|
||||
google.golang.org/grpc v1.69.2/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4=
|
||||
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=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250428153025-10db94c68c34 h1:0PeQib/pH3nB/5pEmFeVQJotzGohV0dq4Vcp09H5yhE=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250428153025-10db94c68c34/go.mod h1:0awUlEkap+Pb1UMeJwJQQAdJQrt3moU7J2moTy69irI=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34 h1:h6p3mQqrmT1XkHVTfzLdNz1u7IhINeZkz67/xTbOuWs=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250428153025-10db94c68c34/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
|
||||
google.golang.org/grpc v1.72.0 h1:S7UkcVa60b5AAQTaO6ZKamFp1zMZSU0fGDK2WZLbBnM=
|
||||
google.golang.org/grpc v1.72.0/go.mod h1:wH5Aktxcg25y1I3w7H69nHfXdOG3UiadoBtjh3izSDM=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/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=
|
||||
|
@ -1,93 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"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
|
||||
HealthChecks []srv.HealthCheckFunc
|
||||
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(
|
||||
a.AppContext,
|
||||
a.HTTP.Funcs,
|
||||
a.HTTP.HealthChecks...,
|
||||
)
|
||||
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)
|
||||
}
|
25
pkg/app/app_types.go
Normal file
25
pkg/app/app_types.go
Normal file
@ -0,0 +1,25 @@
|
||||
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"
|
||||
)
|
||||
|
||||
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
|
70
pkg/app/init.go
Normal file
70
pkg/app/init.go
Normal file
@ -0,0 +1,70 @@
|
||||
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() {
|
||||
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
72
pkg/app/monitor.go
Normal 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
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
106
pkg/app/run.go
106
pkg/app/run.go
@ -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
47
pkg/app/run_grpc.go
Normal 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
33
pkg/app/run_http.go
Normal 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
40
pkg/app/schema.go
Normal file
@ -0,0 +1,40 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
js "github.com/swaggest/jsonschema-go"
|
||||
)
|
||||
|
||||
// Generates json schema for app's config.AppConfig
|
||||
func (app *App) Schema() ([]byte, error) {
|
||||
r := js.Reflector{}
|
||||
|
||||
s, err := r.Reflect(*app.cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return json.MarshalIndent(s, "", " ")
|
||||
}
|
||||
|
||||
// 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, "", " ")
|
||||
}
|
@ -19,7 +19,7 @@ import (
|
||||
// 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
|
||||
|
@ -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,
|
||||
|
@ -1,96 +1,45 @@
|
||||
package config
|
||||
|
||||
import "time"
|
||||
|
||||
// Default Settings
|
||||
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"`
|
||||
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
|
||||
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"`
|
||||
func (ac *AppConfig) OTELEnabled() bool {
|
||||
if ac.OTEL != nil && ac.OTEL.Enabled {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
20
pkg/config/types_grpc.go
Normal file
20
pkg/config/types_grpc.go
Normal file
@ -0,0 +1,20 @@
|
||||
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"`
|
||||
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"`
|
||||
}
|
26
pkg/config/types_http.go
Normal file
26
pkg/config/types_http.go
Normal file
@ -0,0 +1,26 @@
|
||||
package config
|
||||
|
||||
import "time"
|
||||
|
||||
var defaultHTTPConfig = &HTTPConfig{
|
||||
Enabled: true,
|
||||
Listen: "127.0.0.1:8080",
|
||||
|
||||
LogRequests: false,
|
||||
ReadTimeout: "10s",
|
||||
WriteTimeout: "10s",
|
||||
IdleTimeout: "1m",
|
||||
}
|
||||
|
||||
// HTTP 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"`
|
||||
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)
|
||||
rT *time.Duration
|
||||
wT *time.Duration
|
||||
iT *time.Duration
|
||||
}
|
42
pkg/config/types_logging.go
Normal file
42
pkg/config/types_logging.go
Normal file
@ -0,0 +1,42 @@
|
||||
package config
|
||||
|
||||
var defaultLoggingConfig = &LogConfig{
|
||||
Enabled: true,
|
||||
Level: "info",
|
||||
Format: LogFormatJSON,
|
||||
Output: "stderr",
|
||||
TimeFormat: TimeFormatLong,
|
||||
}
|
||||
|
||||
// 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
18
pkg/config/types_otel.go
Normal file
@ -0,0 +1,18 @@
|
||||
package config
|
||||
|
||||
var defaultOTELConfig = &OTELConfig{
|
||||
Enabled: true,
|
||||
PrometheusEnabled: true,
|
||||
PrometheusPath: "/metrics",
|
||||
StdoutEnabled: false,
|
||||
MetricIntervalSecs: 30,
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
@ -38,7 +38,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 ""
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,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"
|
||||
)
|
||||
@ -44,7 +44,7 @@ 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,6 +170,7 @@ func newResource(ctx context.Context) *resource.Resource {
|
||||
attributes := []attribute.KeyValue{
|
||||
semconv.ServiceName(cfg.Name),
|
||||
semconv.ServiceVersion(cfg.Version),
|
||||
semconv.DeploymentEnvironmentName(cfg.Environment),
|
||||
semconv.K8SPodName(os.Getenv("HOSTNAME")),
|
||||
}
|
||||
|
||||
@ -181,9 +182,7 @@ func newResource(ctx context.Context) *resource.Resource {
|
||||
// Conditionally provides an OTLP metrics exporter
|
||||
func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider, error) {
|
||||
// OTEL Prometheus Exporter
|
||||
exporter, err := prometheus.New(
|
||||
prometheus.WithResourceAsConstantLabels(attribute.NewDenyKeysFilter()),
|
||||
)
|
||||
exporter, err := prometheus.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -202,7 +201,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
|
||||
|
65
pkg/srv/grpc/gateway.go
Normal file
65
pkg/srv/grpc/gateway.go
Normal 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
|
||||
}
|
99
pkg/srv/grpc/grpc.go
Normal file
99
pkg/srv/grpc/grpc.go
Normal file
@ -0,0 +1,99 @@
|
||||
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
|
||||
}
|
||||
|
||||
// Returns a shutdown func, a channel indicating done / error,
|
||||
// and an up-front error if 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
51
pkg/srv/grpc/logger.go
Normal 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"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Returns a grpcLogger using the global zerolog Logger
|
||||
func NewGRPCLogger() *GRPCLogger {
|
||||
return &GRPCLogger{logger: log.Logger}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
43
pkg/srv/grpc/opts/config.go
Normal file
43
pkg/srv/grpc/opts/config.go
Normal 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
|
||||
}
|
101
pkg/srv/grpc/prepare.go
Normal file
101
pkg/srv/grpc/prepare.go
Normal file
@ -0,0 +1,101 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
grpclogging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
|
||||
"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)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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
66
pkg/srv/grpc/run.go
Normal 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
35
pkg/srv/grpc/services.go
Normal 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)
|
||||
}
|
@ -1,9 +1,13 @@
|
||||
package srv
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
@ -14,6 +18,7 @@ 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 (
|
||||
@ -24,15 +29,10 @@ var (
|
||||
defIdleTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type HTTPFunc struct {
|
||||
Path string
|
||||
HandlerFunc http.HandlerFunc
|
||||
}
|
||||
|
||||
func prepHTTPServer(ctx context.Context, handleFuncs []HTTPFunc, hcFuncs ...HealthCheckFunc) *http.Server {
|
||||
func prepHTTPServer(opts *opts.AppHTTP) *http.Server {
|
||||
var (
|
||||
cfg = config.MustFromCtx(ctx)
|
||||
l = zerolog.Ctx(ctx)
|
||||
cfg = config.MustFromCtx(opts.Ctx)
|
||||
l = zerolog.Ctx(opts.Ctx)
|
||||
mux = &http.ServeMux{}
|
||||
)
|
||||
|
||||
@ -43,11 +43,11 @@ func prepHTTPServer(ctx context.Context, handleFuncs []HTTPFunc, hcFuncs ...Heal
|
||||
mux.Handle(pattern, handler) // Associate pattern with handler
|
||||
}
|
||||
|
||||
healthChecks := handleHealthCheckFunc(ctx, hcFuncs...)
|
||||
healthChecks := handleHealthCheckFunc(opts.Ctx, opts.HealthChecks...)
|
||||
otelHandleFunc("/health", healthChecks)
|
||||
otelHandleFunc("/", healthChecks)
|
||||
|
||||
for _, f := range handleFuncs {
|
||||
for _, f := range opts.Funcs {
|
||||
otelHandleFunc(f.Path, f.HandlerFunc)
|
||||
}
|
||||
|
||||
@ -58,6 +58,22 @@ func prepHTTPServer(ctx context.Context, handleFuncs []HTTPFunc, hcFuncs ...Heal
|
||||
Msg("mounted prometheus metrics endpoint")
|
||||
}
|
||||
|
||||
// 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, h.Handler)
|
||||
}
|
||||
|
||||
// Add OTEL, skip health-check spans
|
||||
// NOTE: Add any other span exclusions here
|
||||
handler := otelhttp.NewHandler(mux, "/",
|
||||
@ -89,9 +105,19 @@ func prepHTTPServer(ctx context.Context, handleFuncs []HTTPFunc, hcFuncs ...Heal
|
||||
idleTimeout = *iT
|
||||
}
|
||||
|
||||
// Inject any supplied middleware
|
||||
for i := len(opts.Middleware) - 1; i >= 0; i-- {
|
||||
mw := opts.Middleware[i]
|
||||
next := handler
|
||||
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mw.ServeHTTP(w, r)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Inject logging middleware
|
||||
if cfg.HTTP.LogRequests {
|
||||
handler = loggingMiddleware(ctx, handler)
|
||||
handler = loggingMiddleware(opts.Ctx, handler)
|
||||
}
|
||||
|
||||
return &http.Server{
|
||||
@ -100,50 +126,49 @@ func prepHTTPServer(ctx context.Context, handleFuncs []HTTPFunc, hcFuncs ...Heal
|
||||
WriteTimeout: writeTimeout,
|
||||
IdleTimeout: idleTimeout,
|
||||
Handler: handler,
|
||||
ErrorLog: log.New(os.Stderr, fmt.Sprintf("Go-HTTP[%s]", cfg.Name), log.Flags()),
|
||||
BaseContext: func(_ net.Listener) context.Context {
|
||||
return ctx
|
||||
return opts.Ctx
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Returns a shutdown func and a done channel if the
|
||||
// server aborts abnormally. Panics on error.
|
||||
func MustInitHTTPServer(ctx context.Context, funcs []HTTPFunc, hcFuncs ...HealthCheckFunc) (
|
||||
func(context.Context) error, <-chan interface{},
|
||||
) {
|
||||
shutdownFunc, doneChan, err := InitHTTPServer(ctx, funcs, hcFuncs...)
|
||||
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(ctx context.Context, funcs []HTTPFunc, hcFuncs ...HealthCheckFunc) (
|
||||
func(context.Context) error, <-chan interface{}, error,
|
||||
func InitHTTPServer(opts *opts.AppHTTP) (
|
||||
func(context.Context) error, <-chan any, error,
|
||||
) {
|
||||
l := zerolog.Ctx(ctx)
|
||||
doneChan := make(chan interface{})
|
||||
l := zerolog.Ctx(opts.Ctx)
|
||||
doneChan := make(chan any)
|
||||
|
||||
var server *http.Server
|
||||
|
||||
httpMeter = otel.GetMeter(ctx, "http")
|
||||
httpTracer = otel.GetTracer(ctx, "http")
|
||||
httpMeter = otel.GetMeter(opts.Ctx, "http")
|
||||
httpTracer = otel.GetTracer(opts.Ctx, "http")
|
||||
|
||||
server = prepHTTPServer(ctx, funcs, hcFuncs...)
|
||||
server = prepHTTPServer(opts)
|
||||
|
||||
go func() {
|
||||
l.Debug().Msg("HTTP Server Started")
|
||||
err := server.ListenAndServe()
|
||||
var err error
|
||||
|
||||
if opts.CustomListener != nil {
|
||||
err = server.Serve(opts.CustomListener)
|
||||
} else {
|
||||
err = server.ListenAndServe()
|
||||
}
|
||||
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
l.Err(err).Msg("HTTP server error")
|
||||
} else {
|
||||
l.Info().Msg("HTTP server shut down")
|
||||
}
|
||||
|
||||
// Notify app initiator
|
||||
doneChan <- nil
|
||||
}()
|
||||
|
||||
l.Debug().Msg("HTTP Server Started")
|
||||
|
||||
// Shut down http server with a deadline
|
||||
return func(shutdownCtx context.Context) error {
|
||||
l.Debug().Msg("stopping http server")
|
@ -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 (
|
@ -1,4 +1,4 @@
|
||||
package srv
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
30
pkg/srv/http/opts/http_config.go
Normal file
30
pkg/srv/http/opts/http_config.go
Normal 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
|
Loading…
x
Reference in New Issue
Block a user