forked from alicebob/miniredis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
376 lines (328 loc) · 7.55 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
// Basic stream implementation.
package miniredis
import (
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
)
// a Stream is a list of entries, lowest ID (oldest) first, and all "groups".
type streamKey struct {
entries []StreamEntry
groups map[string]*streamGroup
}
// 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 {
// TODO: "last seen" timestamp
}
type pendingEntry struct {
id string
consumer string
deliveryCount int
lastDelivery time.Time
}
func newStreamKey() *streamKey {
return &streamKey{
groups: map[string]*streamGroup{},
}
}
func (s *streamKey) generateID(now time.Time) string {
ts := uint64(now.UnixNano()) / 1_000_000
lastID := s.lastID()
next := fmt.Sprintf("%d-%d", ts, 0)
if streamCmp(lastID, next) == -1 {
return next
}
last, _ := parseStreamID(lastID)
return fmt.Sprintf("%d-%d", last[0], last[1]+1)
}
func (s *streamKey) lastID() string {
if len(s.entries) == 0 {
return "0-0"
}
return s.entries[len(s.entries)-1].ID
}
func (s *streamKey) copy() *streamKey {
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 {
if _, ok := s.groups[group]; ok {
return errors.New("BUSYGROUP Consumer Group name already exists")
}
if id == "$" {
id = s.lastID()
}
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) {
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.lastID(), 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) {
if len(s.entries) > n {
s.entries = s.entries[len(s.entries)-n:]
}
}
// all entries after "id"
func (s *streamKey) after(id string) []StreamEntry {
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) {
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 {
for _, msg := range msgs {
g.pending = append(g.pending, pendingEntry{
id: msg.ID,
consumer: consumerID,
deliveryCount: 1,
lastDelivery: now,
})
}
}
g.consumers[consumerID] = consumer{}
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) ack(ids []string) (int, error) {
count := 0
for _, id := range ids {
if _, err := parseStreamID(id); err != nil {
return 0, errors.New(msgInvalidStreamID)
}
pos := sort.Search(len(g.pending), func(i int) bool {
return streamCmp(id, g.pending[i].id) <= 0
})
if len(g.pending) <= pos || g.pending[pos].id != id {
continue
}
g.pending = append(g.pending[:pos], g.pending[pos+1:]...)
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.pending {
if p.consumer == consumer {
n++
}
}
return n
}
func (g *streamGroup) copy() *streamGroup {
cns := map[string]consumer{}
for k, v := range g.consumers {
cns[k] = v
}
return &streamGroup{
// don't copy stream
lastID: g.lastID,
pending: g.pending,
consumers: cns,
}
}