-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathconsumer.go
135 lines (113 loc) · 2.49 KB
/
consumer.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
package borges
import (
"sync"
"time"
queue "gopkg.in/src-d/go-queue.v1"
amqp "gopkg.in/src-d/go-queue.v1/amqp"
)
// Consumer consumes jobs from a queue and uses multiple workers to process
// them.
type Consumer struct {
Notifiers struct {
QueueError func(error)
}
WorkerPool *WorkerPool
Queue queue.Queue
quit chan struct{}
done chan struct{}
iter queue.JobIter
m *sync.Mutex
}
// NewConsumer creates a new consumer.
func NewConsumer(queue queue.Queue, pool *WorkerPool) *Consumer {
return &Consumer{
WorkerPool: pool,
Queue: queue,
m: &sync.Mutex{},
}
}
// Start initializes the consumer and starts it, blocking until it is stopped.
func (c *Consumer) Start() error {
c.m.Lock()
c.quit = make(chan struct{})
c.done = make(chan struct{})
c.m.Unlock()
defer func() { close(c.done) }()
for {
select {
case <-c.quit:
return c.WorkerPool.Stop()
default:
if err := c.consumeQueue(c.Queue); err != nil {
c.notifyQueueError(err)
}
c.backoff()
}
}
}
// Stop stops the consumer. Note that it does not close the underlying queue
// and worker pool. It blocks until the consumer has actually stopped.
func (c *Consumer) Stop() {
c.m.Lock()
close(c.quit)
if err := c.iter.Close(); err != nil {
c.notifyQueueError(err)
}
c.m.Unlock()
<-c.done
}
func (c *Consumer) backoff() {
time.Sleep(time.Second * 5)
}
func (c *Consumer) reject(j *queue.Job, origErr error) {
c.notifyQueueError(origErr)
if err := j.Reject(false); err != nil {
c.notifyQueueError(err)
}
}
func (c *Consumer) consumeQueue(q queue.Queue) error {
var err error
c.m.Lock()
c.iter, err = c.Queue.Consume(c.WorkerPool.Len())
c.m.Unlock()
if err != nil {
return err
}
return c.consumeJobIter(c.iter)
}
func (c *Consumer) consumeJobIter(iter queue.JobIter) error {
for {
j, err := iter.Next()
if queue.ErrEmptyJob.Is(err) || amqp.ErrRetrievingHeader.Is(err) {
c.notifyQueueError(err)
continue
}
if queue.ErrAlreadyClosed.Is(err) {
return nil
}
if err != nil {
if err := iter.Close(); err != nil {
c.notifyQueueError(err)
}
return err
}
if err := c.consumeJob(j); err != nil {
c.notifyQueueError(err)
}
}
}
func (c *Consumer) consumeJob(j *queue.Job) error {
job := &Job{}
if err := j.Decode(job); err != nil {
c.reject(j, err)
return err
}
c.WorkerPool.Do(&WorkerJob{job, j, c.Queue})
return nil
}
func (c *Consumer) notifyQueueError(err error) {
if c.Notifiers.QueueError == nil {
return
}
c.Notifiers.QueueError(err)
}