-
Notifications
You must be signed in to change notification settings - Fork 4
/
connection.go
370 lines (294 loc) · 10.1 KB
/
connection.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
package gorabbit
import (
"context"
"fmt"
"net/url"
"time"
"github.com/google/uuid"
amqp "github.com/rabbitmq/amqp091-go"
)
// amqpConnection holds information about the management of the native amqp.Connection.
type amqpConnection struct {
// ctx is the parent context and acts as a safeguard.
ctx context.Context
// connection is the native amqp.Connection.
connection *amqp.Connection
// uri represents the connection string to the RabbitMQ server.
uri string
// connectionName is the client connection name passed on to the RabbitMQ server.
connectionName string
// keepAlive is the flag that will define whether active guards and re-connections are enabled or not.
keepAlive bool
// retryDelay defines the delay to wait before re-connecting if we lose connection and the keepAlive flag is set to true.
retryDelay time.Duration
// closed is an inner property that switches to true if the connection was explicitly closed.
closed bool
// channels holds a list of active amqpChannel
channels amqpChannels
// maxRetry defines the number of retries when publishing a message.
maxRetry uint
// publishingCacheSize defines the maximum length of cached failed publishing.
publishingCacheSize uint64
// publishingCacheTTL defines the time to live for a cached failed publishing.
publishingCacheTTL time.Duration
// logger logs events.
logger logger
// connectionType defines the connectionType.
connectionType connectionType
// marshaller defines the marshalling method used to encode messages.
marshaller Marshaller
}
// newConsumerConnection initializes a new consumer amqpConnection with given arguments.
// - ctx is the parent context.
// - uri is the connection string.
// - connectionName is the connection name.
// - keepAlive will keep the connection alive if true.
// - retryDelay defines the delay between each re-connection, if the keepAlive flag is set to true.
// - logger is the parent logger.
// - marshaller is the Marshaller used for encoding messages.
func newConsumerConnection(
ctx context.Context,
uri string,
connectionName string,
keepAlive bool,
retryDelay time.Duration,
logger logger,
marshaller Marshaller,
) *amqpConnection {
connectionName = fmt.Sprintf("%s-consumer-%s", connectionName, uuid.NewString())
return newConnection(ctx, uri, connectionName, keepAlive, retryDelay, logger, connectionTypeConsumer, marshaller)
}
// newPublishingConnection initializes a new publisher amqpConnection with given arguments.
// - ctx is the parent context.
// - uri is the connection string.
// - connectionName is the connection name.
// - keepAlive will keep the connection alive if true.
// - retryDelay defines the delay between each re-connection, if the keepAlive flag is set to true.
// - maxRetry defines the publishing max retry header.
// - publishingCacheSize defines the maximum length of failed publishing cache.
// - publishingCacheTTL defines the time to live for failed publishing in cache.
// - logger is the parent logger.
// - marshaller is the Marshaller used for encoding messages.
func newPublishingConnection(
ctx context.Context,
uri string,
connectionName string,
keepAlive bool,
retryDelay time.Duration,
maxRetry uint,
publishingCacheSize uint64,
publishingCacheTTL time.Duration,
logger logger,
marshaller Marshaller,
) *amqpConnection {
connectionName = fmt.Sprintf("%s-publisher-%s", connectionName, uuid.NewString())
conn := newConnection(ctx, uri, connectionName, keepAlive, retryDelay, logger, connectionTypePublisher, marshaller)
conn.maxRetry = maxRetry
conn.publishingCacheSize = publishingCacheSize
conn.publishingCacheTTL = publishingCacheTTL
return conn
}
// newConnection initializes a new amqpConnection with given arguments.
// - ctx is the parent context.
// - uri is the connection string.
// - connectionName is the connection name.
// - keepAlive will keep the connection alive if true.
// - retryDelay defines the delay between each re-connection, if the keepAlive flag is set to true.
// - logger is the parent logger.
// - marshaller is the Marshaller used for encoding messages.
func newConnection(
ctx context.Context,
uri string,
connectionName string,
keepAlive bool,
retryDelay time.Duration,
logger logger,
connectionType connectionType,
marshaller Marshaller,
) *amqpConnection {
conn := &amqpConnection{
ctx: ctx,
uri: uri,
connectionName: connectionName,
keepAlive: keepAlive,
retryDelay: retryDelay,
channels: make(amqpChannels, 0),
logger: inheritLogger(logger, map[string]interface{}{
"context": "connection",
"type": connectionType,
}),
connectionType: connectionType,
marshaller: marshaller,
}
conn.logger.Debug("Initializing new amqp connection", logField{Key: "uri", Value: conn.uriForLog()})
// We open an initial connection.
err := conn.open()
// If the connection failed and the keepAlive flag is set to true, we want to re-connect until success.
if err != nil && keepAlive {
go conn.reconnect()
}
return conn
}
// open opens a new amqp.Connection with the help of a defined uri.
func (a *amqpConnection) open() error {
// If the uri is empty, we return an error.
if a.uri == "" {
return errEmptyURI
}
a.logger.Debug("Connecting to RabbitMQ server", logField{Key: "uri", Value: a.uriForLog()})
props := amqp.NewConnectionProperties()
if a.connectionName != "" {
props.SetClientConnectionName(a.connectionName)
}
// We request a connection from the RabbitMQ server.
conn, err := amqp.DialConfig(a.uri, amqp.Config{
Heartbeat: defaultHeartbeat,
Locale: defaultLocale,
Properties: props,
})
if err != nil {
a.logger.Error(err, "Connection failed")
return err
}
a.logger.Info("Connection successful", logField{Key: "uri", Value: a.uriForLog()})
a.connection = conn
a.channels.updateParentConnection(a.connection)
// If the keepAlive flag is set to true, we activate a new guard.
if a.keepAlive {
go a.guard()
}
return nil
}
// reconnect will indefinitely call the open method until a connection is successfully established or the context is canceled.
func (a *amqpConnection) reconnect() {
a.logger.Debug("Re-connection launched")
for {
select {
case <-a.ctx.Done():
a.logger.Debug("Re-connection stopped by the context")
// If the context was canceled, we break out of the method.
return
default:
// Wait for the retryDelay.
time.Sleep(a.retryDelay)
// If there is no connection or the current connection is closed, we open a new connection.
if !a.ready() {
err := a.open()
// If the operation succeeds, we break the loop.
if err == nil {
a.logger.Debug("Re-connection successful")
return
}
a.logger.Error(err, "Could not open new connection during re-connection")
} else {
// If the connection exists and is active, we break out.
return
}
}
}
}
// guard is a connection safeguard that listens to connection close events and re-launches the connection.
func (a *amqpConnection) guard() {
a.logger.Debug("Guard launched")
for {
select {
case <-a.ctx.Done():
a.logger.Debug("Guard stopped by the context")
// If the context was canceled, we break out of the method.
return
case err, ok := <-a.connection.NotifyClose(make(chan *amqp.Error)):
if !ok {
return
}
if err != nil {
a.logger.Warn("Connection lost", logField{Key: "reason", Value: err.Reason}, logField{Key: "code", Value: err.Code})
}
// If the connection was explicitly closed, we do not want to re-connect.
if a.closed {
return
}
go a.reconnect()
return
}
}
}
// close the connection only if it is ready.
func (a *amqpConnection) close() error {
if a.ready() {
for _, channel := range a.channels {
err := channel.close()
if err != nil {
return err
}
}
err := a.connection.Close()
if err != nil {
a.logger.Error(err, "Could not close connection")
return err
}
}
a.closed = true
a.logger.Info("Connection closed")
return nil
}
// ready returns true if the connection exists and is not closed.
func (a *amqpConnection) ready() bool {
return a.connection != nil && !a.connection.IsClosed()
}
// healthy returns true if the connection exists, is not closed and all child channels are healthy.
func (a *amqpConnection) healthy() bool {
// If the connection is not ready, return false.
if !a.ready() {
return false
}
// Verify that all connection channels are ready too.
for _, channel := range a.channels {
if !channel.healthy() {
return false
}
}
return true
}
// registerConsumer opens a new consumerChannel and registers the MessageConsumer.
func (a *amqpConnection) registerConsumer(consumer MessageConsumer) error {
for _, channel := range a.channels {
if channel.consumer != nil && channel.consumer.Queue == consumer.Queue {
err := errConsumerAlreadyExists
a.logger.Error(err, "Could not register consumer", logField{Key: "consumer", Value: consumer.Name})
return err
}
}
if err := consumer.Handlers.Validate(); err != nil {
return err
}
channel := newConsumerChannel(a.ctx, a.connection, a.keepAlive, a.retryDelay, &consumer, a.logger, a.marshaller)
a.channels = append(a.channels, channel)
a.logger.Info("Consumer registered", logField{Key: "consumer", Value: consumer.Name})
return nil
}
func (a *amqpConnection) publish(exchange, routingKey string, payload []byte, options *PublishingOptions) error {
publishingChannel := a.channels.publishingChannel()
if publishingChannel == nil {
publishingChannel = newPublishingChannel(
a.ctx, a.connection, a.keepAlive, a.retryDelay, a.maxRetry,
a.publishingCacheSize, a.publishingCacheTTL, a.logger, a.marshaller,
)
a.channels = append(a.channels, publishingChannel)
}
return publishingChannel.publish(exchange, routingKey, payload, options)
}
// uriForLog returns the uri with the password hidden for security measures.
func (a *amqpConnection) uriForLog() string {
if a.uri == "" {
return a.uri
}
parsedURL, err := url.Parse(a.uri)
if err != nil {
return ""
}
hiddenPassword := "xxxx"
if parsedURL.User != nil {
parsedURL.User = url.UserPassword(parsedURL.User.Username(), hiddenPassword)
}
return parsedURL.String()
}