/
grpc.go
222 lines (184 loc) · 5.49 KB
/
grpc.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
package grpc
import (
"context"
"fmt"
"net"
"net/http"
"time"
"github.com/rs/cors"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"github.com/FleekHQ/space-daemon/core/keychain"
"github.com/FleekHQ/space-daemon/core/space/fuse"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/FleekHQ/space-daemon/core/space"
"github.com/FleekHQ/space-daemon/grpc/auth/app_token_auth"
grpc_auth "github.com/FleekHQ/space-daemon/grpc/auth/middleware"
"github.com/FleekHQ/space-daemon/grpc/pb"
"github.com/FleekHQ/space-daemon/log"
"google.golang.org/grpc"
)
const (
DefaultGrpcPort = 9999
)
var defaultServerOptions = serverOptions{
port: DefaultGrpcPort,
}
type serverOptions struct {
port int
proxyPort int // port for grpcweb proxy
restProxyPort int // port for rest api proxy
}
type grpcServer struct {
opts *serverOptions
s *grpc.Server
rpcProxy *http.Server
restServer *http.Server
sv space.Service
fc *fuse.Controller
kc keychain.Keychain
// TODO: see if we need to clean this up by gc or handle an array
fileEventStream pb.SpaceApi_SubscribeServer
txlEventStream pb.SpaceApi_TxlSubscribeServer
notificationEventStream pb.SpaceApi_NotificationSubscribeServer
isStarted bool
readyCh chan bool
}
// Idea taken from here https://medium.com/soon-london/variadic-configuration-functions-in-go-8cef1c97ce99
type ServerOption func(o *serverOptions)
// gRPC server uses Service from core to handle requests
func New(sv space.Service, fc *fuse.Controller, kc keychain.Keychain, opts ...ServerOption) *grpcServer {
o := defaultServerOptions
for _, opt := range opts {
opt(&o)
}
srv := &grpcServer{
opts: &o,
sv: sv,
fc: fc,
kc: kc,
readyCh: make(chan bool, 1),
}
return srv
}
// Start grpc and api server with provided options
func (srv *grpcServer) Start(ctx context.Context) error {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", srv.opts.port))
if err != nil {
log.Error(fmt.Sprintf("failed to listen on port : %v", srv.opts.port), err)
return err
}
log.Info(fmt.Sprintf("listening on address %s", lis.Addr().String()))
appTokenAuth := app_token_auth.New(srv.kc)
srv.s = grpc.NewServer(
grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(appTokenAuth.Authorize)),
grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(appTokenAuth.Authorize)),
)
pb.RegisterSpaceApiServer(srv.s, srv)
if err = srv.startRestProxy(ctx, lis); err != nil {
return err
}
srv.startGrpcWebProxy()
log.Info(fmt.Sprintf("gRPC server started on Port %v", srv.opts.port))
srv.isStarted = true
srv.readyCh <- true
// this is a blocking function
return srv.s.Serve(lis)
}
func (srv *grpcServer) startRestProxy(ctx context.Context, lis net.Listener) error {
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()}
if err := pb.RegisterSpaceApiHandlerFromEndpoint(ctx, mux, lis.Addr().String(), opts); err != nil {
log.Error("Failed to start REST server", err)
return err
}
srv.restServer = &http.Server{
Addr: fmt.Sprintf(":%d", srv.opts.restProxyPort),
Handler: mux,
}
srv.restServer.Handler = cors.AllowAll().Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Debug("Incoming REST Proxy Request", "path:"+r.URL.Path, "method:"+r.Method)
mux.ServeHTTP(w, r)
}))
log.Info("REST server is starting", fmt.Sprintf("port:%v", srv.opts.restProxyPort))
go func() {
if err := srv.restServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error(fmt.Sprintf("REST server failed to start on port %d", srv.opts.restProxyPort), err)
}
}()
return nil
}
func (srv *grpcServer) startGrpcWebProxy() {
webrpcProxy := grpcweb.WrapServer(
srv.s,
grpcweb.WithOriginFunc(func(origin string) bool {
return true
}),
grpcweb.WithWebsockets(true),
grpcweb.WithWebsocketOriginFunc(func(req *http.Request) bool {
return true
}),
)
srv.rpcProxy = &http.Server{
Addr: fmt.Sprintf(":%d", srv.opts.proxyPort),
}
srv.rpcProxy.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if webrpcProxy.IsGrpcWebRequest(r) ||
webrpcProxy.IsAcceptableGrpcCorsRequest(r) ||
webrpcProxy.IsGrpcWebSocketRequest(r) {
webrpcProxy.ServeHTTP(w, r)
}
})
go func() {
if err := srv.rpcProxy.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error("Space grpcweb proxy error", err)
}
}()
log.Info(fmt.Sprintf("gRPC-web proxy server started on Port %d", srv.opts.proxyPort))
}
// Helper function for setting port
func WithPort(port int) ServerOption {
return func(o *serverOptions) {
if port != 0 {
o.port = port
}
}
}
func WithProxyPort(port int) ServerOption {
return func(o *serverOptions) {
if port != 0 {
o.proxyPort = port
}
}
}
// WithRestProxyPort configures the REST Proxy port
func WithRestProxyPort(port int) ServerOption {
return func(o *serverOptions) {
if port != 0 {
o.restProxyPort = port
}
}
}
func (srv *grpcServer) Shutdown() error {
if !srv.isStarted {
return nil
}
close(srv.readyCh)
defer func() {
srv.rpcProxy = nil
srv.restServer = nil
srv.s = nil
srv.isStarted = false
}()
srv.s.GracefulStop()
shutdownCtx, _ := context.WithTimeout(context.Background(), 10*time.Second)
if err := srv.rpcProxy.Shutdown(shutdownCtx); err != nil {
return err
}
if err := srv.restServer.Shutdown(shutdownCtx); err != nil {
return err
}
return nil
}
func (srv *grpcServer) WaitForReady() chan bool {
return srv.readyCh
}