-
Notifications
You must be signed in to change notification settings - Fork 217
/
stream.go
500 lines (435 loc) · 10.3 KB
/
stream.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// Basic stream implementation.
package miniredis
import (
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// a Stream is a list of entries, lowest ID (oldest) first, and all "groups".
type streamKey struct {
entries []StreamEntry
groups map[string]*streamGroup
lastAllocatedID string
mu sync.Mutex
}
// a StreamEntry is an entry in a stream. The ID is always of the form
// "123-123".
// Values is an ordered list of key-value pairs.
type StreamEntry struct {
ID string
Values []string
}
type streamGroup struct {
stream *streamKey
lastID string
pending []pendingEntry
consumers map[string]*consumer
}
type consumer struct {
numPendingEntries int
// these timestamps aren't tracked perfectly
lastSeen time.Time // "idle" XINFO key
lastSuccess time.Time // "inactive" XINFO key
}
type pendingEntry struct {
id string
consumer string
deliveryCount int
lastDelivery time.Time
}
func newStreamKey() *streamKey {
return &streamKey{
groups: map[string]*streamGroup{},
}
}
// generateID doesn't lock the mutex
func (s *streamKey) generateID(now time.Time) string {
ts := uint64(now.UnixNano()) / 1_000_000
next := fmt.Sprintf("%d-%d", ts, 0)
if s.lastAllocatedID != "" && streamCmp(s.lastAllocatedID, next) >= 0 {
last, _ := parseStreamID(s.lastAllocatedID)
next = fmt.Sprintf("%d-%d", last[0], last[1]+1)
}
lastID := s.lastIDUnlocked()
if streamCmp(lastID, next) >= 0 {
last, _ := parseStreamID(lastID)
next = fmt.Sprintf("%d-%d", last[0], last[1]+1)
}
s.lastAllocatedID = next
return next
}
// lastID locks the mutex
func (s *streamKey) lastID() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.lastIDUnlocked()
}
// lastID doesn't lock the mutex
func (s *streamKey) lastIDUnlocked() string {
if len(s.entries) == 0 {
return "0-0"
}
return s.entries[len(s.entries)-1].ID
}
func (s *streamKey) copy() *streamKey {
s.mu.Lock()
defer s.mu.Unlock()
cpy := &streamKey{
entries: s.entries,
}
groups := map[string]*streamGroup{}
for k, v := range s.groups {
gr := v.copy()
gr.stream = cpy
groups[k] = gr
}
cpy.groups = groups
return cpy
}
func parseStreamID(id string) ([2]uint64, error) {
var (
res [2]uint64
err error
)
parts := strings.SplitN(id, "-", 2)
res[0], err = strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return res, errors.New(msgInvalidStreamID)
}
if len(parts) == 2 {
res[1], err = strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return res, errors.New(msgInvalidStreamID)
}
}
return res, nil
}
// compares two stream IDs (of the full format: "123-123"). Returns: -1, 0, 1
// The given IDs should be valid stream IDs.
func streamCmp(a, b string) int {
ap, _ := parseStreamID(a)
bp, _ := parseStreamID(b)
switch {
case ap[0] < bp[0]:
return -1
case ap[0] > bp[0]:
return 1
case ap[1] < bp[1]:
return -1
case ap[1] > bp[1]:
return 1
default:
return 0
}
}
// formatStreamID makes a full id ("42-42") out of a partial one ("42")
func formatStreamID(id string) (string, error) {
var ts [2]uint64
parts := strings.SplitN(id, "-", 2)
if len(parts) > 0 {
p, err := strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return "", errInvalidEntryID
}
ts[0] = p
}
if len(parts) > 1 {
p, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return "", errInvalidEntryID
}
ts[1] = p
}
return fmt.Sprintf("%d-%d", ts[0], ts[1]), nil
}
func formatStreamRangeBound(id string, start bool, reverse bool) (string, error) {
if id == "-" {
return "0-0", nil
}
if id == "+" {
return fmt.Sprintf("%d-%d", uint64(math.MaxUint64), uint64(math.MaxUint64)), nil
}
if id == "0" {
return "0-0", nil
}
parts := strings.Split(id, "-")
if len(parts) == 2 {
return formatStreamID(id)
}
// Incomplete IDs case
ts, err := strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return "", errInvalidEntryID
}
if (!start && !reverse) || (start && reverse) {
return fmt.Sprintf("%d-%d", ts, uint64(math.MaxUint64)), nil
}
return fmt.Sprintf("%d-%d", ts, 0), nil
}
func reversedStreamEntries(o []StreamEntry) []StreamEntry {
newStream := make([]StreamEntry, len(o))
for i, e := range o {
newStream[len(o)-i-1] = e
}
return newStream
}
func (s *streamKey) createGroup(group, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.groups[group]; ok {
return errors.New("BUSYGROUP Consumer Group name already exists")
}
if id == "$" {
id = s.lastIDUnlocked()
}
s.groups[group] = &streamGroup{
stream: s,
lastID: id,
consumers: map[string]*consumer{},
}
return nil
}
// streamAdd adds an entry to a stream. Returns the new entry ID.
// If id is empty or "*" the ID will be generated automatically.
// `values` should have an even length.
func (s *streamKey) add(entryID string, values []string, now time.Time) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
if entryID == "" || entryID == "*" {
entryID = s.generateID(now)
}
entryID, err := formatStreamID(entryID)
if err != nil {
return "", err
}
if entryID == "0-0" {
return "", errors.New(msgStreamIDZero)
}
if streamCmp(s.lastIDUnlocked(), entryID) != -1 {
return "", errors.New(msgStreamIDTooSmall)
}
s.entries = append(s.entries, StreamEntry{
ID: entryID,
Values: values,
})
return entryID, nil
}
func (s *streamKey) trim(n int) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.entries) > n {
s.entries = s.entries[len(s.entries)-n:]
}
}
// trimBefore deletes entries with an id less than the provided id
// and returns the number of entries deleted
func (s *streamKey) trimBefore(id string) int {
s.mu.Lock()
var delete []string
for _, entry := range s.entries {
if entry.ID < id {
delete = append(delete, entry.ID)
} else {
break
}
}
s.mu.Unlock()
s.delete(delete)
return len(delete)
}
// all entries after "id"
func (s *streamKey) after(id string) []StreamEntry {
s.mu.Lock()
defer s.mu.Unlock()
pos := sort.Search(len(s.entries), func(i int) bool {
return streamCmp(id, s.entries[i].ID) < 0
})
return s.entries[pos:]
}
// get a stream entry by ID
// Also returns the position in the entries slice, if found.
func (s *streamKey) get(id string) (int, *StreamEntry) {
s.mu.Lock()
defer s.mu.Unlock()
pos := sort.Search(len(s.entries), func(i int) bool {
return streamCmp(id, s.entries[i].ID) <= 0
})
if len(s.entries) <= pos || s.entries[pos].ID != id {
return 0, nil
}
return pos, &s.entries[pos]
}
func (g *streamGroup) readGroup(
now time.Time,
consumerID,
id string,
count int,
noack bool,
) []StreamEntry {
if id == ">" {
// undelivered messages
msgs := g.stream.after(g.lastID)
if len(msgs) == 0 {
return nil
}
if count > 0 && len(msgs) > count {
msgs = msgs[:count]
}
if !noack {
shouldAppend := len(g.pending) == 0
for _, msg := range msgs {
if !shouldAppend {
shouldAppend = streamCmp(msg.ID, g.pending[len(g.pending)-1].id) == 1
}
var entry *pendingEntry
if shouldAppend {
g.pending = append(g.pending, pendingEntry{})
entry = &g.pending[len(g.pending)-1]
} else {
var pos int
pos, entry = g.searchPending(msg.ID)
if entry == nil {
g.pending = append(g.pending[:pos+1], g.pending[pos:]...)
entry = &g.pending[pos]
} else {
g.consumers[entry.consumer].numPendingEntries--
}
}
*entry = pendingEntry{
id: msg.ID,
consumer: consumerID,
deliveryCount: 1,
lastDelivery: now,
}
}
}
if _, ok := g.consumers[consumerID]; !ok {
g.consumers[consumerID] = &consumer{}
}
g.consumers[consumerID].numPendingEntries += len(msgs)
g.lastID = msgs[len(msgs)-1].ID
return msgs
}
// re-deliver messages from the pending list.
// con := gr.consumers[consumerID]
msgs := g.pendingAfter(id)
var res []StreamEntry
for i, p := range msgs {
if p.consumer != consumerID {
continue
}
_, entry := g.stream.get(p.id)
// not found. Weird?
if entry == nil {
continue
}
p.deliveryCount += 1
p.lastDelivery = now
msgs[i] = p
res = append(res, *entry)
}
return res
}
func (g *streamGroup) searchPending(id string) (int, *pendingEntry) {
pos := sort.Search(len(g.pending), func(i int) bool {
return streamCmp(id, g.pending[i].id) <= 0
})
if pos >= len(g.pending) || g.pending[pos].id != id {
return pos, nil
}
return pos, &g.pending[pos]
}
func (g *streamGroup) ack(ids []string) (int, error) {
count := 0
for _, id := range ids {
if _, err := parseStreamID(id); err != nil {
return 0, errors.New(msgInvalidStreamID)
}
pos, entry := g.searchPending(id)
if entry == nil {
continue
}
consumer := g.consumers[entry.consumer]
consumer.numPendingEntries--
g.pending = append(g.pending[:pos], g.pending[pos+1:]...)
// don't count deleted entries
if _, e := g.stream.get(id); e == nil {
continue
}
count++
}
return count, nil
}
func (s *streamKey) delete(ids []string) (int, error) {
count := 0
for _, id := range ids {
if _, err := parseStreamID(id); err != nil {
return 0, errors.New(msgInvalidStreamID)
}
i, entry := s.get(id)
if entry == nil {
continue
}
s.entries = append(s.entries[:i], s.entries[i+1:]...)
count++
}
return count, nil
}
func (g *streamGroup) pendingAfter(id string) []pendingEntry {
pos := sort.Search(len(g.pending), func(i int) bool {
return streamCmp(id, g.pending[i].id) < 0
})
return g.pending[pos:]
}
func (g *streamGroup) pendingCount(consumer string) int {
n := 0
for _, p := range g.activePending() {
if p.consumer == consumer {
n++
}
}
return n
}
// pending entries without the entries deleted from the group
func (g *streamGroup) activePending() []pendingEntry {
var pe []pendingEntry
for _, p := range g.pending {
// drop deleted ones
if _, e := g.stream.get(p.id); e == nil {
continue
}
p := p
pe = append(pe, p)
}
return pe
}
func (g *streamGroup) copy() *streamGroup {
cns := map[string]*consumer{}
for k, v := range g.consumers {
c := *v
cns[k] = &c
}
return &streamGroup{
// don't copy stream
lastID: g.lastID,
pending: g.pending,
consumers: cns,
}
}
func (g *streamGroup) setLastSeen(c string, t time.Time) {
cons, ok := g.consumers[c]
if !ok {
cons = &consumer{}
}
cons.lastSeen = t
g.consumers[c] = cons
}
func (g *streamGroup) setLastSuccess(c string, t time.Time) {
g.setLastSeen(c, t)
g.consumers[c].lastSuccess = t
}