-
Notifications
You must be signed in to change notification settings - Fork 23
/
server.go
332 lines (307 loc) · 9.78 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
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
package pwapi
import (
"context"
"fmt"
"log"
"net"
"net/http"
"net/http/pprof"
"runtime/debug"
"strings"
"time"
sentryhttp "github.com/getsentry/sentry-go/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/gogo/gateway"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/oklog/run"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/rs/cors"
"github.com/soheilhy/cmux"
chilogger "github.com/treastech/logger"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"pathwar.land/pathwar/v2/go/pkg/errcode"
)
func NewServer(ctx context.Context, svc ServiceServer, opts ServerOpts) (*Server, error) {
opts.applyDefaults()
ctx, cancel := context.WithCancel(ctx)
s := Server{
logger: opts.Logger,
ctx: ctx,
cancel: cancel,
}
// listener
var err error
s.masterListener, err = net.Listen("tcp", opts.Bind)
if err != nil {
return nil, errcode.ErrServerListen.Wrap(err)
}
s.cmux = cmux.New(s.masterListener)
s.grpcListener = s.cmux.MatchWithWriters(cmux.HTTP2MatchHeaderFieldPrefixSendSettings("content-type", "application/grpc"))
s.httpListener = s.cmux.Match(cmux.HTTP2(), cmux.HTTP1())
// FIXME: add gRPC web support
// FIXME: websocket
// grpc server
s.grpcServer = grpcServer(svc, opts)
s.workers.Add(func() error {
err := s.grpcServer.Serve(s.grpcListener)
if err != cmux.ErrListenerClosed {
return err
}
return nil
}, func(error) {
if err := s.grpcListener.Close(); err != nil {
opts.Logger.Warn("close listener", zap.Error(err))
}
})
// http server
httpServer, err := httpServer(ctx, s.ListenerAddr(), opts)
if err != nil {
return nil, errcode.TODO.Wrap(err)
}
s.workers.Add(func() error {
err := httpServer.Serve(s.httpListener)
if err != cmux.ErrListenerClosed {
return err
}
return nil
}, func(error) {
ctx, cancel := context.WithTimeout(ctx, opts.ShutdownTimeout)
if err := httpServer.Shutdown(ctx); err != nil {
opts.Logger.Warn("shutdown HTTP server", zap.Error(err))
}
defer cancel()
if err := s.httpListener.Close(); err != nil {
opts.Logger.Warn("close listener", zap.Error(err))
}
})
s.cmux.HandleError(func(err error) bool {
s.logger.Warn("cmux error", zap.Error(err))
return true
})
// mux
s.workers.Add(
func() error {
err := s.cmux.Serve()
return err
},
func(err error) {
fmt.Println(err)
},
)
// listen for canceled context
s.workers.Add(func() error {
<-s.ctx.Done()
return nil
}, func(error) {})
return &s, nil
}
// Server is an HTTP+gRPC frontend for Service
type Server struct {
grpcServer *grpc.Server
masterListener net.Listener
grpcListener net.Listener
httpListener net.Listener
cmux cmux.CMux
logger *zap.Logger
workers run.Group
ctx context.Context
cancel func()
}
func NewServerOpts() ServerOpts {
opts := ServerOpts{}
opts.applyDefaults()
return opts
}
type ServerOpts struct {
Logger *zap.Logger
Bind string
CORSAllowedOrigins string
RequestTimeout time.Duration
ShutdownTimeout time.Duration
WithPprof bool
Tracer opentracing.Tracer
}
func (opts *ServerOpts) applyDefaults() {
if opts.Logger == nil {
opts.Logger = zap.NewNop()
}
if opts.CORSAllowedOrigins == "" {
opts.CORSAllowedOrigins = "*"
}
if opts.Bind == "" {
opts.Bind = ":0"
}
if opts.RequestTimeout == 0 {
opts.RequestTimeout = 5 * time.Second
}
if opts.ShutdownTimeout == 0 {
opts.ShutdownTimeout = 6 * time.Second
}
}
func (s *Server) Run() error {
return s.workers.Run()
}
func (s *Server) Close() {
// go s.grpcServer.GracefulStop()
// time.Sleep(time.Second)
// s.grpcServer.Stop()
if s.masterListener != nil {
s.masterListener.Close()
}
s.cancel()
}
func (s *Server) ListenerAddr() string {
return s.masterListener.Addr().String()
}
func grpcServer(svc ServiceServer, opts ServerOpts) *grpc.Server {
logger := opts.Logger.Named("grpc")
authFunc := func(context.Context) (context.Context, error) {
return nil, errcode.ErrNotImplemented
}
recoveryOpts := []grpc_recovery.Option{}
if opts.Logger.Check(zap.DebugLevel, "") != nil {
recoveryOpts = append(recoveryOpts, grpc_recovery.WithRecoveryHandlerContext(func(ctx context.Context, p interface{}) error {
log.Println("stacktrace from panic: \n" + string(debug.Stack()))
return status.Errorf(codes.Internal, "recover: %s", p)
}))
}
serverStreamOpts := []grpc.StreamServerInterceptor{grpc_recovery.StreamServerInterceptor(recoveryOpts...)}
serverUnaryOpts := []grpc.UnaryServerInterceptor{grpc_recovery.UnaryServerInterceptor(recoveryOpts...)}
if opts.Tracer != nil {
tracingOpts := []grpc_opentracing.Option{grpc_opentracing.WithTracer(opts.Tracer)}
serverStreamOpts = append(serverStreamOpts, grpc_opentracing.StreamServerInterceptor(tracingOpts...))
serverUnaryOpts = append(serverUnaryOpts, grpc_opentracing.UnaryServerInterceptor(tracingOpts...))
}
serverStreamOpts = append(serverStreamOpts,
grpc_auth.StreamServerInterceptor(authFunc),
// grpc_ctxtags.StreamServerInterceptor(),
grpc_zap.StreamServerInterceptor(logger),
)
serverUnaryOpts = append(
serverUnaryOpts,
grpc_auth.UnaryServerInterceptor(authFunc),
// grpc_ctxtags.UnaryServerInterceptor(),
grpc_zap.UnaryServerInterceptor(logger),
)
if opts.Logger.Check(zap.DebugLevel, "") != nil {
serverStreamOpts = append(serverStreamOpts, grpcServerStreamInterceptor())
serverUnaryOpts = append(serverUnaryOpts, grpcServerUnaryInterceptor())
}
serverStreamOpts = append(serverStreamOpts, grpc_recovery.StreamServerInterceptor(recoveryOpts...))
serverUnaryOpts = append(serverUnaryOpts, grpc_recovery.UnaryServerInterceptor(recoveryOpts...))
grpcServer := grpc.NewServer(
grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(serverStreamOpts...)),
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(serverUnaryOpts...)),
)
RegisterServiceServer(grpcServer, svc)
return grpcServer
}
func grpcServerStreamInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
err := handler(srv, stream)
if err != nil {
log.Printf("%+v", err)
}
return err
}
}
func grpcServerUnaryInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ret, err := handler(ctx, req)
if err != nil {
log.Printf("%+v", err)
}
return ret, err
}
}
func httpServer(ctx context.Context, serverListenerAddr string, opts ServerOpts) (*http.Server, error) {
logger := opts.Logger.Named("http")
r := chi.NewRouter()
cors := cors.New(cors.Options{
AllowedOrigins: strings.Split(opts.CORSAllowedOrigins, ","),
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300,
})
r.Use(cors.Handler)
r.Use(chilogger.Logger(logger))
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(opts.RequestTimeout))
r.Use(middleware.RealIP)
r.Use(middleware.RequestID)
sentryMiddleware := sentryhttp.New(sentryhttp.Options{
Repanic: true,
})
r.Use(sentryMiddleware.Handle)
runtimeMux := runtime.NewServeMux(
runtime.WithMarshalerOption(runtime.MIMEWildcard, &gateway.JSONPb{
EmitDefaults: false,
Indent: " ",
OrigName: true,
}),
runtime.WithProtoErrorHandler(runtime.DefaultHTTPProtoErrorHandler),
runtime.WithIncomingHeaderMatcher(incomingHeaderMatcherFunc),
)
var gwmux http.Handler = runtimeMux
dialOpts := []grpc.DialOption{grpc.WithInsecure()}
if opts.Tracer != nil {
var grpcGatewayTag = opentracing.Tag{Key: string(ext.Component), Value: "grpc-gateway"}
tracingWrapper := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
parentSpanContext, err := opts.Tracer.Extract(
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(r.Header),
)
if err == nil || err == opentracing.ErrSpanContextNotFound {
serverSpan := opts.Tracer.StartSpan(
"ServeHTTP",
ext.RPCServerOption(parentSpanContext),
grpcGatewayTag,
)
r = r.WithContext(opentracing.ContextWithSpan(r.Context(), serverSpan))
defer serverSpan.Finish()
}
// fmt.Println(r.Context())
h.ServeHTTP(w, r)
})
}
gwmux = tracingWrapper(gwmux)
dialOpts = append(dialOpts,
grpc.WithStreamInterceptor(
grpc_opentracing.StreamClientInterceptor(
grpc_opentracing.WithTracer(opts.Tracer))),
grpc.WithUnaryInterceptor(
grpc_opentracing.UnaryClientInterceptor(
grpc_opentracing.WithTracer(opts.Tracer))),
)
}
err := RegisterServiceHandlerFromEndpoint(ctx, runtimeMux, serverListenerAddr, dialOpts)
if err != nil {
return nil, errcode.ErrServerRegisterGateway.Wrap(err)
}
r.Mount("/", gwmux)
if opts.WithPprof {
r.HandleFunc("/debug/pprof/*", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
http.DefaultServeMux = http.NewServeMux() // disables default handlers registered by importing net/http/pprof for security reasons
return &http.Server{
Addr: opts.Bind,
Handler: r,
}, nil
}