-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
360 lines (319 loc) · 8.93 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package http
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"sync"
"time"
"github.com/andrescosta/goico/pkg/env"
"github.com/andrescosta/goico/pkg/option"
"github.com/andrescosta/goico/pkg/service"
"github.com/andrescosta/goico/pkg/service/obs"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
)
const Kind = service.HTTP
type Service struct {
base *service.Base
server *http.Server
healthCheckFunc HealthCheckFn
pool *sync.Pool
imsidecar bool
Listener service.HTTPListener
}
type healthStatus struct {
Status string `json:"status"`
Details map[string]string `json:"details"`
}
type (
initRoutesFn = func(context.Context, *mux.Router) error
HealthCheckFn = func(context.Context) (map[string]string, error)
)
type SidecarOptions struct {
common *commonOptions
base *service.Base
disableOtel bool
}
type httpOptions interface {
*ServiceOptions | *SidecarOptions
}
type Option[T httpOptions] interface {
Apply(T)
}
type ServiceOptions struct {
addr string
common *commonOptions
ctx context.Context
name string
profilingEnabled bool
}
type commonOptions struct {
healthChkFn HealthCheckFn
stackLevelOnError StackLevel
listener service.HTTPListener
initRoutesFn initRoutesFn
}
func New(opts ...Option[*ServiceOptions]) (*Service, error) {
svc := &Service{}
setDefaults(svc)
opt := &ServiceOptions{
common: &commonOptions{
stackLevelOnError: StackLevelSimple,
listener: service.DefaultHTTPListener,
initRoutesFn: func(_ context.Context, _ *mux.Router) error { return nil },
},
ctx: context.Background(),
addr: "",
name: "",
}
for _, o := range opts {
o.Apply(opt)
}
//
base, err := service.New(
service.WithName(opt.name),
service.WithAddr(opt.addr),
service.WithContext(opt.ctx),
service.WithKind("rest"),
)
if err != nil {
return nil, err
}
svc.base = base
svc.Listener = opt.common.listener
// Mux Router initialization
router := svc.initializeRouter(opt)
//// routes initialization
if err := opt.common.initRoutesFn(svc.base.Ctx, router); err != nil {
return nil, err
}
return svc, nil
}
func NewSidecar(opts ...Option[*SidecarOptions]) (*Service, error) {
svc := &Service{}
setDefaults(svc)
opt := &SidecarOptions{
common: &commonOptions{
stackLevelOnError: StackLevelSimple,
listener: service.DefaultHTTPListener,
initRoutesFn: func(_ context.Context, _ *mux.Router) error { return nil },
},
base: nil,
}
for _, o := range opts {
o.Apply(opt)
}
svc.base = opt.base
svc.imsidecar = true
svc.Listener = opt.common.listener
// Mux Router initialization
router := svc.initializeRouterSidecar(*opt)
//// routes initialization
if err := opt.common.initRoutesFn(svc.base.Ctx, router); err != nil {
return nil, err
}
return svc, nil
}
func (s *Service) Serve() error {
listener, err := s.Listener.Listen(s.base.Addr)
if err != nil {
return err
}
return s.DoServe(listener)
}
func (s *Service) DoServe(listener net.Listener) error {
defer s.base.Stopped()
logger := zerolog.Ctx(s.base.Ctx)
logger.Info().Msgf("Starting process %d ", os.Getpid())
s.server.BaseContext = func(_ net.Listener) context.Context { return s.base.Ctx }
errCh := make(chan error, 1)
go func() {
<-s.base.Ctx.Done()
logger.Debug().Msg("HTTP service: context closed")
shutdownCtx, done := context.WithTimeout(context.Background(),
*env.Duration("http.shutdown.timeout", time.Second*5))
defer done()
logger.Debug().Msg("HTTP service: shutting down")
errCh <- s.server.Shutdown(shutdownCtx)
}()
logger.Debug().Msgf("HTTP service: started on %s", listener.Addr().String())
if !s.imsidecar {
s.base.SetStartedNow()
}
if err := s.server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("http.Serve: failed to serve: %w", err)
}
logger.Debug().Msg("HTTP service: serving stopped")
if err := <-errCh; err != nil {
return fmt.Errorf("http.Shutdown: failed to shutdown server: %w", err)
}
logger.Info().Msgf("Process %d ended ", os.Getpid())
return nil
}
func (s *Service) healthCheckHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/JSON")
status := &healthStatus{}
m, err := s.healthCheckFunc(r.Context())
status.Details = m
var statusCode int
if err != nil {
status.Status = "error"
statusCode = http.StatusInternalServerError
} else {
status.Status = "alive"
statusCode = http.StatusOK
}
b := s.pool.Get().(*bytes.Buffer)
b.Reset()
WriteJSONBody(b, status, statusCode, `{error:"error getting health check status"}`, w)
}
func (s *Service) metadataHandler(w http.ResponseWriter, _ *http.Request) {
b := s.pool.Get().(*bytes.Buffer)
b.Reset()
WriteJSONBody(b, s.base.Metadata(), http.StatusOK, `{error:"error getting metadata"}`, w)
}
func (s *Service) initializeRouter(opts *ServiceOptions) (router *mux.Router) {
// Mux Router config
router = mux.NewRouter()
//// setting middlewares
rf := RecoveryFunc{StackLevel: opts.common.stackLevelOnError}
router.Use(rf.TryToRecover())
router.Use(obs.GetLoggingMiddleware)
s.base.OtelProvider.InstrRouter(s.base.Name(), router)
if env.Bool("metadata.enabled", false) {
router.HandleFunc("/meta", s.metadataHandler)
}
if opts.common.healthChkFn != nil {
s.healthCheckFunc = opts.common.healthChkFn
router.HandleFunc("/health", s.healthCheckHandler)
}
if opts.profilingEnabled {
service.AttachProfilingHandlers(router)
}
s.server = newHTTPServer(router)
return
}
func (s *Service) initializeRouterSidecar(opt SidecarOptions) (router *mux.Router) {
// Mux Router config
router = mux.NewRouter()
//// setting middlewares
rf := RecoveryFunc{StackLevel: opt.common.stackLevelOnError}
router.Use(rf.TryToRecover())
router.Use(obs.GetLoggingMiddleware)
if !opt.disableOtel {
s.base.OtelProvider.InstrRouter(s.base.Name(), router)
}
if env.Bool("metadata.enabled.sidecar", false) {
router.HandleFunc("/meta", s.metadataHandler)
}
if opt.common.healthChkFn != nil {
s.healthCheckFunc = opt.common.healthChkFn
router.HandleFunc("/health", s.healthCheckHandler)
}
s.server = newHTTPServer(router)
return
}
func (s *Service) HelthCheckClient(c service.HTTPClientBuilder) *HealthCheckClient {
return &HealthCheckClient{
ServerAddr: s.base.Addr,
Builder: c,
}
}
func newHTTPServer(r http.Handler) *http.Server {
return &http.Server{
WriteTimeout: *env.Duration("http.timeout.write", time.Second*20),
ReadTimeout: *env.Duration("http.timeout.read", time.Second*20),
IdleTimeout: *env.Duration("http.timeout.idle", time.Second*20),
Handler: http.TimeoutHandler(r, *env.Duration("http.timeout.handler", 20*time.Second), ""),
}
}
func setDefaults(s *Service) {
s.pool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 1024))
},
}
}
// Setters
func WithInitRoutesFn[T *SidecarOptions | *ServiceOptions](i initRoutesFn) Option[T] {
return option.NewFuncOption(func(t T) {
if t != nil {
switch v := any(t).(type) {
case *SidecarOptions:
v.common.initRoutesFn = i
case *ServiceOptions:
v.common.initRoutesFn = i
}
}
})
}
func WithAddr(a string) Option[*ServiceOptions] {
return option.NewFuncOption(func(s *ServiceOptions) {
s.addr = a
})
}
func WithName(n string) Option[*ServiceOptions] {
return option.NewFuncOption(func(s *ServiceOptions) {
s.name = n
})
}
func WithContext(ctx context.Context) Option[*ServiceOptions] {
return option.NewFuncOption(func(s *ServiceOptions) {
s.ctx = ctx
})
}
func WithStackLevelOnError[T *SidecarOptions | *ServiceOptions](lvl StackLevel) Option[T] {
return option.NewFuncOption(func(t T) {
if t != nil {
switch v := any(t).(type) {
case *SidecarOptions:
v.common.stackLevelOnError = lvl
case *ServiceOptions:
v.common.stackLevelOnError = lvl
}
}
})
}
func WithHealthCheckFn[T *SidecarOptions | *ServiceOptions](healthChkFn HealthCheckFn) Option[T] {
return option.NewFuncOption(func(t T) {
if t != nil {
switch v := any(t).(type) {
case *SidecarOptions:
v.common.healthChkFn = healthChkFn
case *ServiceOptions:
v.common.healthChkFn = healthChkFn
}
}
})
}
func WithListener[T *SidecarOptions | *ServiceOptions](listener service.HTTPListener) Option[T] {
return option.NewFuncOption(func(t T) {
if t != nil && listener != nil {
switch v := any(t).(type) {
case *SidecarOptions:
v.common.listener = listener
case *ServiceOptions:
v.common.listener = listener
}
}
})
}
func WithPrimaryService(svc *service.Base) Option[*SidecarOptions] {
return option.NewFuncOption(func(opts *SidecarOptions) {
opts.base = svc
})
}
func WithDisableOtel(otel bool) Option[*SidecarOptions] {
return option.NewFuncOption(func(opts *SidecarOptions) {
opts.disableOtel = otel
})
}
func WithProfilingEnabled(p bool) Option[*ServiceOptions] {
return option.NewFuncOption(func(s *ServiceOptions) {
s.profilingEnabled = p
})
}