-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsubscriber.go
213 lines (197 loc) · 5.15 KB
/
subscriber.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
package amqp
import (
"context"
"reflect"
"sync"
"github.com/devimteam/amqp/codecs"
"github.com/devimteam/amqp/conn"
"github.com/pkg/errors"
"github.com/streadway/amqp"
)
type (
Subscriber struct {
conn *conn.Connection
observer *observer
opts subscriberOptions
}
SubscriberOption func(*Subscriber)
)
func newSubscriber(ctx context.Context, conn *conn.Connection, opts ...SubscriberOption) *Subscriber {
s := Subscriber{}
s.opts = defaultSubOptions()
for _, opt := range opts {
opt(&s)
}
s.conn = conn
s.observer = newObserver(ctx, s.conn, s.opts.observerOpts...)
return &s
}
func (s Subscriber) Subscribe(ctx context.Context, exchangeName, queueName string, dataType interface{}, cfg Consumer) <-chan Event {
eventChan := make(chan Event, s.opts.channelBuffer)
channel := s.observer.channel()
go s.listen(ctx, channel, exchangeName, queueName, dataType, eventChan, cfg)
return eventChan
}
func (s Subscriber) SubscribeToQueue(ctx context.Context, queueName string, dataType interface{}, cfg Consumer) <-chan Event {
return s.Subscribe(ctx, "", queueName, dataType, cfg)
}
func (s Subscriber) SubscribeToExchange(ctx context.Context, exchangeName string, dataType interface{}, cfg Consumer) <-chan Event {
return s.Subscribe(ctx, exchangeName, "", dataType, cfg)
}
func (s Subscriber) listen(ctx context.Context, channel *Channel, exchangeName, queueName string, dataType interface{}, eventChan chan<- Event, cfg Consumer) {
for {
select {
case <-ctx.Done():
if channel != nil {
s.observer.release(channel)
}
return
default:
if s.opts.wait.flag {
if err := s.conn.NotifyConnected(s.opts.wait.timeout); err != nil {
_ = s.opts.log.Log(err)
}
}
deliveryCh, err := s.prepareDeliveryChan(channel, exchangeName, queueName, cfg)
if err != nil {
_ = s.opts.log.Log(err)
continue
}
s.workersPool(ctx, queueName, deliveryCh, dataType, eventChan)
}
}
}
func (s Subscriber) prepareDeliveryChan(
channel *Channel, exchangeName, queueName string, cfg Consumer,
) (
<-chan amqp.Delivery, error,
) {
if queueName == "" {
queue, err := channel.declareQueue(Queue{
AutoDelete: true,
Durable: false,
})
if err != nil {
return nil, errors.Wrap(err, "declare queue")
}
err = channel.bind(Binding{
Queue: queue.Name,
Exchange: exchangeName,
Key: "",
Args: nil,
NoWait: false,
})
if err != nil {
return nil, errors.Wrapf(err, "bind %s to %s", queue.Name, exchangeName)
}
}
if cfg.LimitCount > 0 || cfg.LimitSize > 0 {
err := channel.qos(cfg.LimitCount, cfg.LimitSize)
if err != nil {
return nil, errors.Wrap(err, "channel qos err")
}
}
ch, err := channel.consume(queueName, cfg)
if err != nil {
return nil, errors.Wrap(err, "channel consume err")
}
return ch, nil
}
// workersPool wraps processEvents with WorkerPool pattern.
func (s Subscriber) workersPool(
ctx context.Context,
queueName string,
deliveryCh <-chan amqp.Delivery,
dataType interface{},
eventChan chan<- Event,
) {
var wg sync.WaitGroup
wg.Add(s.opts.workers)
for i := 0; i < s.opts.workers; i++ {
go func() {
s.processEvents(ctx, queueName, deliveryCh, dataType, eventChan)
wg.Done()
}()
}
wg.Wait()
}
func (s Subscriber) processEvents(
ctx context.Context,
queueName string,
deliveryCh <-chan amqp.Delivery,
dataType interface{},
eventChan chan<- Event,
) {
processedAll := false
for {
select {
case d, ok := <-deliveryCh:
if !ok {
processedAll = true
return
}
s.processEvent(d, dataType, eventChan)
case <-ctx.Done():
if (s.opts.processAll && processedAll) || !s.opts.processAll {
close(eventChan)
return
}
}
}
}
func (s Subscriber) processEvent(d amqp.Delivery, dataType interface{}, eventChan chan<- Event) {
err := s.checkEvent(d)
if err != nil {
err = s.errorBefore(d, err)
_ = s.opts.log.Log(err)
e := d.Nack(false, true)
if e != nil {
_ = s.opts.log.Log(errors.Errorf("nack delivery: %v because of %v", e, err))
}
return
}
ev, err := s.handleEvent(d, dataType)
if err != nil {
err = s.errorBefore(d, err)
_ = s.opts.log.Log(err)
e := d.Nack(false, true)
if e != nil {
_ = s.opts.log.Log(errors.Errorf("nack delivery: %v because of %v", e, err))
}
return
}
eventChan <- ev
}
func (s Subscriber) checkEvent(d amqp.Delivery) error {
priorityOk := s.opts.msgOpts.minPriority <= d.Priority && d.Priority <= s.opts.msgOpts.maxPriority
if !priorityOk {
return NotAllowedPriority
}
return nil
}
func (s Subscriber) handleEvent(d amqp.Delivery, dataType interface{}) (ev Event, err error) {
ctx := context.Background()
for _, before := range s.opts.msgOpts.deliveryBefore {
ctx = before(ctx, &d)
}
ev.Context = ctx
ev.Delivery = d
codec, ok := codecs.Register.Get(d.ContentType)
if !ok {
return ev, CodecNotFound
}
data := reflect.New(reflect.Indirect(reflect.ValueOf(dataType)).Type()).Interface()
err = codec.Decode(d.Body, data)
if err != nil {
return
}
ev.Data = data
return
}
// ErrorBefore allows user to update error messages before logging.
func (s Subscriber) errorBefore(d amqp.Delivery, err error) error {
for _, before := range s.opts.errorBefore {
err = before(d, err)
}
return err
}