-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
300 lines (227 loc) · 8.08 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
package redisOrderedQueue
import (
"github.com/go-redis/redis/v8"
"github.com/sahmad98/go-ringbuffer"
"fmt"
"context"
"encoding/json"
"time"
"sync/atomic"
"sync"
"strings"
"strconv"
)
type RedisQueueClient interface {
StartConsumers (ctx context.Context) (error)
StopConsumers (ctx context.Context) (error)
Close () (error)
GetMetrics (ctx context.Context, options *GetMetricsOptions) (*Metrics, error)
Send (ctx context.Context, data interface{}, priority int, groupId string) (error)
}
type redisQueueWireMessage struct {
Timestamp int64 `json:"t"`
Producer int64 `json:"c"`
Sequence int64 `json:"s"`
Data *interface{} `json:"d"`
};
type MessageMetadata struct {
MessageContext struct {
Timestamp time.Time
Producer int64
Sequence int64
Latency time.Duration
Lock *lockHandle
}
}
type redisQueueClient struct {
mu sync.RWMutex
options* Options
redis* redis.Client
groupStreamKey string
groupSetKey string
clientIndexKey string
consumerGroupId string
messagePriorityQueueKeyPrefix string
clientId int64
lastMessageSequenceNumber int64
consumerWorkers []*redisQueueWorker
consumerCancellationFunctions []*context.CancelFunc
callGetMetrics redisScriptCall
callAddGroupAndMessageToQueue redisScriptCall
statTotalInvalidMessagesCount int64
statLastMessageLatencies *ringbuffer.RingBuffer
}
func NewClient (ctx context.Context, options* Options) (RedisQueueClient, error) {
if err := options.Validate(); err != nil {
return nil, err
}
var c = &redisQueueClient{}
c.options = options
c.redis = redis.NewClient(c.options.RedisOptions)
redisKeyFormat := "%s::%s"
c.groupStreamKey = fmt.Sprintf(redisKeyFormat, c.options.RedisKeyPrefix, "msg-group-stream")
c.groupSetKey = fmt.Sprintf(redisKeyFormat, c.options.RedisKeyPrefix, "msg-group-set")
c.clientIndexKey = fmt.Sprintf(redisKeyFormat, c.options.RedisKeyPrefix, "consumer-index-sequence")
c.consumerGroupId = fmt.Sprintf(redisKeyFormat, c.options.RedisKeyPrefix, "consumer-group")
c.messagePriorityQueueKeyPrefix = fmt.Sprintf(redisKeyFormat, c.options.RedisKeyPrefix, "msg-group-queue")
c.lastMessageSequenceNumber = 0
c.statLastMessageLatencies = ringbuffer.NewRingBuffer(100)
var err error
if c.clientId, err = c.createClientId(ctx); err != nil {
return nil, err
}
// Prepare Redis scripts calls
if c.callGetMetrics, err = newScriptCall(ctx, c.redis, scriptGetMetrics); err != nil { c.redis.Close(); return nil, err }
if c.callAddGroupAndMessageToQueue, err = newScriptCall(ctx, c.redis, scriptAddGroupAndMessageToQueue); err != nil { c.redis.Close(); return nil, err }
// Ensure stream group exists
if _, err = c.redis.Do(ctx, "XGROUP", "CREATE", c.groupStreamKey, c.consumerGroupId, 0, "MKSTREAM").Result(); err != nil {
if (!strings.HasPrefix(err.Error(), "BUSYGROUP")) {
return nil, err
}
}
return c, nil
}
func (c *redisQueueClient) createClientId (ctx context.Context) (int64, error) {
return c.redis.Incr(ctx, c.clientIndexKey).Result()
}
func (c* redisQueueClient) createPriorityMessageQueueKey (groupId string) (string) {
return fmt.Sprintf("%s::%s", c.messagePriorityQueueKeyPrefix, groupId);
}
func (c *redisQueueClient) processInvalidMessage (ctx context.Context, msgData *string) (error) {
c.mu.RLock()
defer c.mu.RUnlock()
atomic.AddInt64(&c.statTotalInvalidMessagesCount, 1)
if (c.options.HandleInvalidMessage != nil) {
return c.options.HandleInvalidMessage(ctx, msgData)
}
return nil
}
func (c *redisQueueClient) processMessage (ctx context.Context, lock *lockHandle, msgData string) (error) {
c.mu.RLock()
defer c.mu.RUnlock()
var packet redisQueueWireMessage
var err error
if err = json.Unmarshal([]byte(msgData), &packet); err != nil {
return c.processInvalidMessage(ctx, &msgData);
}
var meta MessageMetadata
meta.MessageContext.Timestamp = time.UnixMilli(packet.Timestamp).UTC()
meta.MessageContext.Producer = packet.Producer
meta.MessageContext.Sequence = packet.Sequence
meta.MessageContext.Latency = time.Now().UTC().Sub(meta.MessageContext.Timestamp)
meta.MessageContext.Lock = lock
c.statLastMessageLatencies.Write(meta.MessageContext.Latency)
return c.options.HandleMessage(ctx, packet.Data, &meta)
}
func (c *redisQueueClient) Close () (error) {
c.StopConsumers(context.TODO())
return c.redis.Close()
}
func (c *redisQueueClient) Send (ctx context.Context, data interface{}, priority int, groupId string) (error) {
c.mu.RLock()
defer c.mu.RUnlock()
var packet redisQueueWireMessage
packet.Timestamp = time.Now().UTC().UnixMilli()
packet.Producer = c.clientId
packet.Sequence = atomic.AddInt64(&c.lastMessageSequenceNumber, 1)
packet.Data = &data
var jsonString, err = json.Marshal(packet)
if (err != nil) {
return err
}
_, err = c.callAddGroupAndMessageToQueue(ctx, c.redis,
[]interface{} { groupId, priority, jsonString },
[]string { c.groupStreamKey, c.groupSetKey, c.createPriorityMessageQueueKey(groupId) },
).Result();
return err
}
func (c *redisQueueClient) StartConsumers (ctx context.Context) (error) {
c.mu.Lock()
if (len(c.consumerWorkers) > 0) { return fmt.Errorf("Consumers already started"); }
for i := 0; i < c.options.ConsumerCount; i++ {
worker, err := newWorker(ctx, c)
if (err != nil) {
// Stop consumers which have been started
c.mu.Unlock()
c.StopConsumers(ctx)
return err
}
context, cancelFunc := context.WithCancel(ctx)
go worker.run(context)
c.consumerCancellationFunctions = append(c.consumerCancellationFunctions, &cancelFunc)
c.consumerWorkers = append(c.consumerWorkers, worker)
}
c.mu.Unlock()
return nil
}
func (c *redisQueueClient) StopConsumers (ctx context.Context) (error) {
c.mu.Lock()
defer c.mu.Unlock()
if (len(c.consumerWorkers) == 0) { return fmt.Errorf("Consumers are not running"); }
for _, cancelFunc := range(c.consumerCancellationFunctions) {
(*cancelFunc)();
}
c.consumerCancellationFunctions = []*context.CancelFunc {}
c.consumerWorkers = []*redisQueueWorker {}
return nil
}
func (c *redisQueueClient) getMetricsParseTopMessageGroups (result *Metrics, data []interface{}) {
if list, ok := data[4].([]interface{}); ok {
for i := 0; i < len(list); i += 2 {
if backlog, err := strconv.ParseInt(list[i + 1].(string), 10, 0); err == nil {
result.TopMessageGroups = append(result.TopMessageGroups, &MessageGroupMetrics{
Group: list[i].(string),
Backlog: backlog,
})
result.TopMessageGroupsMessageBacklogLength += backlog
}
}
}
}
func (c *redisQueueClient) getMetricsParseLatencies (result *Metrics) {
latencies := make([]interface{}, c.statLastMessageLatencies.Size)
copy(latencies, c.statLastMessageLatencies.Container)
var sumLatencyMs int64
var minLatencyMs int64 = 0
var maxLatencyMs int64 = 0
var numLatencies int64 = 0
if (len(latencies) > 0 && latencies[0] != nil) {
minLatencyMs = latencies[0].(time.Duration).Milliseconds()
}
for _, latency := range(latencies) {
if (latency != nil) {
numLatencies++
ms := latency.(time.Duration).Milliseconds()
sumLatencyMs += ms
if (ms < minLatencyMs) { minLatencyMs = ms; }
if (ms > maxLatencyMs) { maxLatencyMs = ms; }
}
}
result.MinLatency = time.Duration(minLatencyMs) * time.Millisecond
result.MaxLatency = time.Duration(maxLatencyMs) * time.Millisecond
if (numLatencies > 0) {
result.AvgLatency = time.Duration(sumLatencyMs / numLatencies) * time.Millisecond
} else {
result.AvgLatency = time.Duration(0)
}
}
func (c *redisQueueClient) GetMetrics (ctx context.Context, options *GetMetricsOptions) (*Metrics, error) {
c.mu.RLock()
defer c.mu.RUnlock()
data, err := c.callGetMetrics(ctx, c.redis,
[]interface{} { c.consumerGroupId, options.TopMessageGroupsLimit },
[]string { c.groupStreamKey, c.groupSetKey },
).Slice()
if (err != nil) { return nil, err }
result := &Metrics{
BufferedMessageGroups: data[0].(int64),
TrackedMessageGroups: data[1].(int64),
WorkingConsumers: data[2].(int64),
VisibleMessages: data[3].(int64),
InvalidMessages: c.statTotalInvalidMessagesCount,
TopMessageGroupsMessageBacklogLength: 0,
}
c.getMetricsParseTopMessageGroups(result, data)
c.getMetricsParseLatencies(result)
return result, nil
}