This repository has been archived by the owner on Mar 29, 2022. It is now read-only.
/
channel.go
349 lines (274 loc) · 6.94 KB
/
channel.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
package server
import (
"fmt"
"os"
"sync"
"sync/atomic"
"github.com/NeowayLabs/wabbit"
"github.com/NeowayLabs/wabbit/utils"
amqp "github.com/rabbitmq/amqp091-go"
)
type (
Channel struct {
*VHost
unacked []unackData
muUnacked *sync.RWMutex
consumers map[string]consumer
muConsumer *sync.RWMutex
_ uint32
deliveryTagCounter uint64
confirm bool
publishListeners []chan wabbit.Confirmation
muPublishListeners *sync.RWMutex
errSpread *utils.ErrBroadcast
}
unackData struct {
d wabbit.Delivery
q *Queue
}
consumer struct {
tag string
deliveries chan wabbit.Delivery
done chan bool
}
)
var consumerSeq uint64
func uniqueConsumerTag() string {
return fmt.Sprintf("ctag-%s-%d", os.Args[0], atomic.AddUint64(&consumerSeq, 1))
}
func NewChannel(vhost *VHost) *Channel {
c := Channel{
VHost: vhost,
unacked: make([]unackData, 0, QueueMaxLen),
muUnacked: &sync.RWMutex{},
muConsumer: &sync.RWMutex{},
consumers: make(map[string]consumer),
muPublishListeners: &sync.RWMutex{},
errSpread: utils.NewErrBroadcast(),
}
return &c
}
func (ch *Channel) QueueInspect(name string) (wabbit.Queue, error) {
q, ok := ch.queues[name]
if ok {
return q, nil
}
return nil, fmt.Errorf("no queue named %s", name)
}
func (ch *Channel) Confirm(noWait bool) error {
ch.confirm = true
return nil
}
func (ch *Channel) NotifyPublish(confirm chan wabbit.Confirmation) chan wabbit.Confirmation {
aux := make(chan wabbit.Confirmation, 2<<8)
ch.muPublishListeners.Lock()
ch.publishListeners = append(ch.publishListeners, aux)
ch.muPublishListeners.Unlock()
// aux is set to the maximum size of a queue: 512.
// In theory it is possible that a publisher could deliver >512 messages
// on a channel by sending to multiple queues, in which case Publish()
// will block trying to send confirmations. However this is a pathological
// case which can be ignored since there should be an attached listener
// on the other end of the confirm channel. In any case, a buffered queue,
// while seemingly inefficient is a good enough solution to make sure
// Publish() doesn't block.
go func() {
for c := range aux {
confirm <- c
}
close(confirm)
}()
return confirm
}
func (ch *Channel) Publish(exc, route string, msg []byte, opt wabbit.Option) error {
hdrs, _ := opt["headers"].(amqp.Table)
messageId, _ := opt["messageId"].(string)
contentType, _ := opt["contentType"].(string)
d := NewDelivery(ch,
msg,
atomic.AddUint64(&ch.deliveryTagCounter, 1),
messageId,
wabbit.Option(hdrs),
contentType,
)
err := ch.VHost.Publish(exc, route, d, nil)
if err != nil {
return err
}
if ch.confirm {
confirm := Confirmation{ch.deliveryTagCounter, true}
for _, l := range ch.publishListeners {
l <- confirm
}
}
return nil
}
// Consume starts a fake consumer of queue
func (ch *Channel) Consume(queue, consumerName string, _ wabbit.Option) (<-chan wabbit.Delivery, error) {
var (
c consumer
)
if consumerName == "" {
consumerName = uniqueConsumerTag()
}
c = consumer{
tag: consumerName,
deliveries: make(chan wabbit.Delivery),
done: make(chan bool),
}
ch.muConsumer.RLock()
if c2, found := ch.consumers[consumerName]; found {
c2.done <- true
}
ch.consumers[consumerName] = c
ch.muConsumer.RUnlock()
q, ok := ch.queues[queue]
if !ok {
return nil, fmt.Errorf("Unknown queue '%s'", queue)
}
go func() {
for {
select {
case <-c.done:
close(c.deliveries)
return
case d := <-q.data:
// since we keep track of unacked messages for
// the channel, we need to rebind the delivery
// to the consumer channel.
d = NewDelivery(ch, d.Body(), d.DeliveryTag(), d.MessageId(), d.Headers(), d.ContentType())
ch.addUnacked(d, q)
// sub-select required for cases when
// client attempts to close the channel
// concurrently with re-enqueues of messages
select {
case c.deliveries <- d:
case <-c.done:
close(c.deliveries)
return
}
}
}
}()
return c.deliveries, nil
}
func (ch *Channel) addUnacked(d wabbit.Delivery, q *Queue) {
ch.muUnacked.Lock()
defer ch.muUnacked.Unlock()
ch.unacked = append(ch.unacked, unackData{d, q})
}
func (ch *Channel) enqueueUnacked() {
ch.muUnacked.Lock()
defer ch.muUnacked.Unlock()
for _, ud := range ch.unacked {
ud.q.data <- ud.d
}
ch.unacked = make([]unackData, 0, QueueMaxLen)
}
func (ch *Channel) Ack(tag uint64, multiple bool) error {
var (
pos int
ud unackData
)
if !multiple {
ch.muUnacked.Lock()
defer ch.muUnacked.Unlock()
found := false
for pos, ud = range ch.unacked {
if ud.d.DeliveryTag() == tag {
found = true
break
}
}
if !found {
return fmt.Errorf("Delivery tag %d not found", tag)
}
ch.unacked = ch.unacked[:pos+copy(ch.unacked[pos:], ch.unacked[pos+1:])]
} else {
ackMessages := make([]uint64, 0, QueueMaxLen)
ch.muUnacked.Lock()
found := false
for _, ud = range ch.unacked {
udTag := ud.d.DeliveryTag()
if udTag <= tag {
found = true
ackMessages = append(ackMessages, udTag)
}
}
ch.muUnacked.Unlock()
if !found {
return fmt.Errorf("Delivery tag %d not found", tag)
}
for _, udTag := range ackMessages {
ch.Ack(udTag, false)
}
}
return nil
}
func (ch *Channel) Nack(tag uint64, multiple bool, requeue bool) error {
var (
pos int
ud unackData
)
if !multiple {
ch.muUnacked.Lock()
defer ch.muUnacked.Unlock()
found := false
for pos, ud = range ch.unacked {
if ud.d.DeliveryTag() == tag {
found = true
break
}
}
if !found {
return fmt.Errorf("Delivery tag %d not found", tag)
}
if requeue {
ud.q.data <- ud.d
}
ch.unacked = ch.unacked[:pos+copy(ch.unacked[pos:], ch.unacked[pos+1:])]
} else {
nackMessages := make([]uint64, 0, QueueMaxLen)
for _, ud = range ch.unacked {
udTag := ud.d.DeliveryTag()
if udTag <= tag {
nackMessages = append(nackMessages, udTag)
}
}
for _, udTag := range nackMessages {
ch.Nack(udTag, false, requeue)
}
}
return nil
}
func (ch *Channel) Reject(tag uint64, requeue bool) error {
return ch.Nack(tag, false, requeue)
}
func (ch *Channel) Close() error {
ch.muConsumer.Lock()
defer ch.muConsumer.Unlock()
for _, consumer := range ch.consumers {
consumer.done <- true
}
ch.consumers = make(map[string]consumer)
// enqueue shall happens only after every consumer of this channel
// has stopped.
ch.enqueueUnacked()
ch.muPublishListeners.Lock()
defer ch.muPublishListeners.Unlock()
for _, c := range ch.publishListeners {
close(c)
}
ch.publishListeners = []chan wabbit.Confirmation{}
return nil
}
// NotifyClose publishs notifications about errors in the given channel
func (ch *Channel) NotifyClose(c chan wabbit.Error) chan wabbit.Error {
ch.errSpread.Add(c)
return c
}
// Cancel closes deliveries for all consumers
func (ch *Channel) Cancel(consumer string, noWait bool) error {
ch.Close()
return nil
}