-
Notifications
You must be signed in to change notification settings - Fork 126
/
server.go
288 lines (234 loc) · 7.08 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
package grpc
import (
"context"
"crypto/tls"
"fmt"
"net"
"runtime/debug"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery"
"github.com/rs/zerolog"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/status"
"github.com/hatchet-dev/hatchet/internal/config/server"
"github.com/hatchet-dev/hatchet/internal/logger"
"github.com/hatchet-dev/hatchet/internal/services/admin"
admincontracts "github.com/hatchet-dev/hatchet/internal/services/admin/contracts"
"github.com/hatchet-dev/hatchet/internal/services/dispatcher"
dispatchercontracts "github.com/hatchet-dev/hatchet/internal/services/dispatcher/contracts"
"github.com/hatchet-dev/hatchet/internal/services/grpc/middleware"
"github.com/hatchet-dev/hatchet/internal/services/ingestor"
eventcontracts "github.com/hatchet-dev/hatchet/internal/services/ingestor/contracts"
"github.com/hatchet-dev/hatchet/pkg/analytics"
"github.com/hatchet-dev/hatchet/pkg/errors"
)
type Server struct {
eventcontracts.UnimplementedEventsServiceServer
dispatchercontracts.UnimplementedDispatcherServer
admincontracts.UnimplementedWorkflowServiceServer
l *zerolog.Logger
a errors.Alerter
analytics analytics.Analytics
port int
bindAddress string
config *server.ServerConfig
ingestor ingestor.Ingestor
dispatcher dispatcher.Dispatcher
admin admin.AdminService
tls *tls.Config
insecure bool
}
type ServerOpt func(*ServerOpts)
type ServerOpts struct {
config *server.ServerConfig
l *zerolog.Logger
a errors.Alerter
analytics analytics.Analytics
port int
bindAddress string
ingestor ingestor.Ingestor
dispatcher dispatcher.Dispatcher
admin admin.AdminService
tls *tls.Config
insecure bool
}
func defaultServerOpts() *ServerOpts {
logger := logger.NewDefaultLogger("grpc")
a := errors.NoOpAlerter{}
analytics := analytics.NoOpAnalytics{}
return &ServerOpts{
l: &logger,
a: a,
analytics: analytics,
port: 7070,
bindAddress: "127.0.0.1",
insecure: false,
}
}
func WithLogger(l *zerolog.Logger) ServerOpt {
return func(opts *ServerOpts) {
opts.l = l
}
}
func WithAlerter(a errors.Alerter) ServerOpt {
return func(opts *ServerOpts) {
opts.a = a
}
}
func WithAnalytics(a analytics.Analytics) ServerOpt {
return func(opts *ServerOpts) {
opts.analytics = a
}
}
func WithBindAddress(bindAddress string) ServerOpt {
return func(opts *ServerOpts) {
opts.bindAddress = bindAddress
}
}
func WithPort(port int) ServerOpt {
return func(opts *ServerOpts) {
opts.port = port
}
}
func WithIngestor(i ingestor.Ingestor) ServerOpt {
return func(opts *ServerOpts) {
opts.ingestor = i
}
}
func WithConfig(config *server.ServerConfig) ServerOpt {
return func(opts *ServerOpts) {
opts.config = config
}
}
func WithTLSConfig(tls *tls.Config) ServerOpt {
return func(opts *ServerOpts) {
opts.tls = tls
}
}
func WithInsecure() ServerOpt {
return func(opts *ServerOpts) {
opts.insecure = true
}
}
func WithDispatcher(d dispatcher.Dispatcher) ServerOpt {
return func(opts *ServerOpts) {
opts.dispatcher = d
}
}
func WithAdmin(a admin.AdminService) ServerOpt {
return func(opts *ServerOpts) {
opts.admin = a
}
}
func NewServer(fs ...ServerOpt) (*Server, error) {
opts := defaultServerOpts()
for _, f := range fs {
f(opts)
}
if opts.config == nil {
return nil, fmt.Errorf("config is required. use WithConfig")
}
if opts.tls == nil {
return nil, fmt.Errorf("tls config is required. use WithTLSConfig")
}
newLogger := opts.l.With().Str("service", "grpc").Logger()
opts.l = &newLogger
return &Server{
l: opts.l,
a: opts.a,
analytics: opts.analytics,
config: opts.config,
port: opts.port,
bindAddress: opts.bindAddress,
ingestor: opts.ingestor,
dispatcher: opts.dispatcher,
admin: opts.admin,
tls: opts.tls,
insecure: opts.insecure,
}, nil
}
func (s *Server) Start() (func() error, error) {
return s.startGRPC()
}
func (s *Server) startGRPC() (func() error, error) {
s.l.Debug().Msgf("starting grpc server on %s:%d", s.bindAddress, s.port)
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", s.bindAddress, s.port))
if err != nil {
return nil, fmt.Errorf("failed to listen: %w", err)
}
serverOpts := []grpc.ServerOption{}
if s.insecure {
serverOpts = append(serverOpts, grpc.Creds(insecure.NewCredentials()))
} else {
serverOpts = append(serverOpts, grpc.Creds(credentials.NewTLS(s.tls)))
}
authMiddleware := middleware.NewAuthN(s.config)
grpcPanicRecoveryHandler := func(p any) (err error) {
panicErr, ok := p.(error)
var panicStr string
if !ok {
panicStr, ok = p.(string)
if !ok {
panicStr = "Could not determine panic error"
}
} else {
panicStr = panicErr.Error()
}
err = fmt.Errorf("recovered from panic: %s. Stack: %s", panicStr, string(debug.Stack()))
s.l.Err(err).Msg("")
s.a.SendAlert(context.Background(), err, nil)
return status.Errorf(codes.Internal, "An internal error occurred")
}
errorInterceptor := middleware.NewErrorInterceptor(s.a, s.l)
opts := []logging.Option{
logging.WithLogOnEvents(logging.StartCall, logging.FinishCall),
}
serverOpts = append(serverOpts, grpc.ChainStreamInterceptor(
logging.StreamServerInterceptor(middleware.InterceptorLogger(s.l), opts...),
auth.StreamServerInterceptor(authMiddleware.Middleware),
errorInterceptor.ErrorStreamServerInterceptor(),
recovery.StreamServerInterceptor(recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)),
))
serverOpts = append(serverOpts, grpc.ChainUnaryInterceptor(
logging.UnaryServerInterceptor(middleware.InterceptorLogger(s.l), opts...),
auth.UnaryServerInterceptor(authMiddleware.Middleware),
errorInterceptor.ErrorUnaryServerInterceptor(),
recovery.UnaryServerInterceptor(recovery.WithRecoveryHandler(grpcPanicRecoveryHandler)),
))
var enforcement = keepalive.EnforcementPolicy{
MinTime: 5 * time.Second,
PermitWithoutStream: true,
}
serverOpts = append(serverOpts, grpc.KeepaliveEnforcementPolicy(enforcement))
var kasp = keepalive.ServerParameters{
// ping the client every 30 seconds if idle to ensure the connection is still active
Time: 30 * time.Second,
}
serverOpts = append(serverOpts, grpc.KeepaliveParams(kasp))
grpcServer := grpc.NewServer(serverOpts...)
if s.ingestor != nil {
eventcontracts.RegisterEventsServiceServer(grpcServer, s.ingestor)
}
if s.dispatcher != nil {
dispatchercontracts.RegisterDispatcherServer(grpcServer, s.dispatcher)
}
if s.admin != nil {
admincontracts.RegisterWorkflowServiceServer(grpcServer, s.admin)
}
go func() {
if err := grpcServer.Serve(lis); err != nil {
panic(fmt.Errorf("failed to serve: %w", err))
}
}()
cleanup := func() error {
grpcServer.GracefulStop()
return nil
}
return cleanup, nil
}