-
Notifications
You must be signed in to change notification settings - Fork 1
/
channel.go
406 lines (362 loc) · 10.5 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
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
package chamqp
import (
"encoding/json"
"errors"
"fmt"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
type NotifyPublishSpec struct {
confirm chan amqp.Confirmation
}
type ConsumeSpec struct {
Queue string
Consumer string
DeliveryChan chan<- amqp.Delivery
AutoAck bool
Exclusive bool
NoLocal bool
NoWait bool
Args amqp.Table
ErrorChan chan<- error
}
type ExchangeDeclareSpec struct {
Name string
Kind string
Durable bool
AutoDelete bool
Internal bool
NoWait bool
Args amqp.Table
ErrorChan chan<- error
}
type QueueBindSpec struct {
Name string
Key string
Exchange string
NoWait bool
Args amqp.Table
ErrorChan chan<- error
}
type QueueDeclareSpec struct {
Name string
Durable bool
AutoDelete bool
Exclusive bool
NoWait bool
Args amqp.Table
QueueChan chan<- amqp.Queue
ErrorChan chan<- error
}
type Properties struct {
ContentType string // MIME content type
ContentEncoding string // MIME content encoding
DeliveryMode uint8 // Transient (0 or 1) or Persistent (2)
Priority uint8 // 0 to 9
CorrelationId string // correlation identifier
ReplyTo string // address to reply to (ex: RPC)
Expiration string // message expiration spec
MessageId string // message identifier
Timestamp time.Time // message timestamp
Type string // message type name
UserId string // creating user id - ex: "guest"
AppId string // creating application id
}
// Channel represents an AMQP channel. Used as a context for valid message
// Exchange. Errors on methods with this Channel will be detected and the
// channel will recreate itself.
type Channel struct {
ch *amqp.Channel
consumeSpecs []ConsumeSpec
exchangeDeclareSpecs []ExchangeDeclareSpec
queueBindSpecs []QueueBindSpec
queueDeclareSpecs []QueueDeclareSpec
notifyPublishSpec []NotifyPublishSpec
confirm bool
confirmNoWait bool
}
func (ch *Channel) connected(conn *amqp.Connection) error {
channel, err := conn.Channel()
if ch.confirm {
channel.Confirm(ch.confirmNoWait)
}
if err != nil {
ch.ch = nil
return err
}
ch.ch = channel
for _, spec := range ch.exchangeDeclareSpecs {
err := ch.applyExchangeDeclareSpec(spec)
if err != nil {
return err
}
}
for _, spec := range ch.queueDeclareSpecs {
err := ch.applyQueueDeclareSpec(spec)
if err != nil {
return err
}
}
for _, spec := range ch.queueBindSpecs {
err := ch.applyQueueBindSpec(spec)
if err != nil {
return err
}
}
for _, spec := range ch.consumeSpecs {
err := ch.applyConsumeSpec(spec)
if err != nil {
return err
}
}
for _, spec := range ch.notifyPublishSpec {
ch.applyNotifyPublishSpec(spec)
}
return nil
}
func (ch *Channel) disconnected() {
ch.ch = nil
}
func (ch *Channel) applyExchangeDeclareSpec(spec ExchangeDeclareSpec) error {
err := ch.ch.ExchangeDeclare(spec.Name, spec.Kind, spec.Durable, spec.AutoDelete, spec.Internal, spec.NoWait, spec.Args)
if err != nil {
if spec.ErrorChan != nil {
spec.ErrorChan <- err
}
return err
}
return nil
}
func (ch *Channel) applyQueueDeclareSpec(spec QueueDeclareSpec) error {
queue, err := ch.ch.QueueDeclare(spec.Name, spec.Durable, spec.AutoDelete, spec.Exclusive, spec.NoWait, spec.Args)
if err != nil {
if spec.ErrorChan != nil {
spec.ErrorChan <- err
}
return err
}
if spec.QueueChan != nil {
spec.QueueChan <- queue
}
return nil
}
func (ch *Channel) applyQueueBindSpec(spec QueueBindSpec) error {
err := ch.ch.QueueBind(spec.Name, spec.Key, spec.Exchange, spec.NoWait, spec.Args)
if err != nil {
if spec.ErrorChan != nil {
spec.ErrorChan <- err
}
spec.ErrorChan <- err
return err
}
return nil
}
func (ch *Channel) applyConsumeSpec(spec ConsumeSpec) error {
deliveries, err := ch.ch.Consume(spec.Queue, spec.Consumer, spec.AutoAck, spec.Exclusive, spec.NoLocal, spec.NoWait, spec.Args)
if err != nil {
if spec.ErrorChan != nil {
spec.ErrorChan <- err
}
return err
}
if spec.DeliveryChan != nil {
go shovel(deliveries, spec.DeliveryChan)
}
return nil
}
func (ch *Channel) applyNotifyPublishSpec(spec NotifyPublishSpec) {
subscribeChannel := make(chan amqp.Confirmation, 1)
go shovelConfirmation(subscribeChannel, spec.confirm)
ch.ch.NotifyPublish(subscribeChannel)
}
func (ch *Channel) ConsumeWithSpec(spec ConsumeSpec) {
ch.Consume(spec.Queue, spec.Consumer, spec.AutoAck, spec.Exclusive, spec.NoLocal, spec.NoWait, spec.Args, spec.DeliveryChan, spec.ErrorChan)
}
// Consume immediately starts delivering queued messages.
func (ch *Channel) Consume(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args amqp.Table, deliveryChan chan<- amqp.Delivery, errorChan chan<- error) {
spec := ConsumeSpec{
queue,
consumer,
deliveryChan,
autoAck,
exclusive,
noLocal,
noWait,
args,
errorChan,
}
ch.consumeSpecs = append(ch.consumeSpecs, spec)
if ch.ch != nil {
ch.applyConsumeSpec(spec)
}
}
// Publish sends a Publishing from the client to an Exchange on the server.
func (ch *Channel) Publish(exchange, key string, mandatory, immediate bool, msg amqp.Publishing) error {
if ch.ch == nil {
return fmt.Errorf("context has no channel")
}
return ch.ch.Publish(exchange, key, mandatory, immediate, msg)
}
func (ch *Channel) PublishJSONWithProperties(exchange, key string, mandatory, immediate bool, objectToBeSent interface{}, properties Properties) error {
if ch.ch == nil {
return fmt.Errorf("context has no channel")
}
payload, err := json.Marshal(objectToBeSent)
if err != nil {
return err
}
return ch.Publish(exchange, key, mandatory, immediate, amqp.Publishing{
ContentType: "application/json",
Body: payload,
ContentEncoding: properties.ContentEncoding,
DeliveryMode: properties.DeliveryMode,
Priority: properties.Priority,
CorrelationId: properties.CorrelationId,
ReplyTo: properties.ReplyTo,
Expiration: properties.Expiration,
MessageId: properties.MessageId,
Timestamp: properties.Timestamp,
Type: properties.Type,
UserId: properties.UserId,
AppId: properties.AppId,
})
}
func (ch *Channel) PublishJSON(exchange, key string, mandatory, immediate bool, objectToBeSent interface{}) error {
if ch.ch == nil {
return fmt.Errorf("context has no channel")
}
payload, err := json.Marshal(objectToBeSent)
if err != nil {
return err
}
return ch.Publish(exchange, key, mandatory, immediate, amqp.Publishing{
ContentType: "application/json",
Body: payload,
})
}
func (ch *Channel) PublishJsonAndWaitForResponse(replyQueueName, correlationId string, response, request interface{}, exchange, key string, mandatory, immediate bool, responseTimeout time.Duration) error {
if ch.ch == nil {
return errors.New("channel not present")
}
defer ch.ch.Cancel(replyQueueName+".consumer", false)
replyQueue, err := ch.ch.Consume(replyQueueName, replyQueueName+".consumer", true, false, false, false, nil)
if err != nil {
return err
}
payload, err := json.Marshal(request)
if err != nil {
return err
}
msg := amqp.Publishing{
Headers: amqp.Table{},
ContentType: "application/json",
ReplyTo: replyQueueName,
CorrelationId: correlationId,
Body: payload,
}
err = ch.Publish(exchange, key, mandatory, immediate, msg)
if err != nil {
return err
}
timer := time.NewTimer(responseTimeout)
for {
select {
case reply := <-replyQueue:
if correlationId != "" && reply.CorrelationId != correlationId {
fmt.Println("skipping, not for me")
continue
}
err := json.Unmarshal(reply.Body, response)
if err != nil {
continue
}
return err
case <-timer.C:
return errors.New("timed out")
}
}
}
func (ch *Channel) ExchangeDeclareWithSpec(spec ExchangeDeclareSpec) {
ch.ExchangeDeclare(spec.Name, spec.Kind, spec.Durable, spec.AutoDelete, spec.Internal, spec.NoWait, spec.Args, spec.ErrorChan)
}
// ExchangeDeclare declares an Exchange on the server. If the Exchange does not
// already exist, the server will create it. If the Exchange exists, the server
// verifies that it is of the provided type, durability and auto-delete flags.
func (ch *Channel) ExchangeDeclare(name, kind string, durable, autoDelete, internal, noWait bool, args amqp.Table, errorChan chan<- error) {
spec := ExchangeDeclareSpec{
name,
kind,
durable,
autoDelete,
internal,
noWait,
args,
errorChan,
}
ch.exchangeDeclareSpecs = append(ch.exchangeDeclareSpecs, spec)
if ch.ch != nil {
ch.applyExchangeDeclareSpec(spec)
}
}
func (ch *Channel) QueueBindWithSpec(q QueueBindSpec) {
ch.QueueBind(q.Name, q.Key, q.Exchange, q.NoWait, q.Args, q.ErrorChan)
}
// QueueBind binds an Exchange to a Queue so that publishings to the Exchange
// will be routed to the Queue when the publishing routing Key matches the
// binding routing Key.
func (ch *Channel) QueueBind(name, key, exchange string, noWait bool, args amqp.Table, errorChan chan<- error) {
spec := QueueBindSpec{
name,
key,
exchange,
noWait,
args,
errorChan,
}
ch.queueBindSpecs = append(ch.queueBindSpecs, spec)
if ch.ch != nil {
ch.applyQueueBindSpec(spec)
}
}
func (ch *Channel) QueueDeclareWithSpec(q QueueDeclareSpec) {
ch.QueueDeclare(q.Name, q.Durable, q.AutoDelete, q.Exclusive, q.NoWait, q.Args, q.QueueChan, q.ErrorChan)
}
// QueueDeclare declares a Queue to hold messages and deliver to consumers.
// Declaring creates a Queue if it doesn't already exist, or ensures that an
// existing Queue matches the same parameters.
func (ch *Channel) QueueDeclare(name string, durable, autoDelete, exclusive, noWait bool, args amqp.Table, queueChan chan<- amqp.Queue, errorChan chan<- error) {
spec := QueueDeclareSpec{
name,
durable,
autoDelete,
exclusive,
noWait,
args,
queueChan,
errorChan,
}
ch.queueDeclareSpecs = append(ch.queueDeclareSpecs, spec)
if ch.ch != nil {
ch.applyQueueDeclareSpec(spec)
}
}
func (ch *Channel) NotifyPublish() chan amqp.Confirmation {
notifyPublishChan := make(chan amqp.Confirmation, 1)
spec := NotifyPublishSpec{notifyPublishChan}
ch.notifyPublishSpec = append(ch.notifyPublishSpec, spec)
if ch.ch != nil {
ch.applyNotifyPublishSpec(spec)
}
return notifyPublishChan
}
// Shovel takes messages from `src` and puts them into `dest`.
func shovel(src <-chan amqp.Delivery, dest chan<- amqp.Delivery) {
for msg := range src {
dest <- msg
}
}
func shovelConfirmation(src, dest chan amqp.Confirmation) {
for msg := range src {
dest <- msg
}
}