-
Notifications
You must be signed in to change notification settings - Fork 69
/
server.go
168 lines (139 loc) · 4.71 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
package server
import (
"context"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/0xPolygonHermez/zkevm-bridge-service/bridgectrl/pb"
"github.com/0xPolygonHermez/zkevm-bridge-service/log"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/protobuf/encoding/protojson"
)
// RunServer runs gRPC server and HTTP gateway
func RunServer(cfg Config, bridgeService pb.BridgeServiceServer) error {
ctx := context.Background()
if len(cfg.GRPCPort) == 0 {
return fmt.Errorf("invalid TCP port for gRPC server: '%s'", cfg.GRPCPort)
}
if len(cfg.HTTPPort) == 0 {
return fmt.Errorf("invalid TCP port for HTTP gateway: '%s'", cfg.HTTPPort)
}
go func() {
_ = runRestServer(ctx, cfg.GRPCPort, cfg.HTTPPort)
}()
go func() {
_ = runGRPCServer(ctx, bridgeService, cfg.GRPCPort)
}()
return nil
}
// HealthChecker will provide an implementation of the HealthCheck interface.
type healthChecker struct{}
// NewHealthChecker returns a health checker according to standard package
// grpc.health.v1.
func newHealthChecker() *healthChecker {
return &healthChecker{}
}
// HealthCheck interface implementation.
// Check returns the current status of the server for unary gRPC health requests,
// for now if the server is up and able to respond we will always return SERVING.
func (s *healthChecker) Check(ctx context.Context, req *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
return &grpc_health_v1.HealthCheckResponse{
Status: grpc_health_v1.HealthCheckResponse_SERVING,
}, nil
}
// Watch returns the current status of the server for stream gRPC health requests,
// for now if the server is up and able to respond we will always return SERVING.
func (s *healthChecker) Watch(req *grpc_health_v1.HealthCheckRequest, server grpc_health_v1.Health_WatchServer) error {
return server.Send(&grpc_health_v1.HealthCheckResponse{
Status: grpc_health_v1.HealthCheckResponse_SERVING,
})
}
func runGRPCServer(ctx context.Context, bridgeServer pb.BridgeServiceServer, port string) error {
listen, err := net.Listen("tcp", ":"+port)
if err != nil {
return err
}
server := grpc.NewServer()
pb.RegisterBridgeServiceServer(server, bridgeServer)
healthService := newHealthChecker()
grpc_health_v1.RegisterHealthServer(server, healthService)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
server.GracefulStop()
<-ctx.Done()
}
}()
log.Info("gRPC Server is serving at ", port)
return server.Serve(listen)
}
func preflightHandler(w http.ResponseWriter, r *http.Request) {
headers := []string{"Content-Type", "Accept"}
w.Header().Set("Access-Control-Allow-Headers", strings.Join(headers, ","))
methods := []string{"GET", "HEAD", "POST", "PUT", "DELETE"}
w.Header().Set("Access-Control-Allow-Methods", strings.Join(methods, ","))
}
// allowCORS allows Cross Origin Resource Sharing from any origin.
// Don't do this without consideration in production systems.
func allowCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
preflightHandler(w, r)
return
}
}
h.ServeHTTP(w, r)
})
}
func runRestServer(ctx context.Context, grpcPort, httpPort string) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
endpoint := "localhost:" + grpcPort
conn, err := grpc.NewClient(endpoint, opts...)
if err != nil {
return err
}
muxHealthOpt := runtime.WithHealthzEndpoint(grpc_health_v1.NewHealthClient(conn))
muxJSONOpt := runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
UseProtoNames: true,
EmitUnpopulated: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
})
mux := runtime.NewServeMux(muxJSONOpt, muxHealthOpt)
if err := pb.RegisterBridgeServiceHandler(ctx, mux, conn); err != nil {
return err
}
srv := &http.Server{
ReadTimeout: 1 * time.Second, //nolint:gomnd
Addr: ":" + httpPort,
Handler: allowCORS(mux),
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
_ = srv.Shutdown(ctx)
<-ctx.Done()
}
_, cancel := context.WithTimeout(ctx, 5*time.Second) //nolint:gomnd
defer cancel()
_ = srv.Shutdown(ctx)
}()
log.Info("Restful Server is serving at ", httpPort)
return srv.ListenAndServe()
}