/
client.go
458 lines (394 loc) · 10.6 KB
/
client.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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package client
import (
"fmt"
"github.com/kubemq-io/kubemq-community/pkg/entities"
pb "github.com/kubemq-io/protobuf/go"
"github.com/nats-io/nuid"
"sync"
"time"
nats "github.com/kubemq-io/broker/client/nats"
stan "github.com/kubemq-io/broker/client/stan"
"github.com/kubemq-io/kubemq-community/pkg/logging"
"context"
"go.uber.org/atomic"
)
const (
prefixEvents = "_EVENTS_."
prefixEventsStore = "_EVENTS_STORE_."
prefixCommands = "_COMMANDS_."
prefixQueries = "_QUERIES_."
prefixQueues = "_QUEUES_."
delayQueueChannel = "_QUEUE_DELAY_"
)
const (
storeConnectionTime = 30 * time.Second
defaultDeadline = 2000 * time.Millisecond
storePingInterval = 30000
storePingMaxOut = 30000
)
type Client struct {
options *Options
mu sync.Mutex
logger *logging.Logger
isUp *atomic.Bool
baseConn *nats.Conn
subscriber *nats.Subscription
storeConn stan.Conn
queueConn stan.Conn
storeSubscriber stan.Subscription
writeDeadline time.Duration
isStoreClient bool
isQueueClient bool
}
func getBaseClient(opts *Options, isPersistence bool) (*Client, error) {
err := validateOptions(opts, isPersistence)
if err != nil {
return nil, err
}
nc := &Client{
options: opts,
logger: logging.GetLogFactory().NewLogger("client-" + opts.ClientID),
isUp: atomic.NewBool(false),
isStoreClient: isPersistence,
}
if opts.Deadline == 0 {
nc.writeDeadline = defaultDeadline
} else {
nc.writeDeadline = opts.Deadline
}
return nc, nil
}
func NewClient(opts *Options) (*Client, error) {
nc, err := getBaseClient(opts, false)
if err != nil {
return nil, err
}
err = nc.connect(opts)
if err != nil {
return nil, err
}
nc.isUp.Store(true)
return nc, nil
}
func NewStoreClient(opts *Options) (*Client, error) {
nc, err := getBaseClient(opts, true)
if err != nil {
return nil, err
}
err = nc.connect(opts)
if err != nil {
return nil, err
}
nc.storeConn, err = nc.connectStore(nc.baseConn, opts)
if err != nil {
return nil, err
}
nc.isUp.Store(true)
return nc, nil
}
func (c *Client) connectStore(conn *nats.Conn, opts *Options) (stan.Conn, error) {
storeConn, err := stan.Connect("kubemq", opts.ClientID,
stan.NatsConn(conn),
stan.NatsURL(fmt.Sprintf("nats://0.0.0.0:%d", 4224)),
stan.ConnectWait(storeConnectionTime),
stan.Pings(storePingInterval, storePingMaxOut),
stan.SetConnectionLostHandler(func(conn stan.Conn, err error) {
c.logger.Errorf("store client %s connection lost", opts.ClientID)
}),
)
return storeConn, err
}
func (c *Client) connect(opts *Options) error {
natsOpts := nats.Options{
Url: fmt.Sprintf("nats://0.0.0.0:%d", 4224),
DisconnectedErrCB: func(conn *nats.Conn, err error) {
conn.Close()
},
}
if opts.AutoReconnect {
natsOpts.AllowReconnect = true
natsOpts.MaxReconnect = -1
natsOpts.ReconnectWait = 100 * time.Millisecond
natsOpts.ReconnectBufSize = 1000
}
if opts.MemoryPipe != nil {
natsOpts.CustomDialer = opts.MemoryPipe
} else {
return fmt.Errorf("no memory pipe exist")
}
conn, err := natsOpts.Connect()
if err != nil {
return err
}
c.baseConn = conn
return nil
}
func (c *Client) UnSubscribe() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.isStoreClient {
_ = c.storeSubscriber.Unsubscribe()
}
return c.subscriber.Unsubscribe()
}
func (c *Client) Disconnect() error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.isUp.Load() {
return nil
}
c.isUp.Store(false)
if c.isStoreClient {
c.storeConn.Close()
}
if c.isQueueClient {
c.queueConn.Close()
}
c.baseConn.Close()
return nil
}
func (c *Client) SendEvents(ctx context.Context, event *pb.Event) (*pb.Result, error) {
if !c.isUp.Load() {
return nil, entities.ErrConnectionNoAvailable
}
if err := ValidateEventMessage(event); err != nil {
return nil, err
}
if event.EventID == "" {
event.EventID = nuid.Next()
}
result := &pb.Result{
EventID: event.EventID,
Sent: true,
Error: "",
}
channel := fmt.Sprintf("%s%s", prefixEvents, event.Channel)
data, err := event.Marshal()
if err != nil {
return nil, err
}
err = c.baseConn.Publish(channel, data)
if err != nil {
result.Sent = false
result.Error = err.Error()
}
return result, nil
}
func (c *Client) SendEventsStore(ctx context.Context, event *pb.Event) (*pb.Result, error) {
if !c.isUp.Load() {
return nil, entities.ErrConnectionNoAvailable
}
if err := ValidateEventMessage(event); err != nil {
return nil, err
}
if event.EventID == "" {
event.EventID = nuid.Next()
}
result := &pb.Result{
EventID: event.EventID,
Sent: true,
Error: "",
}
channel := prefixEventsStore + event.Channel
data, err := event.Marshal()
if err != nil {
return nil, err
}
_, err = c.storeConn.PublishAsync(channel, data, func(s string, err error) {
})
if err != nil {
result.Sent = false
result.Error = err.Error()
}
return result, nil
}
func (c *Client) SubscribeToEvents(ctx context.Context, subReq *pb.Subscribe, eventsCh chan *pb.EventReceive) error {
if !c.isUp.Load() {
return entities.ErrConnectionNoAvailable
}
if err := ValidateSubscriptionToEvents(subReq, entities.KindTypeEvent); err != nil {
return err
}
var err error
channel := fmt.Sprintf("%s%s", prefixEvents, subReq.Channel)
c.subscriber, err = c.baseConn.QueueSubscribe(channel, subReq.Group, func(r *nats.Msg) {
eventReceive, err := UnmarshalToEventReceive(r.Data)
if err != nil {
c.logger.Errorf("error on unmarshal message", "error", err.Error())
return
}
select {
case <-ctx.Done():
return
case eventsCh <- eventReceive:
case <-time.After(c.writeDeadline):
c.logger.Warnw("events message dropped due to slow consumer", "channel", channel, "event_id", eventReceive.EventID, "metadata", eventReceive.Metadata)
}
})
return err
}
func (c *Client) SubscribeToEventsStore(ctx context.Context, subReq *pb.Subscribe, eventsCh chan *pb.EventReceive) error {
c.mu.Lock()
defer c.mu.Unlock()
if !c.isUp.Load() {
return entities.ErrConnectionNoAvailable
}
if err := ValidateSubscriptionToEvents(subReq, entities.KindTypeEventStore); err != nil {
return err
}
subOpts := ParseSubscriptionRequest(subReq)
channel := prefixEventsStore + subReq.Channel
var err error
c.storeSubscriber, err = c.storeConn.QueueSubscribe(channel, subReq.Group, func(msg *stan.Msg) {
c.mu.Lock()
defer c.mu.Unlock()
var err error
eventReceive, err := unmarshalToEventReceive(msg.Data)
if err != nil {
c.logger.Errorf("error on unmarshal message, %s", err.Error())
return
}
eventReceive.Timestamp = msg.Timestamp
eventReceive.Sequence = msg.Sequence
select {
case <-ctx.Done():
return
case eventsCh <- eventReceive:
case <-time.After(c.writeDeadline):
c.logger.Warnw("events store message dropped due to slow consumer", "channel", channel, "event_id", eventReceive.EventID, "metadata", eventReceive.Metadata)
}
}, subOpts...)
return err
}
func (c *Client) SendCommand(ctx context.Context, req *pb.Request) (*pb.Response, error) {
if !c.isUp.Load() {
return nil, entities.ErrConnectionNoAvailable
}
if err := ValidateRequest(req); err != nil {
return nil, err
}
if req.RequestID == "" {
req.RequestID = nuid.Next()
}
channel := prefixCommands + req.Channel
ctxTimeout, cancel := context.WithTimeout(ctx, time.Duration(req.Timeout)*time.Millisecond)
defer cancel()
data, err := req.Marshal()
if err != nil {
return nil, err
}
resMsg, err := c.baseConn.RequestWithContext(ctxTimeout, channel, data)
if err != nil {
return nil, entities.ErrRequestTimeout
}
res := &pb.Response{}
err = res.Unmarshal(resMsg.Data)
if err != nil {
return nil, entities.ErrInvalidResponseFormat
}
res.Body = nil
res.Metadata = ""
res.CacheHit = false
res.ReplyChannel = ""
return res, nil
}
func (c *Client) SendQuery(ctx context.Context, req *pb.Request) (*pb.Response, error) {
if !c.isUp.Load() {
return nil, entities.ErrConnectionNoAvailable
}
if err := ValidateRequest(req); err != nil {
return nil, err
}
if req.RequestID == "" {
req.RequestID = nuid.Next()
}
channel := prefixQueries + req.Channel
ctxTimeout, cancel := context.WithTimeout(ctx, time.Duration(req.Timeout)*time.Millisecond)
defer cancel()
data, err := req.Marshal()
if err != nil {
return nil, err
}
resMsg, err := c.baseConn.RequestWithContext(ctxTimeout, channel, data)
if err != nil {
return nil, entities.ErrRequestTimeout
}
res := &pb.Response{}
err = res.Unmarshal(resMsg.Data)
if err != nil {
return nil, entities.ErrInvalidResponseFormat
}
res.ReplyChannel = ""
return res, nil
}
func (c *Client) SendResponse(ctx context.Context, res *pb.Response) error {
if !c.isUp.Load() {
return entities.ErrConnectionNoAvailable
}
if err := ValidateResponse(res); err != nil {
return err
}
data, err := res.Marshal()
if err != nil {
return err
}
err = c.baseConn.Publish(res.ReplyChannel, data)
if err != nil {
return err
}
return nil
}
func (c *Client) SubscribeToCommands(ctx context.Context, subReq *pb.Subscribe, reqCh chan *pb.Request) error {
if !c.isUp.Load() {
return entities.ErrConnectionNoAvailable
}
if err := ValidateSubscriptionToRequests(subReq); err != nil {
return err
}
channel := prefixCommands + subReq.Channel
var err error
c.subscriber, err = c.baseConn.QueueSubscribe(channel, subReq.Group, func(r *nats.Msg) {
req := &pb.Request{}
err := req.Unmarshal(r.Data)
if err == nil {
req.ReplyChannel = r.Reply
select {
case <-ctx.Done():
return
case reqCh <- req:
case <-time.After(c.writeDeadline):
c.logger.Warnw("command request dropped due to slow consumer", "channel", channel, "client_id", req.ClientID, "request_id", req.RequestID, "metadata", req.Metadata)
}
} else {
c.logger.Errorw("error on unmarshal commands request", "error", err)
}
})
return err
}
func (c *Client) SubscribeToQueries(ctx context.Context, subReq *pb.Subscribe, reqCh chan *pb.Request) error {
if !c.isUp.Load() {
return entities.ErrConnectionNoAvailable
}
if err := ValidateSubscriptionToRequests(subReq); err != nil {
return err
}
channel := prefixQueries + subReq.Channel
var err error
c.subscriber, err = c.baseConn.QueueSubscribe(channel, subReq.Group, func(r *nats.Msg) {
req := &pb.Request{}
err := req.Unmarshal(r.Data)
if err == nil {
req.ReplyChannel = r.Reply
select {
case <-ctx.Done():
return
case reqCh <- req:
case <-time.After(c.writeDeadline):
c.logger.Warnw("query request dropped due to slow consumer", "channel", channel, "client_id", req.ClientID, "request_id", req.RequestID, "metadata", req.Metadata)
}
} else {
c.logger.Errorw("error on unmarshal query request", "error", err)
}
})
return err
}