-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnector.go
More file actions
345 lines (293 loc) · 9.53 KB
/
connector.go
File metadata and controls
345 lines (293 loc) · 9.53 KB
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package lunodbgo
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"sync"
"time"
lunopb "github.com/cloudproud/lunodb.api/proto"
"github.com/cloudproud/lunodb.go/value"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
)
// ConnectorOption defines a functional option for configuring a Connector. It
// allows for flexible and composable Connector construction via NewConnector.
type ConnectorOption func(*Connector) error
// WithLogger sets a custom zap.Logger for the Connector.
// If not specified, a no-op logger is used by default.
func WithLogger(logger *zap.Logger) ConnectorOption {
return func(connector *Connector) error {
connector.logger = logger
return nil
}
}
// WithStargateAddress sets the address of the Stargate gRPC endpoint.
func WithStargateAddress(address string) ConnectorOption {
return func(connector *Connector) error {
connector.StargateAddress = address
return nil
}
}
// WithInsecure configures the Connector to use insecure transport credentials (non-TLS).
func WithInsecure(insecure bool) ConnectorOption {
return func(connector *Connector) error {
connector.Insecure = insecure
return nil
}
}
// WithSource sets the source identifier used to register this Connector with Stargate.
func WithSource(source string) ConnectorOption {
return func(connector *Connector) (err error) {
connector.Source, err = strconv.ParseUint(source, 10, 64)
if err != nil {
return fmt.Errorf("invalid source uid: %w", err)
}
return nil
}
}
// WithToken sets the secret token used for authenticating this Connector with Stargate.
func WithToken(token string) ConnectorOption {
return func(connector *Connector) error {
connector.Token = token
return nil
}
}
// DefaultConnectorHeartbeat represents the default heartbeat interval in which a given
// source controller will ping the configured source.
const DefaultConnectorHeartbeat = 5 * time.Second
// NewConnector constructs a new Connector instance with optional configuration overrides.
func NewConnector(options ...ConnectorOption) (*Connector, error) {
connector := Connector{
logger: zap.NewNop(),
StargateAddress: os.Getenv("LUNODB_STARGATE_ADDRESS"),
Insecure: os.Getenv("LUNODB_INSECURE") == "true",
}
if connector.StargateAddress == "" {
connector.StargateAddress = DefaultStargateAddress
}
for _, option := range options {
err := option(&connector)
if err != nil {
return nil, err
}
}
return &connector, nil
}
// Connector is a gRPC client that connects to the LunoDB Stargate server. It
// maintains connection settings such as address, TLS preferences, and source
// identity.
type Connector struct {
logger *zap.Logger
StargateAddress string
Insecure bool
Source uint64
Token string
mu sync.Mutex
healthy bool
}
// Healthy returns true if the Connector is currently healthy and able to
// process Stargate requests.
func (connector *Connector) Healthy() bool {
connector.mu.Lock()
defer connector.mu.Unlock()
return connector.healthy
}
// Serve establishes a gRPC connection to the configured Stargate server and
// starts the message receive loop using the provided handler. It blocks until
// the stream ends or an error occurs.
func (connector *Connector) Serve(ctx context.Context, handler Handler) error {
options := []grpc.DialOption{}
if connector.Insecure {
options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
conn, err := grpc.NewClient(connector.StargateAddress, options...)
if err != nil {
return err
}
client := lunopb.NewStargateClient(conn)
return connector.serveLoop(ctx, client, handler)
}
func (connector *Connector) defaultOutgoingContext(ctx context.Context) context.Context {
md := map[string][]string{
"authorization": {"Bearer " + connector.Token},
"source": {fmt.Sprintf("%d", connector.Source)},
}
return metadata.NewOutgoingContext(ctx, md)
}
func (connector *Connector) serveLoop(ctx context.Context, client lunopb.StargateClient, handler Handler) error {
heartbeat := time.NewTicker(DefaultConnectorHeartbeat)
defer heartbeat.Stop()
for {
logger := connector.logger.With(zap.String("address", connector.StargateAddress))
logger.Info("attempting to connect to Stargate")
connector.serveTick(ctx, client, handler)
logger.Info("connection closed, attempting to reconnect", zap.Duration("heartbeat", DefaultConnectorHeartbeat))
select {
case <-ctx.Done():
connector.logger.Info("context cancelled, stopping connector")
return nil
case <-heartbeat.C:
logger.Info("attempting to reconnect to Stargate...")
}
}
}
func (connector *Connector) serveTick(ctx context.Context, client lunopb.StargateClient, handler Handler) {
ctx = connector.defaultOutgoingContext(ctx)
stream, err := client.Connector(ctx)
if err != nil {
connector.logger.Error("failed to connect to Stargate", zap.Error(err))
return
}
connector.logger.Info("connected to Stargate")
err = connector.recvLoop(ctx, stream, handler)
if err != nil {
connector.logger.Error("unexpected error in receive loop", zap.Error(err))
return
}
}
func (connector *Connector) recvLoop(ctx context.Context, stream grpc.BidiStreamingClient[lunopb.ConnectorResponse, lunopb.ConnectorRequest], handler Handler) error {
connector.health(true)
defer connector.health(false)
logger := connector.logger.With(zap.String("address", connector.StargateAddress))
logger.Info("starting message receive loop")
ctx, cancel := context.WithCancel(ctx)
defer cancel()
for {
msg, err := stream.Recv()
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil
}
if err != nil {
return err
}
logger.Debug("received message", zap.Uint32("id", msg.Id))
switch state := msg.State.(type) {
case *lunopb.ConnectorRequest_Ping:
go func() {
err := connector.ping(ctx, msg.Id, stream, handler)
if err != nil {
logger.Error("failed to ping", zap.Error(err))
cancel()
}
}()
case *lunopb.ConnectorRequest_Fetch:
go func() {
err := connector.fetch(ctx, msg.Id, stream, handler)
if err != nil {
logger.Error("failed to fetch tables", zap.Error(err))
cancel()
}
}()
case *lunopb.ConnectorRequest_ExecuteStatement:
go func() {
err := connector.execute(ctx, msg.Id, state.ExecuteStatement, stream, handler)
if err != nil {
logger.Error("failed to execute statement", zap.Error(err))
cancel()
}
}()
}
}
}
func (connector *Connector) health(status bool) {
connector.mu.Lock()
defer connector.mu.Unlock()
connector.healthy = status
}
func (connector *Connector) ping(ctx context.Context, id uint32, stream grpc.BidiStreamingClient[lunopb.ConnectorResponse, lunopb.ConnectorRequest], handler Handler) error {
logger := connector.logger.With(zap.Uint32("id", id))
logger.Debug("ping connector")
pong := &lunopb.PingResponse{}
err := handler.Ping(ctx)
if err != nil {
logger.Error("unexpected error while pinging", zap.Error(err))
pong.Error = &lunopb.Error{
Message: err.Error(),
}
}
logger.Debug("ping complete")
return stream.Send(&lunopb.ConnectorResponse{
Id: id,
State: &lunopb.ConnectorResponse_Ping{
Ping: pong,
},
})
}
func (connector *Connector) fetch(ctx context.Context, id uint32, stream grpc.BidiStreamingClient[lunopb.ConnectorResponse, lunopb.ConnectorRequest], handler Handler) error {
logger := connector.logger.With(zap.Uint32("id", id))
logger.Debug("fetching tables")
fetch := &lunopb.FetchResponse{}
tables, err := handler.Fetch(ctx)
if err != nil {
logger.Error("unexpected error while fetching tables", zap.Error(err))
fetch.Error = &lunopb.Error{
Message: err.Error(),
}
}
if tables != nil {
fetch.Tables = tables.Proto()
}
logger.Debug("tables fetched", zap.Int("count", len(fetch.Tables)))
return stream.Send(&lunopb.ConnectorResponse{
Id: id,
State: &lunopb.ConnectorResponse_Fetch{
Fetch: fetch,
},
})
}
func (connector *Connector) execute(ctx context.Context, id uint32, state *lunopb.ExecuteStatementRequest, stream grpc.BidiStreamingClient[lunopb.ConnectorResponse, lunopb.ConnectorRequest], handler Handler) error {
plan := state.Plan
logger := connector.logger.With(zap.Uint32("id", id))
logger.Debug("executing statement")
writer := WriterFunc(func(ctx context.Context, values []any) (err error) {
row := make([][]byte, len(values))
for index, col := range values {
_, row[index], err = value.Encode(col, nil)
if err != nil {
return err
}
}
logger.Debug("writing row")
return stream.Send(&lunopb.ConnectorResponse{
Id: id,
State: &lunopb.ConnectorResponse_ExecuteStatement{
ExecuteStatement: &lunopb.ExecuteStatementResponse{
Result: &lunopb.ExecuteStatementResponse_Data{
Data: &lunopb.Row{
Values: row,
},
},
},
},
})
})
err := handler.Scan(ctx, plan, writer)
if err != nil {
logger.Error("unexpected error while scanning", zap.Error(err))
return stream.Send(&lunopb.ConnectorResponse{
Id: id,
State: &lunopb.ConnectorResponse_ExecuteStatement{
ExecuteStatement: &lunopb.ExecuteStatementResponse{
Result: &lunopb.ExecuteStatementResponse_Error{
Error: &lunopb.Error{
Message: err.Error(),
},
},
},
},
})
}
logger.Debug("statement executed successfully")
return stream.Send(&lunopb.ConnectorResponse{
Id: id,
State: &lunopb.ConnectorResponse_ExecuteStatement{
ExecuteStatement: &lunopb.ExecuteStatementResponse{
Result: &lunopb.ExecuteStatementResponse_EOE{},
},
},
})
}