-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlepus.go
More file actions
238 lines (202 loc) · 5.32 KB
/
Copy pathlepus.go
File metadata and controls
238 lines (202 loc) · 5.32 KB
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
package lepus
import (
"errors"
"fmt"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/streadway/amqp"
)
type info struct {
state int32
err error
}
// Channel is a wrapper around async AMQP channel
type Channel struct {
*amqp.Channel
messageCount uint64
midPrefix string
sm sync.Map
timeout time.Duration
}
// SyncChannel returns channel wrapper
func SyncChannel(ch *amqp.Channel, err error) (*Channel, error) {
if err != nil {
return nil, err
}
if err := ch.Confirm(false); err != nil {
return nil, err
}
c := &Channel{
Channel: ch,
midPrefix: "lepus-" + strconv.Itoa(int(time.Now().Unix())),
timeout: 2 * time.Second,
}
go func() {
pubc := ch.NotifyPublish(make(chan amqp.Confirmation))
for pub := range pubc {
smkey := "DeliveryTag-" + strconv.Itoa(int(pub.DeliveryTag))
if v, ok := c.sm.Load(smkey); ok {
v.(chan info) <- info{
state: int32(StatePublished),
}
}
}
}()
go func() {
retc := ch.NotifyReturn(make(chan amqp.Return))
for ret := range retc {
smkey := ret.MessageId + ret.CorrelationId
if v, ok := c.sm.Load(smkey); ok {
v.(chan info) <- info{
state: int32(StateReturned),
}
}
}
}()
go func() {
err := <-ch.NotifyClose(make(chan *amqp.Error))
c.sm.Range(func(k, v interface{}) bool {
v.(chan info) <- info{
state: int32(StateClosed),
err: err,
}
return true
})
}()
return c, nil
}
// WithTimeout sets publish wait timeout
func (c *Channel) WithTimeout(d time.Duration) {
c.timeout = d
}
// PublishAndWait sends message to queue and waits for response
func (c *Channel) PublishAndWait(exchange, key string, mandatory, immediate bool, msg amqp.Publishing) (State, error) {
mid := atomic.AddUint64(&c.messageCount, 1)
if msg.MessageId == "" {
msg.MessageId = c.midPrefix + "-" + strconv.Itoa(int(mid))
}
if msg.Timestamp.IsZero() {
msg.Timestamp = time.Now()
}
if msg.CorrelationId == "" {
msg.CorrelationId = strconv.Itoa(int(mid))
}
mkey := msg.MessageId + msg.CorrelationId
tkey := "DeliveryTag-" + strconv.Itoa(int(mid))
sch := make(chan info)
c.sm.Store(mkey, sch)
c.sm.Store(tkey, sch)
defer func() {
c.sm.Delete(mkey)
c.sm.Delete(tkey)
}()
err := c.Publish(exchange, key, mandatory, immediate, msg)
if err != nil {
return StateUnknown, err
}
timer := time.NewTimer(c.timeout)
defer timer.Stop()
for {
select {
case <-timer.C:
return StateTimeout, errors.New("message publishing timeout reached")
case inf := <-sch:
return State(inf.state), inf.err
}
}
}
// ConsumeMessages returns chan of wrapped messages from queue
func (c *Channel) ConsumeMessages(queue, consumer string, autoAck, exclusive, noLocal, noWait bool, args amqp.Table) (<-chan Delivery, error) {
d, err := c.Consume(queue, consumer, autoAck, exclusive, noLocal, noWait, args)
if err != nil {
return nil, err
}
wd := make(chan Delivery)
go func() {
for msg := range d {
msg.Acknowledger = c
wd <- Delivery{msg, 0}
}
}()
return wd, nil
}
// Delivery is a superset of amqp.Delivery
type Delivery struct {
amqp.Delivery
acked int32
}
// Nack is a concurrent safe wrapper around standart AMQP Nack
func (d *Delivery) Nack(multiple, requeue bool) error {
if atomic.CompareAndSwapInt32(&d.acked, 0, 1) {
err := d.Delivery.Nack(multiple, requeue)
if err != nil {
atomic.StoreInt32(&d.acked, 0)
}
return err
}
return nil
}
// Ack is a concurrent safe wrapper around standart AMQP Ack
func (d *Delivery) Ack(multiple bool) error {
if atomic.CompareAndSwapInt32(&d.acked, 0, 1) {
err := d.Delivery.Ack(multiple)
if err != nil {
atomic.StoreInt32(&d.acked, 0)
}
return err
}
return nil
}
// Reject is a concurrent safe wrapper around standart AMQP Reject
func (d *Delivery) Reject(requeue bool) error {
if atomic.CompareAndSwapInt32(&d.acked, 0, 1) {
err := d.Delivery.Reject(requeue)
if err != nil {
atomic.StoreInt32(&d.acked, 0)
}
return err
}
return nil
}
// NackDelayed nacks message without requeue and publishes it again
// without modification back to tail of queue
func (d *Delivery) NackDelayed(multiple, mandatory, immediate bool) (State, error) {
ch, ok := d.Delivery.Acknowledger.(*Channel)
if !ok {
return StateUnknown, errors.New("Acknowledger is not of type *lepus.Channel")
}
err := d.Nack(multiple, false)
if err != nil {
return StateUnknown, err
}
return ch.PublishAndWait(d.Delivery.Exchange, d.Delivery.RoutingKey, mandatory, immediate, amqp.Publishing{
Headers: d.Delivery.Headers,
ContentType: d.Delivery.ContentType,
ContentEncoding: d.Delivery.ContentEncoding,
DeliveryMode: d.Delivery.DeliveryMode,
Priority: d.Delivery.Priority,
CorrelationId: d.Delivery.CorrelationId,
ReplyTo: d.Delivery.ReplyTo,
Expiration: d.Delivery.Expiration,
MessageId: d.Delivery.MessageId,
Timestamp: d.Delivery.Timestamp,
Type: d.Delivery.Type,
UserId: d.Delivery.UserId,
AppId: d.Delivery.AppId,
Body: d.Delivery.Body,
})
}
// MustPublish can be used as a wrapper around `PublishAndWait` and
// `NackDelayed` methods if you didn't want to process error and state
// separately.
func MustPublish(s State, err error) error {
if err != nil {
return err
}
if s != StatePublished {
return fmt.Errorf("Message publishing failed. Result state: %s", s)
}
return nil
}