-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrabbitmq.go
More file actions
489 lines (408 loc) · 12.2 KB
/
Copy pathrabbitmq.go
File metadata and controls
489 lines (408 loc) · 12.2 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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Package rabbitmq provides a simplified interface for RabbitMQ messaging
// with support for publishers, consumers, exchanges, and queues.
package rabbitmq
import (
"crypto/tls"
"errors"
"fmt"
"math"
"net"
"net/url"
"strconv"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
// Sentinel errors for RabbitMQ operations.
var (
ErrConnectionClosed = errors.New("rabbitmq: connection closed")
ErrChannelClosed = errors.New("rabbitmq: channel closed")
ErrPublishFailed = errors.New("rabbitmq: publish failed")
ErrConsumeFailed = errors.New("rabbitmq: consume failed")
ErrInvalidConfig = errors.New("rabbitmq: invalid configuration")
ErrNotConnected = errors.New("rabbitmq: not connected")
ErrTimeout = errors.New("rabbitmq: operation timeout")
ErrNack = errors.New("rabbitmq: message was nacked")
ErrMaxReconnects = errors.New("rabbitmq: max reconnection attempts reached")
ErrShuttingDown = errors.New("rabbitmq: shutting down")
// ErrNilConnection is returned by constructors when given a nil *Connection.
ErrNilConnection = errors.New("rabbitmq: nil connection")
// ErrNilMessage is returned by publish methods when given a nil *Message.
ErrNilMessage = errors.New("rabbitmq: nil message")
// ErrDelayTooLong is returned by PublishDelayed when the requested delay
// exceeds the largest rung of the delay ladder (see DelayLadder).
ErrDelayTooLong = errors.New("rabbitmq: delay exceeds maximum supported delay")
// ErrRequeue, when returned by a message handler, forces the failed message
// to be requeued regardless of ConsumerConfig.RequeueOnError. Use it for
// transient failures that are worth retrying. May be wrapped with %w.
ErrRequeue = errors.New("rabbitmq: requeue message")
// ErrDrop, when returned by a message handler, forces the failed message to
// NOT be requeued regardless of ConsumerConfig.RequeueOnError. The message
// is dead-lettered if a dead-letter exchange is configured, else discarded.
// Use it for poison messages that will never succeed. May be wrapped with %w.
ErrDrop = errors.New("rabbitmq: drop message")
)
// Config holds the RabbitMQ connection configuration.
type Config struct {
// URL is the AMQP connection URL.
URL string
// Host is the RabbitMQ host (used if URL is empty).
Host string
// Port is the RabbitMQ port (default: 5672).
Port int
// Username for authentication (default: "guest").
Username string
// Password for authentication (default: "guest").
Password string
// VHost is the virtual host (default: "/").
VHost string
// TLS configuration for secure connections.
TLS *tls.Config
// Heartbeat interval (default: 10s).
Heartbeat time.Duration
// ConnectionTimeout for establishing connection (default: 30s).
ConnectionTimeout time.Duration
// ReconnectDelay is the initial delay between reconnection attempts (default: 1s).
// The delay increases exponentially up to ReconnectDelayMax.
ReconnectDelay time.Duration
// ReconnectDelayMax is the maximum delay between reconnection attempts (default: 60s).
ReconnectDelayMax time.Duration
// MaxReconnectAttempts is the maximum reconnection attempts (0 = unlimited).
MaxReconnectAttempts int
// Logger for connection events. Defaults to a no-op logger.
Logger Logger
}
// DefaultConfig returns a default RabbitMQ configuration.
func DefaultConfig() Config {
return Config{
Host: "localhost",
Port: 5672,
Username: "guest",
Password: "guest",
VHost: "/",
Heartbeat: 10 * time.Second,
ConnectionTimeout: 30 * time.Second,
ReconnectDelay: 1 * time.Second,
ReconnectDelayMax: 60 * time.Second,
MaxReconnectAttempts: 0,
}
}
// WithURL returns a new config with the specified URL.
func (c Config) WithURL(url string) Config {
c.URL = url
return c
}
// WithHost returns a new config with the specified host and port.
func (c Config) WithHost(host string, port int) Config {
c.Host = host
c.Port = port
return c
}
// WithCredentials returns a new config with the specified credentials.
func (c Config) WithCredentials(username, password string) Config {
c.Username = username
c.Password = password
return c
}
// WithVHost returns a new config with the specified virtual host.
func (c Config) WithVHost(vhost string) Config {
c.VHost = vhost
return c
}
// WithTLS returns a new config with TLS enabled.
func (c Config) WithTLS(config *tls.Config) Config {
c.TLS = config
return c
}
// WithHeartbeat returns a new config with the specified heartbeat.
func (c Config) WithHeartbeat(heartbeat time.Duration) Config {
c.Heartbeat = heartbeat
return c
}
// WithReconnect returns a new config with reconnection settings.
func (c Config) WithReconnect(initialDelay, maxDelay time.Duration, maxAttempts int) Config {
c.ReconnectDelay = initialDelay
c.ReconnectDelayMax = maxDelay
c.MaxReconnectAttempts = maxAttempts
return c
}
// WithLogger returns a new config with the specified logger.
func (c Config) WithLogger(logger Logger) Config {
c.Logger = logger
return c
}
// connectionURL builds the AMQP connection URL.
func (c Config) connectionURL() string {
if c.URL != "" {
return c.URL
}
scheme := "amqp"
if c.TLS != nil {
scheme = "amqps"
}
// Build the URL via net/url so that the username, password, and vhost are
// percent-encoded. A raw fmt.Sprintf breaks for credentials or vhosts that
// contain reserved characters such as '@', ':', '/', or '?'.
u := &url.URL{
Scheme: scheme,
User: url.UserPassword(c.Username, c.Password),
Host: net.JoinHostPort(c.Host, strconv.Itoa(c.Port)),
Path: c.VHost,
}
return u.String()
}
// logger returns the configured logger or a no-op logger.
func (c Config) logger() Logger {
if c.Logger != nil {
return c.Logger
}
return nopLogger{}
}
// reconnectDelay calculates the exponential backoff delay for the given attempt.
func (c Config) reconnectDelay(attempt int) time.Duration {
delay := c.ReconnectDelay
if delay <= 0 {
delay = 1 * time.Second
}
maxDelay := c.ReconnectDelayMax
if maxDelay <= 0 {
maxDelay = 60 * time.Second
}
backoff := time.Duration(float64(delay) * math.Pow(2, float64(attempt)))
if backoff > maxDelay {
backoff = maxDelay
}
return backoff
}
// Connection manages the RabbitMQ connection with auto-reconnect.
type Connection struct {
config Config
conn *amqp.Connection
mu sync.RWMutex
closed bool
closeCh chan struct{}
notifyCh chan *amqp.Error
log Logger
// Callbacks
onConnect func()
onDisconnect func(error)
// Reconnect subscribers — publishers and consumers register here
// to be notified when the connection is re-established.
subsMu sync.Mutex
subscribers []chan struct{}
}
// NewConnection creates a new RabbitMQ connection.
func NewConnection(config Config) (*Connection, error) {
c := &Connection{
config: config,
closeCh: make(chan struct{}),
log: config.logger(),
}
if err := c.connect(); err != nil {
return nil, err
}
c.log.Infof("connected to %s", c.config.Host)
// Start reconnection handler
go c.handleReconnect()
return c, nil
}
// connect establishes the connection.
func (c *Connection) connect() error {
c.mu.Lock()
defer c.mu.Unlock()
amqpConfig := amqp.Config{
Heartbeat: c.config.Heartbeat,
Locale: "en_US",
}
// Honor the configured connection timeout for the initial dial and for
// every reconnection attempt. Without this, amqp091's default 30s dial
// timeout is used and Config.ConnectionTimeout has no effect.
if c.config.ConnectionTimeout > 0 {
amqpConfig.Dial = amqp.DefaultDial(c.config.ConnectionTimeout)
}
if c.config.TLS != nil {
amqpConfig.TLSClientConfig = c.config.TLS
}
conn, err := amqp.DialConfig(c.config.connectionURL(), amqpConfig)
if err != nil {
return fmt.Errorf("%w: %v", ErrConnectionClosed, err)
}
c.conn = conn
c.notifyCh = make(chan *amqp.Error, 1)
c.conn.NotifyClose(c.notifyCh)
if c.onConnect != nil {
go c.onConnect()
}
return nil
}
// handleReconnect handles automatic reconnection with exponential backoff.
func (c *Connection) handleReconnect() {
for {
select {
case <-c.closeCh:
return
case amqpErr := <-c.notifyCh:
c.mu.RLock()
if c.closed {
c.mu.RUnlock()
return
}
onDisconnect := c.onDisconnect
c.mu.RUnlock()
c.log.Warnf("connection lost: %v", amqpErr)
if onDisconnect != nil {
onDisconnect(amqpErr)
}
// Attempt reconnection with exponential backoff
for attempt := 0; ; attempt++ {
if c.config.MaxReconnectAttempts > 0 && attempt >= c.config.MaxReconnectAttempts {
c.log.Errorf("max reconnection attempts (%d) reached, giving up", c.config.MaxReconnectAttempts)
return
}
delay := c.config.reconnectDelay(attempt)
c.log.Infof("reconnecting in %s (attempt %d)...", delay, attempt+1)
select {
case <-time.After(delay):
case <-c.closeCh:
return
}
if err := c.connect(); err != nil {
c.log.Warnf("reconnection attempt %d failed: %v", attempt+1, err)
continue
}
c.log.Infof("reconnected successfully after %d attempt(s)", attempt+1)
c.notifySubscribers()
break
}
}
}
}
// subscribeReconnect returns a channel that receives a signal when the
// connection is re-established. Used internally by Publisher and Consumer.
func (c *Connection) subscribeReconnect() chan struct{} {
ch := make(chan struct{}, 1)
c.subsMu.Lock()
c.subscribers = append(c.subscribers, ch)
c.subsMu.Unlock()
return ch
}
// unsubscribeReconnect removes a subscriber channel.
func (c *Connection) unsubscribeReconnect(ch chan struct{}) {
c.subsMu.Lock()
defer c.subsMu.Unlock()
for i, sub := range c.subscribers {
if sub == ch {
c.subscribers = append(c.subscribers[:i], c.subscribers[i+1:]...)
return
}
}
}
// notifySubscribers signals all subscribers that reconnection succeeded.
func (c *Connection) notifySubscribers() {
c.subsMu.Lock()
defer c.subsMu.Unlock()
for _, ch := range c.subscribers {
select {
case ch <- struct{}{}:
default:
}
}
}
// OnConnect sets the connection callback.
func (c *Connection) OnConnect(fn func()) {
c.mu.Lock()
defer c.mu.Unlock()
c.onConnect = fn
}
// OnDisconnect sets the disconnection callback.
func (c *Connection) OnDisconnect(fn func(error)) {
c.mu.Lock()
defer c.mu.Unlock()
c.onDisconnect = fn
}
// Channel creates a new channel.
func (c *Connection) Channel() (*Channel, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if c.conn == nil || c.conn.IsClosed() {
return nil, ErrNotConnected
}
ch, err := c.conn.Channel()
if err != nil {
return nil, err
}
return &Channel{ch: ch, conn: c}, nil
}
// Close closes the connection.
func (c *Connection) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil
}
c.closed = true
close(c.closeCh)
c.log.Infof("closing connection")
if c.conn != nil {
return c.conn.Close()
}
return nil
}
// IsClosed returns true if the connection is closed.
func (c *Connection) IsClosed() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.closed || c.conn == nil || c.conn.IsClosed()
}
// IsHealthy returns true if the connection is open and responsive.
// It attempts to create and immediately close a channel as a health probe.
func (c *Connection) IsHealthy() bool {
if c.IsClosed() {
return false
}
ch, err := c.Channel()
if err != nil {
return false
}
_ = ch.Close()
return true
}
// Channel wraps an AMQP channel.
type Channel struct {
ch *amqp.Channel
conn *Connection
mu sync.RWMutex
}
// SetQos sets the quality of service.
func (c *Channel) SetQos(prefetchCount, prefetchSize int, global bool) error {
return c.ch.Qos(prefetchCount, prefetchSize, global)
}
// Close closes the channel.
func (c *Channel) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.ch != nil {
return c.ch.Close()
}
return nil
}
// Raw returns the underlying amqp.Channel.
func (c *Channel) Raw() *amqp.Channel {
return c.ch
}
// ExchangeType represents the type of exchange.
type ExchangeType string
// Supported exchange types.
const (
ExchangeDirect ExchangeType = "direct"
ExchangeFanout ExchangeType = "fanout"
ExchangeTopic ExchangeType = "topic"
ExchangeHeaders ExchangeType = "headers"
)
// DeliveryMode represents the message delivery mode.
type DeliveryMode uint8
// Supported delivery modes.
const (
Transient DeliveryMode = 1
Persistent DeliveryMode = 2
)