-
Notifications
You must be signed in to change notification settings - Fork 19
/
app.go
201 lines (173 loc) · 4.75 KB
/
app.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
package main
import (
"context"
"fmt"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/go-chi/chi/middleware"
grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpczap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
grpcrecovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpcctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/cosmology-tech/starship/registry/registry"
)
type AppServer struct {
pb.UnimplementedRegistryServer
config *Config
logger *zap.Logger
// clients for various chains
chainClients ChainClients
grpcServer *grpc.Server
httpServer *http.Server
}
func NewAppServer(config *Config) (*AppServer, error) {
log, err := NewLogger(config)
if err != nil {
return nil, err
}
log.Info(
"Starting the service",
zap.String("prog", Prog),
zap.String("version", Version),
zap.Any("config", config),
)
chainClients, err := NewChainClients(
log,
strings.Split(config.ChainClientIDs, ","),
strings.Split(config.ChainClientRPCs, ","),
strings.Split(config.ChainClientExposers, ","),
os.Getenv("HOME"),
)
if err != nil {
return nil, err
}
app := &AppServer{
config: config,
logger: log,
chainClients: chainClients,
}
// Validate config
err = app.ValidateConfig()
if err != nil {
return nil, err
}
// Create grpc server
grpcServer := grpc.NewServer(app.grpcMiddleware()...)
pb.RegisterRegistryServer(grpcServer, app)
app.grpcServer = grpcServer
// Create http server
mux := runtime.NewServeMux()
err = pb.RegisterRegistryHandlerFromEndpoint(
context.Background(),
mux,
fmt.Sprintf("%s:%s", config.Host, config.GRPCPort),
[]grpc.DialOption{grpc.WithInsecure()},
)
if err != nil {
return nil, err
}
httpServer := &http.Server{
Addr: fmt.Sprintf("%s:%s", config.Host, config.HTTPPort),
Handler: app.panicRecovery(app.loggingMiddleware(mux)),
}
app.httpServer = httpServer
return app, err
}
func (a *AppServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.httpServer.Handler.ServeHTTP(w, r)
}
func (a *AppServer) ValidateConfig() error {
// Verify chain ids and chain registry information
err := verifyChainIDs(a.config)
if err != nil {
return err
}
return nil
}
func (a *AppServer) grpcMiddleware() []grpc.ServerOption {
opts := []grpcrecovery.Option{
grpcrecovery.WithRecoveryHandler(
func(p interface{}) error {
err := status.Errorf(codes.Unknown, "panic triggered: %v", p)
a.logger.Error("panic error", zap.Error(err))
return err
},
),
}
serverOpts := []grpc.ServerOption{
grpcmiddleware.WithUnaryServerChain(
grpcctxtags.UnaryServerInterceptor(),
grpczap.UnaryServerInterceptor(a.logger),
grpcrecovery.UnaryServerInterceptor(opts...),
),
grpcmiddleware.WithStreamServerChain(
grpcctxtags.StreamServerInterceptor(),
grpczap.StreamServerInterceptor(a.logger),
grpcrecovery.StreamServerInterceptor(opts...),
),
}
return serverOpts
}
func (a *AppServer) loggingMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
start := time.Now()
defer func() {
a.logger.Info("client request",
zap.Duration("latency", time.Since(start)),
zap.Int("status", ww.Status()),
zap.Int("bytes", ww.BytesWritten()),
zap.String("client_ip", r.RemoteAddr),
zap.String("method", r.Method),
zap.String("path", r.URL.Path),
zap.String("request-id", middleware.GetReqID(r.Context())))
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
func (a *AppServer) panicRecovery(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rc := recover(); rc != nil {
err, ok := rc.(error)
if !ok {
err = fmt.Errorf("panic: %v", rc)
}
a.logger.Error("panic error", zap.Error(err))
http.Error(w, ErrInternalServer.Error(), 500)
return
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func (a *AppServer) Run() error {
a.logger.Info("App starting", zap.Any("Config", a.config))
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%s", a.config.Host, a.config.GRPCPort))
if err != nil {
a.logger.Error("failed to listen", zap.Error(err))
}
// Start grpc server as long-running go routine
go func() {
if err := a.grpcServer.Serve(lis); err != nil {
a.logger.Error("failed to start the App gRPC server", zap.Error(err))
}
}()
// Start http server
go func() {
if err := a.httpServer.ListenAndServe(); err != nil {
a.logger.Error("failed to start the App http server", zap.Error(err))
}
}()
return nil
}