Compare commits
24 Commits
Author | SHA1 | Date | |
---|---|---|---|
f0a699029a | |||
e178956eef | |||
c5da5f7887 | |||
d414754e14 | |||
3b3f7f1f8b | |||
00c8e2e4fc | |||
2cf15a4837 | |||
98fba4eac8 | |||
5aa5dda111 | |||
81676c5404 | |||
075902ecd8 | |||
a83abba4ce | |||
e11c563c3a | |||
96f9213213 | |||
ae00c64684 | |||
004c1b1ee6 | |||
861214be5d | |||
896225effc | |||
06bf7ebca7 | |||
15a597de1d | |||
56037c4b05 | |||
70ba85bf79 | |||
55e3a68db6 | |||
c47eae8afa |
10
TODO.md
10
TODO.md
@ -1,3 +1,11 @@
|
||||
# TODO
|
||||
|
||||
- [ ] Unit tests
|
||||
- [ ] Finish implementing GRPC service support
|
||||
- [ ] Expand config test case to cover GRPC config
|
||||
- [ ] Expand tracing
|
||||
|
||||
## Done
|
||||
- [x] Unit tests
|
||||
- [x] Pattern for extending config
|
||||
- [x] HTTP Logging Middleware
|
||||
- [x] Fix panic with OTEL disabled
|
||||
|
52
go.mod
52
go.mod
@ -4,19 +4,22 @@ go 1.23.4
|
||||
|
||||
require (
|
||||
github.com/caarlos0/env/v11 v11.3.1
|
||||
github.com/prometheus/client_golang v1.20.5
|
||||
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.1
|
||||
github.com/prometheus/client_golang v1.21.1
|
||||
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
|
||||
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.71.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
@ -28,22 +31,21 @@ 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.13 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // 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/common v0.62.0 // indirect
|
||||
github.com/prometheus/procfs v0.15.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.4.0 // indirect
|
||||
golang.org/x/net v0.33.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-20250102185135-69823020774d // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250102185135-69823020774d // indirect
|
||||
google.golang.org/grpc v1.69.2 // indirect
|
||||
google.golang.org/protobuf v1.36.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.5.0 // indirect
|
||||
golang.org/x/net v0.37.0 // indirect
|
||||
golang.org/x/sys v0.31.0 // indirect
|
||||
golang.org/x/text v0.23.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect
|
||||
google.golang.org/protobuf v1.36.5 // indirect
|
||||
)
|
||||
|
110
go.sum
110
go.sum
@ -23,10 +23,20 @@ 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/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/go-grpc-middleware/v2 v2.3.1 h1:KcFzXwzM/kGhIRHvc8jdixfIJjVzuUJdnv+5xsPutog=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.1/go.mod h1:qOchhhIlmRcqk/O9uCo/puJlyo07YINaIqdZfZG3Jkc=
|
||||
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/grpc-ecosystem/grpc-gateway/v2 v2.26.1 h1:e9Rjr40Z98/clHv5Yg79Is0NtosR5LXRvdr7o/6NwbA=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.1/go.mod h1:tIxuGz/9mpox++sgp9fJjHO0+q1X9/UOWd798aAm22M=
|
||||
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/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||
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=
|
||||
@ -35,6 +45,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
|
||||
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=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
@ -46,10 +58,14 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
||||
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_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk=
|
||||
github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg=
|
||||
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/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
@ -61,51 +77,145 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
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/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.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/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.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 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.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/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.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 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.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/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.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/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.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/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.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/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.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/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.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 v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
|
||||
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/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.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/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.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.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.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||
golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c=
|
||||
golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||
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/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
|
||||
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
|
||||
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/api v0.0.0-20250212204824-5a70512c5d8b h1:i+d0RZa8Hs2L/MuaOQYI+krthcxdEbEM2N+Tf3kJ4zk=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250212204824-5a70512c5d8b/go.mod h1:iYONQfRdizDB8JJBybql13nArx91jcUk7zCXEsOofM4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb h1:p31xT4yrYrSM/G4Sn2+TNUkVhFCbG9y8itM2S6Th950=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:jbe3Bkdp+Dh2IrslsFCklNhweNTBgSYanP1UXhJDhKg=
|
||||
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/genproto/googleapis/rpc v0.0.0-20250212204824-5a70512c5d8b h1:FQtJ1MxbXoIIrZHZ33M+w5+dAP9o86rgpjoKr/ZmT7k=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250212204824-5a70512c5d8b/go.mod h1:8BS3B93F/U1juMFq9+EDk+qOT5CO1R9IzXxG3PTqiRk=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a h1:51aaUVRocpvUOSQKM6Q7VuoaktNIaMCLuhZB6DKksq4=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250218202821-56aae31c358a/go.mod h1:uRxBH1mhmO8PGhU89cMcHaXKZqO+OfakD8QQO0oYwlQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb h1:TLPQVbx1GJ8VKZxz52VAxl1EBgKXXbTiU9Fc5fZeLn4=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I=
|
||||
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/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg=
|
||||
google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec=
|
||||
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=
|
||||
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM=
|
||||
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
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,40 +1,17 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"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{} {
|
||||
func (a *App) Done() <-chan any {
|
||||
return a.appDone
|
||||
}
|
||||
|
||||
@ -47,20 +24,55 @@ func (a *App) MustRun() {
|
||||
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{})
|
||||
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()
|
||||
var initSpan trace.Span
|
||||
_, initSpan = a.tracer.Start(a.AppContext, "init")
|
||||
|
||||
// Start HTTP
|
||||
a.initHTTP()
|
||||
ctx, initSpan := a.tracer.Start(a.AppContext, "init")
|
||||
defer initSpan.End()
|
||||
|
||||
var serverWG sync.WaitGroup
|
||||
|
||||
// Start HTTP (does not block)
|
||||
if a.cfg.HTTPEnabled() {
|
||||
serverWG.Add(1)
|
||||
go func() {
|
||||
defer serverWG.Done()
|
||||
if err := a.initHTTP(ctx); err != nil {
|
||||
initSpan.RecordError(err)
|
||||
initSpan.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
initSpan.AddEvent("http server started")
|
||||
initSpan.SetAttributes(attribute.Int("http.handlers", len(a.HTTP.Funcs)))
|
||||
}()
|
||||
}
|
||||
|
||||
// Start GRPC (does not block)
|
||||
if a.cfg.GRPCEnabled() {
|
||||
serverWG.Add(1)
|
||||
go func() {
|
||||
defer serverWG.Done()
|
||||
if err := a.initGRPC(ctx); err != nil {
|
||||
initSpan.RecordError(err)
|
||||
initSpan.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
initSpan.AddEvent("grpc server started")
|
||||
initSpan.SetAttributes(attribute.Int("grpc.services", len(a.GRPC.Services)))
|
||||
}()
|
||||
}
|
||||
|
||||
serverWG.Wait()
|
||||
|
||||
// Monitor app lifecycle
|
||||
go a.run()
|
||||
@ -72,22 +84,4 @@ func (a *App) MustRun() {
|
||||
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)
|
||||
}
|
||||
|
70
pkg/app/app_init.go
Normal file
70
pkg/app/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)
|
||||
}
|
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
|
@ -5,6 +5,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
)
|
||||
|
||||
@ -16,12 +17,14 @@ func (a *App) run() {
|
||||
case <-a.AppContext.Done():
|
||||
a.l.Warn().Str("reason", a.AppContext.Err().Error()).
|
||||
Msg("shutting down on context done")
|
||||
case <-a.HTTP.httpDone:
|
||||
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()
|
||||
|
||||
a.appDone <- nil
|
||||
a.Shutdown() // Run through all shutdown funcs
|
||||
a.appDone <- nil // Notify app
|
||||
}
|
||||
|
||||
// Typically invoked when AppContext is done
|
||||
@ -48,6 +51,8 @@ func (a *App) Shutdown() {
|
||||
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))
|
||||
|
||||
|
@ -23,3 +23,10 @@ func MustSetupConfigAndLogging(ctx context.Context) context.Context {
|
||||
zerolog.Ctx(ctx).Trace().Any("config", *cfg).Send()
|
||||
return ctx
|
||||
}
|
||||
|
||||
// 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) {
|
||||
return ctx, into
|
||||
}
|
||||
|
107
pkg/app/setup_custom.go
Normal file
107
pkg/app/setup_custom.go
Normal file
@ -0,0 +1,107 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
|
||||
)
|
||||
|
||||
// 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 {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Step 2: Do the normal thing
|
||||
ctx = MustSetupConfigAndLogging(ctx)
|
||||
|
||||
// Step 3: Extract the config
|
||||
cfg := config.MustFromCtx(ctx)
|
||||
|
||||
// Step 4: Unmarshal custom config
|
||||
configPath := flag.Lookup("config")
|
||||
if configPath != nil && configPath.Value.String() != "" {
|
||||
file, err := os.Open(configPath.Value.String())
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("could not open config file: %w", err))
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
decoder := yaml.NewDecoder(file)
|
||||
if err := decoder.Decode(into); err != nil {
|
||||
panic(fmt.Errorf("could not decode config file: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
// Step 5: Re-apply AppConfig to custom type
|
||||
if err := setAppConfig(into, cfg); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Step 6: Update context, return custom type
|
||||
return ctx, into
|
||||
}
|
||||
|
||||
func setAppConfig[T any](target T, appConfig *config.AppConfig) error {
|
||||
// Ensure target is a pointer to a struct
|
||||
v := reflect.ValueOf(target)
|
||||
if v.Kind() != reflect.Ptr || v.IsNil() {
|
||||
return errors.New("target must be a non-nil pointer to a struct")
|
||||
}
|
||||
|
||||
v = v.Elem() // Dereference the pointer
|
||||
if v.Kind() != reflect.Struct {
|
||||
return errors.New("target must be a pointer to a struct")
|
||||
}
|
||||
|
||||
// Replace *config.AppConfig
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
field := v.Field(i)
|
||||
if field.Type() == reflect.TypeOf((*config.AppConfig)(nil)) {
|
||||
if !field.CanSet() {
|
||||
return fmt.Errorf("field %q cannot be set", v.Type().Field(i).Name)
|
||||
}
|
||||
field.Set(reflect.ValueOf(appConfig))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return errors.New("no *config.AppConfig field found in target struct")
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
v = v.Elem()
|
||||
|
||||
if v.Kind() != reflect.Struct {
|
||||
return errors.New("target must be a pointer to a struct")
|
||||
}
|
||||
|
||||
hasAppConfig := false
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
field := v.Type().Field(i)
|
||||
if field.Type == reflect.TypeOf((*config.AppConfig)(nil)) {
|
||||
hasAppConfig = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasAppConfig {
|
||||
return errors.New("struct does not contain a *config.AppConfig field")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
123
pkg/app/setup_test.go
Normal file
123
pkg/app/setup_test.go
Normal file
@ -0,0 +1,123 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"flag"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"testing"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
|
||||
)
|
||||
|
||||
func TestMustSetupConfigAndLogging(t *testing.T) {
|
||||
// Configure app and logger
|
||||
type inputs struct {
|
||||
envs map[string]string
|
||||
}
|
||||
type outputs struct {
|
||||
appName string
|
||||
logLevel zerolog.Level
|
||||
logRegexChecks []*regexp.Regexp
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
inputs inputs
|
||||
want outputs
|
||||
}{
|
||||
{
|
||||
name: "Test json logging with short timestamp",
|
||||
inputs: inputs{
|
||||
envs: map[string]string{
|
||||
"APP_NAME": "testapp",
|
||||
"APP_LOG_LEVEL": "warn",
|
||||
"APP_LOG_FORMAT": "json",
|
||||
"APP_LOG_TIME_FORMAT": "short",
|
||||
},
|
||||
},
|
||||
want: outputs{
|
||||
appName: "testapp",
|
||||
logLevel: zerolog.WarnLevel,
|
||||
logRegexChecks: []*regexp.Regexp{
|
||||
regexp.MustCompile(`^\{.*time":"\d{1,}:\d{2}`),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Test json logging with unix timestamp",
|
||||
inputs: inputs{
|
||||
envs: map[string]string{
|
||||
"APP_NAME": "testapp",
|
||||
"APP_LOG_LEVEL": "info",
|
||||
"APP_LOG_FORMAT": "json",
|
||||
"APP_LOG_TIME_FORMAT": "unix",
|
||||
},
|
||||
},
|
||||
want: outputs{
|
||||
appName: "testapp",
|
||||
logLevel: zerolog.InfoLevel,
|
||||
logRegexChecks: []*regexp.Regexp{
|
||||
regexp.MustCompile(`time":\d+,`),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Set environment variables
|
||||
for key, val := range tt.inputs.envs {
|
||||
os.Setenv(key, val)
|
||||
}
|
||||
|
||||
// Prepare config in context
|
||||
ctx := MustSetupConfigAndLogging(context.Background())
|
||||
|
||||
// Retrieve config and logger from prepared context
|
||||
cfg := config.MustFromCtx(ctx)
|
||||
logger := zerolog.Ctx(ctx)
|
||||
|
||||
// Check wants
|
||||
if cfg.Name != tt.want.appName {
|
||||
t.Errorf("Expected app name %s, got %s", tt.want.appName, cfg.Name)
|
||||
}
|
||||
if logger.GetLevel() != tt.want.logLevel {
|
||||
t.Errorf("Expected log level %#v, got %#v", tt.want.logLevel, logger.GetLevel())
|
||||
}
|
||||
|
||||
// Send and capture a log
|
||||
r, w := io.Pipe()
|
||||
testLogger := logger.Output(w)
|
||||
scanner := bufio.NewScanner(r)
|
||||
|
||||
go func() {
|
||||
testLogger.Error().Msg("test message")
|
||||
w.Close()
|
||||
}()
|
||||
|
||||
logOut := make([]byte, 0)
|
||||
if scanner.Scan() {
|
||||
logOut = scanner.Bytes()
|
||||
}
|
||||
|
||||
// Check all expressions
|
||||
for _, expr := range tt.want.logRegexChecks {
|
||||
if !expr.Match(logOut) {
|
||||
t.Errorf("Regex %s did not match log %s", expr.String(), logOut)
|
||||
}
|
||||
}
|
||||
|
||||
// Super annoying need to reset due to app framework package
|
||||
// using flag.Parse() and go test also using it
|
||||
testlog := flag.Lookup("test.testlogfile").Value.String()
|
||||
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
|
||||
flag.String("test.testlogfile", testlog, "")
|
||||
flag.String("test.paniconexit0", "", "")
|
||||
flag.String("test.v", "", "")
|
||||
flag.Parse()
|
||||
})
|
||||
}
|
||||
}
|
89
pkg/config/config_test.go
Normal file
89
pkg/config/config_test.go
Normal file
@ -0,0 +1,89 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Changing defaults could be a breaking change,
|
||||
// if this needs to be modified to pass the test,
|
||||
// an item should be added to the changelog.
|
||||
//
|
||||
// This should be maintained, as it is the primary
|
||||
// interface between an app and the app framework.
|
||||
var testDefaultConfig = &AppConfig{
|
||||
Environment: "development",
|
||||
Version: getVersion(),
|
||||
Logging: &LogConfig{
|
||||
Enabled: true,
|
||||
Level: "info",
|
||||
Format: LogFormatJSON,
|
||||
Output: "stderr",
|
||||
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,
|
||||
PrometheusPath: "/metrics",
|
||||
StdoutEnabled: false,
|
||||
MetricIntervalSecs: 30,
|
||||
},
|
||||
}
|
||||
|
||||
func Test_loadConfig(t *testing.T) {
|
||||
type args struct {
|
||||
configPath string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *AppConfig
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Ensure defaults",
|
||||
args: args{configPath: ""},
|
||||
want: testDefaultConfig,
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := loadConfig(tt.args.configPath)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("loadConfig() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
|
||||
// Marshal both the expected and actual structs to JSON
|
||||
gotJSON, err := json.Marshal(got)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal got to JSON: %v", err)
|
||||
}
|
||||
wantJSON, err := json.Marshal(tt.want)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal want to JSON: %v", err)
|
||||
}
|
||||
|
||||
// Compare the JSON strings
|
||||
if string(gotJSON) != string(wantJSON) {
|
||||
t.Errorf("loadConfig() JSON = %s, want JSON = %s", string(gotJSON), string(wantJSON))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
43
pkg/config/ctx_test.go
Normal file
43
pkg/config/ctx_test.go
Normal file
@ -0,0 +1,43 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFromCtx(t *testing.T) {
|
||||
app := &AppConfig{
|
||||
Name: "testapp",
|
||||
}
|
||||
appCtx := app.AddToCtx(context.Background())
|
||||
|
||||
type args struct {
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Unprepared app context",
|
||||
args: args{ctx: context.Background()},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Prepared app context",
|
||||
args: args{ctx: appCtx},
|
||||
wantErr: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
_, err := FromCtx(tt.args.ctx)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("FromCtx() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
@ -1,31 +1,13 @@
|
||||
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",
|
||||
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 {
|
||||
@ -38,57 +20,26 @@ type AppConfig struct {
|
||||
Logging *LogConfig `yaml:"logging,omitempty"`
|
||||
HTTP *HTTPConfig `yaml:"http,omitempty"`
|
||||
OTEL *OTELConfig `yaml:"otel,omitempty"`
|
||||
GRPC *GRPCConfig `yaml:"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"`
|
||||
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
|
||||
}
|
||||
|
18
pkg/config/types_grpc.go
Normal file
18
pkg/config/types_grpc.go
Normal file
@ -0,0 +1,18 @@
|
||||
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"`
|
||||
Listen string `yaml:"listen" env:"APP_GRPC_LISTEN"`
|
||||
LogRequests bool `yaml:"logRequests" env:"APP_GRPC_LOG_REQUESTS"`
|
||||
EnableReflection bool `yaml:"enableReflection" env:"APP_GRPC_ENABLE_REFLECTION"`
|
||||
EnableInstrumentation bool `yaml:"enableInstrumentation" env:"APP_GRPC_ENABLE_INSTRUMENTATION"` // requires OTEL
|
||||
}
|
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"`
|
||||
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 `yaml:"rT" env:"rT"`
|
||||
wT *time.Duration `yaml:"wT" env:"wT"`
|
||||
iT *time.Duration `yaml:"iT" env:"iT"`
|
||||
}
|
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"`
|
||||
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"`
|
||||
}
|
||||
|
||||
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"`
|
||||
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"`
|
||||
}
|
@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
opentelemetry "go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
|
||||
"go.opentelemetry.io/otel/exporters/prometheus"
|
||||
@ -21,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"
|
||||
)
|
||||
@ -43,9 +44,14 @@ 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
|
||||
meter := opentelemetry.Meter(cfg.Name)
|
||||
ctx = AddMeterToCtx(ctx, meter)
|
||||
tracer := opentelemetry.Tracer(cfg.Name)
|
||||
ctx = AddTracerToCtx(ctx, tracer)
|
||||
return ctx, func(context.Context) error {
|
||||
return nil
|
||||
}
|
||||
@ -62,12 +68,12 @@ func Init(ctx context.Context) (context.Context, func(context.Context) error) {
|
||||
if cfg.OTEL.StdoutEnabled {
|
||||
options = append(options, EnableStdoutExporter)
|
||||
}
|
||||
if cfg.OTEL.MetricIntervalSecs > 0 {
|
||||
metricInterval = time.Duration(cfg.OTEL.MetricIntervalSecs) * time.Second
|
||||
}
|
||||
if cfg.OTEL.PrometheusEnabled {
|
||||
options = append(options, EnablePrometheusExporter)
|
||||
}
|
||||
if cfg.OTEL.MetricIntervalSecs > 0 {
|
||||
metricInterval = time.Duration(cfg.OTEL.MetricIntervalSecs) * time.Second
|
||||
}
|
||||
options = append(options,
|
||||
WithMetricExportInterval(metricInterval))
|
||||
|
||||
@ -134,7 +140,7 @@ func newPropagator() propagation.TextMapPropagator {
|
||||
|
||||
func (s *settings) newTracerProvider(ctx context.Context) (traceProvider *traceSDK.TracerProvider, err error) {
|
||||
traceOpts := []traceSDK.TracerProviderOption{
|
||||
traceSDK.WithResource(newResource()),
|
||||
traceSDK.WithResource(newResource(ctx)),
|
||||
}
|
||||
|
||||
host, set := os.LookupEnv("OTEL_EXPORTER_OTLP_ENDPOINT")
|
||||
@ -159,8 +165,16 @@ func (s *settings) newTracerProvider(ctx context.Context) (traceProvider *traceS
|
||||
return
|
||||
}
|
||||
|
||||
func newResource() *resource.Resource {
|
||||
return resource.NewWithAttributes(semconv.SchemaURL)
|
||||
func newResource(ctx context.Context) *resource.Resource {
|
||||
cfg := config.MustFromCtx(ctx)
|
||||
attributes := []attribute.KeyValue{
|
||||
semconv.ServiceName(cfg.Name),
|
||||
semconv.ServiceVersion(cfg.Version),
|
||||
semconv.DeploymentEnvironmentName(cfg.Environment),
|
||||
semconv.K8SPodName(os.Getenv("HOSTNAME")),
|
||||
}
|
||||
|
||||
return resource.NewWithAttributes(semconv.SchemaURL, attributes...)
|
||||
}
|
||||
|
||||
// Configures meter provider
|
||||
@ -187,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
|
||||
@ -197,6 +211,7 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
|
||||
var meterProvider *metric.MeterProvider
|
||||
if otlpExporter != nil {
|
||||
metricOptions = append(metricOptions,
|
||||
metric.WithResource(newResource(ctx)),
|
||||
metric.WithReader(exporter),
|
||||
metric.WithReader(
|
||||
metric.NewPeriodicReader(
|
||||
@ -204,12 +219,11 @@ func (s *settings) newMeterProvider(ctx context.Context) (*metric.MeterProvider,
|
||||
metric.WithInterval(s.MetricExportInterval),
|
||||
),
|
||||
),
|
||||
metric.WithResource(newResource()),
|
||||
)
|
||||
} else {
|
||||
metricOptions = append(metricOptions,
|
||||
metric.WithResource(newResource(ctx)),
|
||||
metric.WithReader(exporter),
|
||||
metric.WithResource(newResource()),
|
||||
)
|
||||
}
|
||||
|
||||
|
97
pkg/srv/grpc/grpc.go
Normal file
97
pkg/srv/grpc/grpc.go
Normal file
@ -0,0 +1,97 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"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
|
||||
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/grpc_logger.go
Normal file
51
pkg/srv/grpc/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)
|
||||
}
|
96
pkg/srv/grpc/grpc_prepare.go
Normal file
96
pkg/srv/grpc/grpc_prepare.go
Normal file
@ -0,0 +1,96 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
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
|
||||
for _, service := range a.opts.Services {
|
||||
span.AddEvent(fmt.Sprintf("registered %s service", service.Name))
|
||||
a.server.RegisterService(service.Type, service.Service)
|
||||
}
|
||||
span.SetAttributes(attribute.Int("grpc.server.grpcservices", len(a.opts.Services)))
|
||||
|
||||
// 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, "")
|
||||
}
|
||||
}
|
67
pkg/srv/grpc/grpc_run.go
Normal file
67
pkg/srv/grpc/grpc_run.go
Normal file
@ -0,0 +1,67 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.27.0"
|
||||
)
|
||||
|
||||
// TODO: Implement
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
26
pkg/srv/grpc/opts/grpc_config.go
Normal file
26
pkg/srv/grpc/opts/grpc_config.go
Normal file
@ -0,0 +1,26 @@
|
||||
package opts
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/go-app/pkg/config"
|
||||
)
|
||||
|
||||
type GRPCOpts struct {
|
||||
*config.GRPCConfig
|
||||
*AppGRPC
|
||||
}
|
||||
|
||||
type AppGRPC struct {
|
||||
Services []*GRPCService
|
||||
UnaryInterceptors []grpc.UnaryServerInterceptor
|
||||
StreamInterceptors []grpc.StreamServerInterceptor
|
||||
GRPCOpts []grpc.ServerOption
|
||||
GRPCDone <-chan error
|
||||
}
|
||||
|
||||
type GRPCService struct {
|
||||
Name string // Descriptive name of service
|
||||
Type *grpc.ServiceDesc // Type (from protoc generated code)
|
||||
Service any // Implementation of GRPCService.Type (ptr)
|
||||
}
|
@ -1,9 +1,12 @@
|
||||
package srv
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
@ -14,6 +17,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 +28,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 +42,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)
|
||||
}
|
||||
|
||||
@ -89,56 +88,70 @@ 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(opts.Ctx, handler)
|
||||
}
|
||||
|
||||
return &http.Server{
|
||||
Addr: cfg.HTTP.Listen,
|
||||
ReadTimeout: readTimeout,
|
||||
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 (
|
87
pkg/srv/http/http_log.go
Normal file
87
pkg/srv/http/http_log.go
Normal file
@ -0,0 +1,87 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var ExcludeFromLogging = regexp.MustCompile(`\/(ready|live|metrics)$`)
|
||||
|
||||
type LoggingResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
func loggingMiddleware(appCtx context.Context, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if ExcludeFromLogging.Match([]byte(r.URL.Path)) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
log := zerolog.Ctx(appCtx)
|
||||
|
||||
start := time.Now()
|
||||
lrr := newLoggingResponseWriter(w)
|
||||
next.ServeHTTP(lrr, r)
|
||||
|
||||
log.Debug().
|
||||
Str("path", r.URL.Path).
|
||||
Any("query", r.URL.Query()).
|
||||
Int("statusCode", lrr.statusCode).
|
||||
Str("protocol", r.Proto).
|
||||
Str("remote", r.RemoteAddr).
|
||||
Dur("duration", time.Since(start)).
|
||||
Msg("http request served")
|
||||
|
||||
// Log response body
|
||||
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
|
||||
}
|
||||
lrr.body.UnreadByte()
|
||||
|
||||
if firstByte == '{' {
|
||||
trcLog = trcLog.RawJSON("response", lrr.body.Bytes())
|
||||
} else {
|
||||
trcLog = trcLog.Bytes("response", lrr.body.Bytes())
|
||||
}
|
||||
trcLog.Msg("response payload")
|
||||
})
|
||||
}
|
||||
|
||||
// Implement Flush to support the http.Flusher interface
|
||||
func (w *LoggingResponseWriter) Flush() {
|
||||
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *LoggingResponseWriter) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *LoggingResponseWriter) Write(b []byte) (int, error) {
|
||||
w.body.Write(b)
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func newLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter {
|
||||
return &LoggingResponseWriter{
|
||||
ResponseWriter: w, statusCode: http.StatusOK, body: bytes.NewBuffer(nil),
|
||||
}
|
||||
}
|
23
pkg/srv/http/opts/http_config.go
Normal file
23
pkg/srv/http/opts/http_config.go
Normal file
@ -0,0 +1,23 @@
|
||||
package opts
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type AppHTTP struct {
|
||||
Ctx context.Context
|
||||
Funcs []HTTPFunc
|
||||
Middleware []http.Handler
|
||||
HealthChecks []HealthCheckFunc
|
||||
CustomListener net.Listener
|
||||
HTTPDone <-chan any
|
||||
}
|
||||
|
||||
type HTTPFunc struct {
|
||||
Path string
|
||||
HandlerFunc http.HandlerFunc
|
||||
}
|
||||
|
||||
type HealthCheckFunc func(context.Context) error
|
Reference in New Issue
Block a user