-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathqueue.go
97 lines (80 loc) · 1.43 KB
/
queue.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
package subee
import (
"context"
"time"
)
type queuedMessage interface {
Acknowledger
Count() int
}
type singleMessage struct {
Message
}
func (s *singleMessage) Count() int { return 1 }
type multiMessages struct {
Ctx context.Context
Msgs []Message
}
func (m *multiMessages) Ack() {
for _, msg := range m.Msgs {
msg.Ack()
}
}
func (m *multiMessages) Nack() {
for _, msg := range m.Msgs {
msg.Nack()
}
}
func (m *multiMessages) Count() int { return len(m.Msgs) }
func createBufferedQueue(
createCtx func() context.Context,
chunkSize int,
flushInterval time.Duration,
) (
chan<- Message,
<-chan *multiMessages,
) {
inCh := make(chan Message, chunkSize)
outCh := make(chan *multiMessages)
go func() {
defer close(outCh)
for {
msgs, opened := buffering(inCh, chunkSize, flushInterval)
if len(msgs) > 0 {
outCh <- &multiMessages{
Ctx: createCtx(),
Msgs: msgs,
}
}
if !opened {
break
}
}
}()
return inCh, outCh
}
func buffering(
msgCh <-chan Message,
chunkSize int,
flushInterval time.Duration,
) (msgs []Message, opened bool) {
msgs = make([]Message, 0, chunkSize)
opened = true
ctx, cancel := context.WithTimeout(context.Background(), flushInterval)
defer cancel()
for {
select {
case msg, ok := <-msgCh:
if !ok {
opened = false
return
}
msgs = append(msgs, msg)
if len(msgs) >= chunkSize {
return
}
case <-ctx.Done():
return
}
}
}