forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
232 lines (200 loc) · 5.95 KB
/
server.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
package server
import (
"context"
"net"
"net/http"
"sync"
"time"
"errors"
"github.com/infobloxopen/atlas-app-toolkit/gateway"
"github.com/infobloxopen/atlas-app-toolkit/health"
"google.golang.org/grpc"
)
var (
// ErrInitializeTimeout is returned when an InitializerFunc takes too long to finish during Server.Serve
ErrInitializeTimeout = errors.New("initialization timed out")
// DefaultInitializerTimeout is the reasonable default amount of time one would expect initialization to take in the
// worst case
DefaultInitializerTimeout = time.Minute
)
// Server is a wrapper struct that will allow you to stand up your GPRC server, API Gateway and health checks within
// the same struct. The recommended way to initialize this is with the NewServer function.
type Server struct {
initializers []InitializerFunc
initializeTimeout time.Duration
registrars []func(mux *http.ServeMux) error
// GRPCServer will be started whenever this is served
GRPCServer *grpc.Server
// HTTPServer will be started whenever this is served
HTTPServer *http.Server
}
// Option is a functional option for creating a Server
type Option func(*Server) error
// InitializerFunc is a handler that can be passed into WithInitializer to be executed prior to serving
type InitializerFunc func(context.Context) error
// NewServer creates a Server from the given options. All options are processed in the order they are declared.
func NewServer(opts ...Option) (*Server, error) {
s := &Server{
initializeTimeout: DefaultInitializerTimeout,
HTTPServer: &http.Server{},
registrars: []func(mux *http.ServeMux) error{},
}
for _, opt := range opts {
if err := opt(s); err != nil {
return nil, err
}
}
mux := http.NewServeMux()
for _, register := range s.registrars {
if err := register(mux); err != nil {
return nil, err
}
}
s.HTTPServer.Handler = mux
return s, nil
}
// WithInitializerTimeout set the duration initialization will wait before halting and returning an error
func WithInitializerTimeout(timeout time.Duration) Option {
return func(s *Server) error {
s.initializeTimeout = timeout
return nil
}
}
// WithInitializer adds an initialization function that will get called prior to serving.
func WithInitializer(initializerFunc InitializerFunc) Option {
return func(s *Server) error {
s.initializers = append(s.initializers, initializerFunc)
return nil
}
}
// WithGrpcServer adds the given GRPC server to this server. There can only be one GRPC server within a given instance,
// so multiple calls with this option will overwrite the previous ones.
func WithGrpcServer(grpcServer *grpc.Server) Option {
return func(s *Server) error {
s.GRPCServer = grpcServer
return nil
}
}
// WithHandler registers the given http handler to this server by registering the pattern at the root of the http server
func WithHandler(pattern string, handler http.Handler) Option {
return func(s *Server) error {
s.registrars = append(s.registrars, func(mux *http.ServeMux) error {
mux.Handle(pattern, handler)
return nil
})
return nil
}
}
// WithHealthChecks registers the given health checker with this server by registering its endpoints at the root of the
// http server.
func WithHealthChecks(checker health.Checker) Option {
return func(s *Server) error {
s.registrars = append(s.registrars, func(mux *http.ServeMux) error {
checker.RegisterHandler(mux)
return nil
})
return nil
}
}
// WithGateway registers the given gateway options with this server
func WithGateway(options ...gateway.Option) Option {
return func(s *Server) error {
s.registrars = append(s.registrars, func(mux *http.ServeMux) error {
_, err := gateway.NewGateway(append(options, gateway.WithMux(mux))...)
return err
})
return nil
}
}
// Serve invokes all initializers then serves on the given listeners.
//
// If a listener is left blank, then that particular part will not be served.
//
// If a listener is specified for a part that doesn't have a corresponding server, then an error will be returned. This
// can happen, for instance, whenever a gRPC listener is provided but no gRPC server was set or no option was passed
// into NewServer.
//
// If both listeners are nil, then an error is returned
func (s *Server) Serve(grpcL, httpL net.Listener) error {
if grpcL == nil && httpL == nil {
return errors.New("both grpcL and httpL are nil")
}
if err := s.initialize(); err != nil {
return err
}
errC := make(chan error)
if httpL != nil {
if s.HTTPServer == nil {
return errors.New("httpL is specified, but no HTTPServer is provided")
}
go func() { errC <- s.HTTPServer.Serve(httpL) }()
} else {
s.HTTPServer = nil
}
if grpcL != nil {
if s.GRPCServer == nil {
return errors.New("grpcL is specified, but no GRPCServer is provided")
}
go func() { errC <- s.GRPCServer.Serve(grpcL) }()
} else {
s.GRPCServer = nil
}
defer s.Stop()
return <-errC
}
// Stop immediately terminates the grpc and http servers, immediately closing their active listeners
func (s *Server) Stop() error {
wg := sync.WaitGroup{}
wg.Add(2)
doneC := make(chan bool)
errC := make(chan error)
go func() {
defer wg.Done()
if s.GRPCServer != nil {
s.GRPCServer.Stop()
}
}()
go func() {
defer wg.Done()
if s.HTTPServer != nil {
if err := s.HTTPServer.Close(); err != nil {
errC <- err
}
}
}()
go func() {
wg.Wait()
doneC <- true
}()
select {
case err := <-errC:
return err
case <-doneC:
return nil
}
}
func (s Server) initialize() error {
ctx, cancel := context.WithTimeout(context.Background(), s.initializeTimeout)
defer cancel()
errC := make(chan error)
wg := sync.WaitGroup{}
wg.Add(len(s.initializers))
go func() {
wg.Wait()
errC <- nil
}()
for _, initFunc := range s.initializers {
go func(init InitializerFunc) {
defer wg.Done()
if err := init(ctx); err != nil {
errC <- err
}
}(initFunc)
}
select {
case err := <-errC:
return err
case <-time.After(s.initializeTimeout):
return ErrInitializeTimeout
}
}