-
Notifications
You must be signed in to change notification settings - Fork 18
/
dialer.go
455 lines (384 loc) · 10.7 KB
/
dialer.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Package amqpextra provides Dialer for dialing in case the connection lost.
package amqpextra
import (
"context"
"crypto/tls"
"errors"
"sync"
"time"
"fmt"
"github.com/makasim/amqpextra/consumer"
"github.com/makasim/amqpextra/logger"
"github.com/makasim/amqpextra/publisher"
amqp "github.com/rabbitmq/amqp091-go"
)
type State struct {
Ready *Ready
Unready *Unready
}
type Ready struct{}
type Unready struct {
Err error
}
// Option could be used to configure Dialer
type Option func(c *Dialer)
// AMQPConnection is an interface for streadway's *amqp.Connection
type AMQPConnection interface {
NotifyClose(chan *amqp.Error) chan *amqp.Error
Close() error
}
// Connection provides access to streadway's *amqp.Connection as well as notification channels
// A notification indicates that something wrong has happened to the connection.
// The client should get a fresh connection from Dialer.
type Connection struct {
amqpConn AMQPConnection
lostCh chan struct{}
}
// AMQPConnection returns streadway's *amqp.Connection
func (c *Connection) AMQPConnection() *amqp.Connection {
return c.amqpConn.(*amqp.Connection)
}
// NotifyLost notifies when current connection is lost and new once should be requested
func (c *Connection) NotifyLost() chan struct{} {
return c.lostCh
}
type config struct {
amqpUrls []string
amqpDial func(url string, c amqp.Config) (AMQPConnection, error)
amqpConfig amqp.Config
logger logger.Logger
retryPeriod time.Duration
ctx context.Context
}
// Dialer is responsible for keeping the connection up.
// If connection is lost or closed. It tries dial a server again and again with some wait periods.
// Dialer keep connection up until it Dialer.Close() method called or the context is canceled.
type Dialer struct {
config
ctx context.Context
cancelFunc context.CancelFunc
connCh chan *Connection
mu sync.Mutex
stateChs []chan State
internalStateChan chan State
closedCh chan struct{}
}
// Dial returns established connection or an error.
// It keeps retrying until timeout 30sec is reached.
func Dial(opts ...Option) (*amqp.Connection, error) {
d, err := NewDialer(opts...)
if err != nil {
return nil, err
}
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second*30)
defer cancelFunc()
return d.Connection(ctx)
}
// NewDialer returns Dialer or a configuration error.
func NewDialer(opts ...Option) (*Dialer, error) {
c := &Dialer{
config: config{
amqpUrls: make([]string, 0, 1),
amqpDial: func(url string, c amqp.Config) (AMQPConnection, error) {
return amqp.DialConfig(url, c)
},
amqpConfig: amqp.Config{
Heartbeat: time.Second * 30,
Locale: "en_US",
},
retryPeriod: time.Second * 5,
logger: logger.Discard,
},
internalStateChan: make(chan State),
connCh: make(chan *Connection),
closedCh: make(chan struct{}),
}
for _, opt := range opts {
opt(c)
}
for _, readyCh := range c.stateChs {
if readyCh == nil {
return nil, errors.New("state chan must be not nil")
}
if cap(readyCh) == 0 {
return nil, errors.New("state chan is unbuffered")
}
}
if len(c.amqpUrls) == 0 {
return nil, fmt.Errorf("url(s) must be set")
}
for _, url := range c.amqpUrls {
if url == "" {
return nil, fmt.Errorf("url(s) must be not empty")
}
}
if c.config.ctx != nil {
c.ctx, c.cancelFunc = context.WithCancel(c.config.ctx)
} else {
c.ctx, c.cancelFunc = context.WithCancel(context.Background())
}
if c.retryPeriod <= 0 {
return nil, fmt.Errorf("retryPeriod must be greater then zero")
}
go c.connectState()
return c, nil
}
// WithURL configure RabbitMQ servers to dial.
// Dialer dials url by round-robbin
func WithURL(urls ...string) Option {
return func(c *Dialer) {
c.amqpUrls = append(c.amqpUrls, urls...)
}
}
// WithTLS configure TLS.
// tlsConfig TLS configuration to use
func WithTLS(tlsConfig *tls.Config) Option {
return func(c *Dialer) {
c.amqpConfig.TLSClientConfig = tlsConfig
}
}
// WithAMQPDial configure dial function.
// The function takes the url and amqp.Config and returns AMQPConnection.
func WithAMQPDial(dial func(url string, c amqp.Config) (AMQPConnection, error)) Option {
return func(c *Dialer) {
c.amqpDial = dial
}
}
// WithLogger configure the logger used by Dialer
func WithLogger(l logger.Logger) Option {
return func(c *Dialer) {
c.logger = l
}
}
// WithLogger configure Dialer context
// The context could used later to stop Dialer
func WithContext(ctx context.Context) Option {
return func(c *Dialer) {
c.config.ctx = ctx
}
}
// WithRetryPeriod configure how much time to wait before next dial attempt. Default: 5sec.
func WithRetryPeriod(dur time.Duration) Option {
return func(c *Dialer) {
c.retryPeriod = dur
}
}
// WithConnectionProperties configure connection properties set on dial.
func WithConnectionProperties(props amqp.Table) Option {
return func(c *Dialer) {
c.amqpConfig.Properties = props
}
}
// WithNotify helps subscribe on Dialer ready/unready events.
func WithNotify(stateCh chan State) Option {
return func(c *Dialer) {
c.stateChs = append(c.stateChs, stateCh)
}
}
// ConnectionCh returns Connection channel.
// The channel should be used to get established connections.
// The client must subscribe on Connection.NotifyLost().
// Once lost, client must stop using current connection and get new one from Connection channel.
// Connection channel is closed when Dialer is closed. Don't forget to check for closed connection.
func (c *Dialer) ConnectionCh() <-chan *Connection {
return c.connCh
}
// Notify could be used to subscribe on Dialer ready/unready events
func (c *Dialer) Notify(stateCh chan State) <-chan State {
if cap(stateCh) == 0 {
panic("state chan is unbuffered")
}
select {
case state := <-c.internalStateChan:
stateCh <- state
case <-c.NotifyClosed():
return stateCh
}
c.mu.Lock()
c.stateChs = append(c.stateChs, stateCh)
c.mu.Unlock()
return stateCh
}
// NotifyClosed could be used to subscribe on Dialer closed event.
// Dialer.ConnectionCh() could no longer be used after this point
func (c *Dialer) NotifyClosed() <-chan struct{} {
return c.closedCh
}
// Close initiate Dialer close.
// Subscribe Dialer.NotifyClosed() to know when it was finally closed.
func (c *Dialer) Close() {
c.cancelFunc()
}
// Connection returns streadway's *amqp.Connection.
// The client should subscribe on Dialer.NotifyReady(), Dialer.NotifyUnready() events in order to know when the connection is lost.
func (c *Dialer) Connection(ctx context.Context) (*amqp.Connection, error) {
select {
case <-c.ctx.Done():
return nil, fmt.Errorf("connection closed")
case <-ctx.Done():
return nil, ctx.Err()
case conn, ok := <-c.connCh:
if !ok {
return nil, fmt.Errorf("connection closed")
}
return conn.AMQPConnection(), nil
}
}
// Consumer returns a consumer that support reconnection feature.
func (c *Dialer) Consumer(opts ...consumer.Option) (*consumer.Consumer, error) {
opts = append([]consumer.Option{
consumer.WithLogger(c.logger),
consumer.WithContext(c.ctx),
}, opts...)
return NewConsumer(c.ConnectionCh(), opts...)
}
// Publisher returns a consumer that support reconnection feature.
func (c *Dialer) Publisher(opts ...publisher.Option) (*publisher.Publisher, error) {
opts = append([]publisher.Option{
publisher.WithLogger(c.logger),
publisher.WithContext(c.ctx),
}, opts...)
return NewPublisher(c.ConnectionCh(), opts...)
}
// connectState is a starting point.
// It chooses URL and dials the server.
// Once connection is established it pass control to Dialer.connectedState()
// If connection is closed or lost Dialer.connectedState() returns control back to Dialer.connectState()
// Exits on Dialer.Close()
func (c *Dialer) connectState() {
defer close(c.connCh)
defer close(c.closedCh)
defer c.cancelFunc()
defer c.logger.Printf("[DEBUG] connection closed")
i := 0
l := len(c.amqpUrls)
c.logger.Printf("[DEBUG] connection unready")
state := State{Unready: &Unready{Err: amqp.ErrClosed}}
for {
select {
case <-c.ctx.Done():
return
default:
}
url := c.amqpUrls[i]
i = (i + 1) % l
connCh := make(chan AMQPConnection)
errorCh := make(chan error)
go func() {
c.logger.Printf("[DEBUG] dialing")
if conn, err := c.amqpDial(url, c.amqpConfig); err != nil {
errorCh <- err
} else {
connCh <- conn
}
}()
loop2:
for {
select {
case c.internalStateChan <- state:
continue
case conn := <-connCh:
select {
case <-c.ctx.Done():
c.closeConn(conn)
return
default:
}
if err := c.connectedState(conn); err != nil {
c.logger.Printf("[DEBUG] connection unready: %s", err)
state = c.notifyUnready(err)
break loop2
}
return
case err := <-errorCh:
c.logger.Printf("[DEBUG] connection unready: %v", err)
if retryErr := c.waitRetry(err); retryErr != nil {
state = State{Unready: &Unready{Err: retryErr}}
break loop2
}
return
}
}
}
}
// connectedState serves Dialer.ConnectionCh() and Dialer.Connection() methods.
// It shares an established connection with all the clients who requests it.
// Once connection is lost or closed it gives control back to Dialer.connectState().
func (c *Dialer) connectedState(amqpConn AMQPConnection) error {
defer c.closeConn(amqpConn)
lostCh := make(chan struct{})
defer close(lostCh)
internalCloseCh := amqpConn.NotifyClose(make(chan *amqp.Error, 1))
conn := &Connection{amqpConn: amqpConn, lostCh: lostCh}
c.logger.Printf("[DEBUG] connection ready")
state := c.notifyReady()
for {
select {
case c.internalStateChan <- state:
continue
case c.connCh <- conn:
continue
case err, ok := <-internalCloseCh:
if !ok {
err = amqp.ErrClosed
}
return err
case <-c.ctx.Done():
return nil
}
}
}
func (c *Dialer) notifyUnready(err error) State {
state := State{Unready: &Unready{Err: err}}
c.mu.Lock()
defer c.mu.Unlock()
for _, stateCh := range c.stateChs {
select {
case stateCh <- state:
case <-stateCh:
stateCh <- state
}
}
return state
}
func (c *Dialer) notifyReady() State {
state := State{Ready: &Ready{}}
c.mu.Lock()
defer c.mu.Unlock()
for _, stateCh := range c.stateChs {
select {
case stateCh <- state:
case <-stateCh:
stateCh <- state
}
}
return state
}
func (c *Dialer) waitRetry(err error) error {
timer := time.NewTimer(c.retryPeriod)
defer func() {
timer.Stop()
select {
case <-timer.C:
default:
}
}()
state := c.notifyUnready(err)
for {
select {
case c.internalStateChan <- state:
continue
case <-timer.C:
return err
case <-c.ctx.Done():
return nil
}
}
}
func (c *Dialer) closeConn(conn AMQPConnection) {
if err := conn.Close(); err == amqp.ErrClosed {
return
} else if err != nil {
c.logger.Printf("[ERROR] %s", err)
}
}