/
server.go
204 lines (186 loc) · 4.76 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
package grpc
import (
"context"
"net"
"net/url"
"sync"
"time"
apimd "github.com/go-warrior/pkg/api/metadata"
ic "github.com/go-warrior/pkg/internal/context"
"github.com/go-warrior/pkg/internal/host"
"github.com/go-warrior/pkg/middleware"
"github.com/go-warrior/pkg/transport"
"github.com/go-warrior/pkg/zlog"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
grpcmd "google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection"
)
var _ transport.Server = (*Server)(nil)
var _ transport.Endpointer = (*Server)(nil)
// ServerOption is gRPC server option.
type ServerOption func(o *Server)
// Network with server network.
func Network(network string) ServerOption {
return func(s *Server) {
s.network = network
}
}
// Address with server address.
func Address(addr string) ServerOption {
return func(s *Server) {
s.address = addr
}
}
// Timeout with server timeout.
func Timeout(timeout time.Duration) ServerOption {
return func(s *Server) {
s.timeout = timeout
}
}
// Logger with server logger.
func Logger(logger zlog.Logger) ServerOption {
return func(s *Server) {
s.log = zlog.Instance()
}
}
// Middleware with server middleware.
func Middleware(m ...middleware.Middleware) ServerOption {
return func(s *Server) {
s.middleware = m
}
}
// UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the server.
func UnaryInterceptor(in ...grpc.UnaryServerInterceptor) ServerOption {
return func(s *Server) {
s.ints = in
}
}
// Options with grpc options.
func Options(opts ...grpc.ServerOption) ServerOption {
return func(s *Server) {
s.grpcOpts = opts
}
}
// Server is a gRPC server wrapper.
type Server struct {
*grpc.Server
ctx context.Context
lis net.Listener
once sync.Once
err error
network string
address string
endpoint *url.URL
timeout time.Duration
log zlog.Logger
middleware []middleware.Middleware
ints []grpc.UnaryServerInterceptor
grpcOpts []grpc.ServerOption
health *health.Server
metadata *apimd.Server
}
// NewServer creates a gRPC server by options.
func NewServer(opts ...ServerOption) *Server {
srv := &Server{
network: "tcp",
address: ":0",
timeout: 1 * time.Second,
health: health.NewServer(),
log: zlog.Instance(),
}
for _, o := range opts {
o(srv)
}
var ints = []grpc.UnaryServerInterceptor{
srv.unaryServerInterceptor(),
}
if len(srv.ints) > 0 {
ints = append(ints, srv.ints...)
}
var grpcOpts = []grpc.ServerOption{
grpc.ChainUnaryInterceptor(ints...),
}
if len(srv.grpcOpts) > 0 {
grpcOpts = append(grpcOpts, srv.grpcOpts...)
}
srv.Server = grpc.NewServer(grpcOpts...)
srv.metadata = apimd.NewServer(srv.Server)
// internal register
grpc_health_v1.RegisterHealthServer(srv.Server, srv.health)
apimd.RegisterMetadataServer(srv.Server, srv.metadata)
reflection.Register(srv.Server)
return srv
}
// Endpoint return a real address to registry endpoint.
// examples:
//
// grpc://127.0.0.1:9000?isSecure=false
func (s *Server) Endpoint() (*url.URL, error) {
s.once.Do(func() {
lis, err := net.Listen(s.network, s.address)
if err != nil {
s.err = err
return
}
addr, err := host.Extract(s.address, lis)
if err != nil {
lis.Close()
s.err = err
return
}
s.lis = lis
s.endpoint = &url.URL{Scheme: "grpc", Host: addr}
})
if s.err != nil {
return nil, s.err
}
return s.endpoint, nil
}
// Start start the gRPC server.
func (s *Server) Start(ctx context.Context) error {
if _, err := s.Endpoint(); err != nil {
return err
}
s.ctx = ctx
s.log.Infof("[gRPC] server listening on: %s", s.lis.Addr().String())
s.health.Resume()
return s.Serve(s.lis)
}
// Stop stop the gRPC server.
func (s *Server) Stop(ctx context.Context) error {
s.GracefulStop()
s.health.Shutdown()
s.log.Info("[gRPC] server stopping")
return nil
}
func (s *Server) unaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx, cancel := ic.Merge(ctx, s.ctx)
defer cancel()
md, _ := grpcmd.FromIncomingContext(ctx)
replyHeader := grpcmd.MD{}
ctx = transport.NewServerContext(ctx, &Transport{
endpoint: s.endpoint.String(),
operation: info.FullMethod,
reqHeader: headerCarrier(md),
replyHeader: headerCarrier(replyHeader),
})
if s.timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, s.timeout)
defer cancel()
}
h := func(ctx context.Context, req interface{}) (interface{}, error) {
return handler(ctx, req)
}
if len(s.middleware) > 0 {
h = middleware.Chain(s.middleware...)(h)
}
reply, err := h(ctx, req)
if len(replyHeader) > 0 {
grpc.SetHeader(ctx, replyHeader)
}
return reply, err
}
}