/
queue.go
239 lines (196 loc) · 5.54 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
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
package cluster
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"go.etcd.io/etcd/api/v3/mvccpb"
v3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/client/v3/concurrency"
"github.com/beihai0xff/pudding/pkg/log"
)
// Queue is a distributed queue implementation based on etcd
type Queue interface {
// Produce adds an element to the queue.
Produce(m *Message) (string, error)
// Consume returns the first element in the queue.
Consume(ctx context.Context) (*Message, error)
// Commit removes the element from the queue.
Commit(msg *Message) error
}
// Message is the unit of the queue
type Message struct {
// Key is the unique identifier of the message
Key string
// Value is the content of the message
Value string
// the key is unique in the queue
Unique bool
}
// queue implements a single-reader, multi-writer distributed queue.
// /namespace/topic/msg/key (value: value)
// /namespace/topic/unacked (value: consumer_id, rev)
// /namespace/topic/consumer (mutex)
type queue struct {
cluster *cluster
client *v3.Client
topic string
consumerMutex Mutex
consumerID string
}
// Queue creates a new queue.
func (c *cluster) Queue(topic string) (Queue, error) {
return newQueue(c, topic)
}
func newQueue(cluster *cluster, topic string) (*queue, error) {
q := queue{
cluster: cluster,
client: cluster.client,
topic: topic,
consumerID: uuid.New().String(),
}
if err := q.newMutex(); err != nil {
return nil, err
}
return &q, nil
}
func (q *queue) newMutex() error {
m, err := q.cluster.Mutex(q.getConsumerLockPath(), 10*time.Second)
if err != nil {
return err
}
q.consumerMutex = m
return nil
}
func (q *queue) Produce(m *Message) (string, error) {
messageID := m.Key
if !m.Unique {
// the message do not need unique, add an uuid to make it won't conflict with other messages
messageID = fmt.Sprintf("%s/%s", messageID, uuid.New().String())
}
// if the messageID is non-unique, an error will be returned
if err := putNewKV(q.client.KV, q.getMsgPath()+messageID, m.Value, v3.NoLease); err != nil {
return "", err
}
return messageID, nil
}
// Consume returns Produce()'d elements in FIFO order. If the
// queue is empty, Consume blocks until elements are available.
//
//nolint:gocyclo
func (q *queue) Consume(ctx context.Context) (*Message, error) {
for {
log.Debugf("try to get message from the topic [%s]", q.topic)
if !q.consumerMutex.IsLocked() {
// wait for the lock, only one consumer can consume the message
if err := q.consumerMutex.Lock(ctx); err != nil {
return nil, err
}
}
resp, err := q.client.KV.Get(ctx, q.getMsgPath(), v3.WithFirstRev()...)
if err != nil {
return nil, err
}
if len(resp.Kvs) != 0 {
kv := resp.Kvs[0]
rev, err := q.tryUnackMessage(kv)
if err != nil {
return nil, err
}
if rev != 0 {
log.Debugf("message [%s] has been locked by this consumer, "+
"wait for the consumer to commit the message", string(kv.Key))
_, err := waitKeyEvents(q.client, q.getUnAckedPath(), rev, []mvccpb.Event_EventType{mvccpb.DELETE})
if err != nil {
return nil, err
}
continue
}
return q.message(kv), nil
}
log.Infof("no message in the topic [%s] , wait for new message", q.topic)
ev, err := waitPrefixEvents(
q.client,
q.getMsgPath(),
resp.Header.Revision,
[]mvccpb.Event_EventType{mvccpb.PUT})
if err != nil {
return nil, err
}
// If watch type is PUT, it indicates new data has been stored to the key.
return q.message(ev.Kv), nil
}
}
func (q *queue) Commit(msg *Message) error {
key := fmt.Sprintf("%s%s", q.getMsgPath(), msg.Key)
_, err := concurrency.NewSTM(q.client, func(stm concurrency.STM) error {
rev := stm.Rev(key)
// the message has been consumed
if rev == 0 {
return nil
}
stm.Del(q.getUnAckedPath())
stm.Del(key)
return nil
})
return err
}
// tryUnackMessage try to lock the message
// if the message has been locked, return false
func (q *queue) tryUnackMessage(kv *mvccpb.KeyValue) (int64, error) {
var rev int64
_, err := concurrency.NewSTM(q.client, func(stm concurrency.STM) error {
rev = stm.Rev(q.getUnAckedPath())
if rev != 0 {
v := unAckedValue{}
v.parse(stm.Get(q.getUnAckedPath()))
// the message has been locked by the consumer
// need to wait for the consumer to commit the message
if v.ConsumerID == q.consumerID {
// return the rev of the message
return nil
}
// the message has been locked by other consumer
// but the consumer has not commit the message and the consumer is dead
// so we can lock the message and reconsume it
rev = 0
}
v := unAckedValue{
ConsumerID: q.consumerID,
Rev: kv.CreateRevision,
}
stm.Put(q.getUnAckedPath(), v.jsonFormat())
return nil
})
return rev, err
}
func (q *queue) message(kv *mvccpb.KeyValue) *Message {
msg := Message{
Key: strings.TrimPrefix(string(kv.Key), q.getMsgPath()),
Value: string(kv.Value),
}
log.Debugf("get message [%s] from the topic [%s]", msg.Key, q.topic)
return &msg
}
func (q *queue) getMsgPath() string {
return fmt.Sprintf("%s/msg/", q.topic)
}
func (q *queue) getUnAckedPath() string {
return fmt.Sprintf("%s/unacked", q.topic)
}
func (q *queue) getConsumerLockPath() string {
return fmt.Sprintf("%s/consumer", q.topic)
}
type unAckedValue struct {
ConsumerID string `json:"consumer_id"`
Rev int64 `json:"rev"`
}
func (v *unAckedValue) jsonFormat() string {
b, _ := json.Marshal(v)
return string(b)
}
func (v *unAckedValue) parse(s string) {
_ = json.Unmarshal([]byte(s), v)
}