-
Notifications
You must be signed in to change notification settings - Fork 46
/
client.go
291 lines (247 loc) · 6.2 KB
/
client.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
package cony
import (
"errors"
"sync"
"sync/atomic"
"time"
"github.com/streadway/amqp"
)
const (
noRun = iota
run
)
var (
// ErrNoConnection is an indicator that currently there is no connection
// available
ErrNoConnection = errors.New("No connection available")
)
// ClientOpt is a Client's functional option type
type ClientOpt func(*Client)
// Client is a Main AMQP client wrapper
type Client struct {
addr string
declarations []Declaration
consumers map[*Consumer]struct{}
publishers map[*Publisher]struct{}
errs chan error
blocking chan amqp.Blocking
run int32 // bool
conn atomic.Value //*amqp.Connection
bo Backoffer
attempt int32
l sync.Mutex
config amqp.Config
}
// Declare used to declare queues/exchanges/bindings.
// Declaration is saved and will be re-run every time Client gets connection
func (c *Client) Declare(d []Declaration) {
c.l.Lock()
defer c.l.Unlock()
c.declarations = append(c.declarations, d...)
if ch, err := c.channel(); err == nil {
for _, declare := range d {
declare(ch)
}
}
}
// Consume used to declare consumers
func (c *Client) Consume(cons *Consumer) {
c.l.Lock()
defer c.l.Unlock()
c.consumers[cons] = struct{}{}
if ch, err := c.channel(); err == nil {
go cons.serve(c, ch)
}
}
func (c *Client) deleteConsumer(cons *Consumer) {
c.l.Lock()
defer c.l.Unlock()
delete(c.consumers, cons)
}
// Publish used to declare publishers
func (c *Client) Publish(pub *Publisher) {
c.l.Lock()
defer c.l.Unlock()
c.publishers[pub] = struct{}{}
if ch, err := c.channel(); err == nil {
go pub.serve(c, ch)
}
}
func (c *Client) deletePublisher(pub *Publisher) {
c.l.Lock()
defer c.l.Unlock()
delete(c.publishers, pub)
}
// Errors returns AMQP connection level errors. Default buffer size is 100.
// Messages will be dropped in case if receiver can't keep up
func (c *Client) Errors() <-chan error {
return c.errs
}
// Blocking notifies the server's TCP flow control of the Connection. Default
// buffer size is 10. Messages will be dropped in case if receiver can't keep up
func (c *Client) Blocking() <-chan amqp.Blocking {
return c.blocking
}
// Close shutdown the client
func (c *Client) Close() {
atomic.StoreInt32(&c.run, noRun) // c.run = false
conn, _ := c.conn.Load().(*amqp.Connection)
if conn != nil {
conn.Close()
}
c.conn.Store((*amqp.Connection)(nil))
}
// Loop should be run as condition for `for` with receiving from (*Client).Errors()
//
// It will manage AMQP connection, run queue and exchange declarations, consumers.
// Will start to return false once (*Client).Close() called.
func (c *Client) Loop() bool {
var (
err error
)
if atomic.LoadInt32(&c.run) == noRun {
return false
}
conn, _ := c.conn.Load().(*amqp.Connection)
if conn != nil {
return true
}
if c.bo != nil {
time.Sleep(c.bo.Backoff(int(c.attempt)))
atomic.AddInt32(&c.attempt, 1)
}
// set default Heartbeat to 10 seconds like in original amqp.Dial
if c.config.Heartbeat == 0 {
c.config.Heartbeat = 10 * time.Second
}
conn, err = amqp.DialConfig(c.addr, c.config)
if c.reportErr(err) {
return true
}
c.conn.Store(conn)
atomic.StoreInt32(&c.attempt, 0)
// guard conn
go func() {
chanErr := make(chan *amqp.Error)
chanBlocking := make(chan amqp.Blocking)
conn.NotifyClose(chanErr)
conn.NotifyBlocked(chanBlocking)
// loop for blocking/deblocking
for {
select {
case err1 := <-chanErr:
c.reportErr(err1)
if conn1 := c.conn.Load().(*amqp.Connection); conn1 != nil {
c.conn.Store((*amqp.Connection)(nil))
conn1.Close()
}
// return from routine to launch reconnect process
return
case blocking := <-chanBlocking:
select {
case c.blocking <- blocking:
default:
}
}
}
}()
ch, err := conn.Channel()
if c.reportErr(err) {
return true
}
for _, declare := range c.declarations {
c.reportErr(declare(ch))
}
for cons := range c.consumers {
ch1, err := c.channel()
if err == nil {
go cons.serve(c, ch1)
}
}
for pub := range c.publishers {
ch1, err := c.channel()
if err == nil {
go pub.serve(c, ch1)
}
}
return true
}
func (c *Client) reportErr(err error) bool {
if err != nil {
select {
case c.errs <- err:
default:
}
return true
}
return false
}
func (c *Client) channel() (*amqp.Channel, error) {
conn, err := c.connection()
if err != nil {
return nil, err
}
return conn.Channel()
}
func (c *Client) connection() (*amqp.Connection, error) {
conn, _ := c.conn.Load().(*amqp.Connection)
if conn == nil {
return nil, ErrNoConnection
}
return conn, nil
}
// NewClient initializes new Client
func NewClient(opts ...ClientOpt) *Client {
c := &Client{
run: run,
declarations: make([]Declaration, 0),
consumers: make(map[*Consumer]struct{}),
publishers: make(map[*Publisher]struct{}),
errs: make(chan error, 100),
blocking: make(chan amqp.Blocking, 10),
}
for _, o := range opts {
o(c)
}
return c
}
// URL is a functional option, used in `NewClient` constructor
// default URL is amqp://guest:guest@localhost/
func URL(addr string) ClientOpt {
return func(c *Client) {
if addr == "" {
addr = "amqp://guest:guest@localhost/"
}
c.addr = addr
}
}
// Backoff is a functional option, used to define backoff policy, used in
// `NewClient` constructor
func Backoff(bo Backoffer) ClientOpt {
return func(c *Client) {
c.bo = bo
}
}
// ErrorsChan is a functional option, used to initialize error reporting channel
// in client code, maintaining control over buffer size. Default buffer size is
// 100. Messages will be dropped in case if receiver can't keep up, used in
// `NewClient` constructor
func ErrorsChan(errChan chan error) ClientOpt {
return func(c *Client) {
c.errs = errChan
}
}
// BlockingChan is a functional option, used to initialize blocking reporting
// channel in client code, maintaining control over buffering, used in
// `NewClient` constructor
func BlockingChan(blockingChan chan amqp.Blocking) ClientOpt {
return func(c *Client) {
c.blocking = blockingChan
}
}
// Config is a functional option, used to setup extended amqp configuration
func Config(config amqp.Config) ClientOpt {
return func(c *Client) {
c.config = config
}
}