-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
242 lines (202 loc) · 5.17 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
package chamqp
import (
"crypto/tls"
"fmt"
"math"
"os"
"sync"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const (
initialInterval = 1 * time.Second
maxInterval = 10 * time.Second
multiplier = float64(2)
maxAttemps = 10
AllowSelfTermination = true
)
// Connection manages the serialization and deserialization of frames from IO
// and dispatches the frames to the appropriate channel. All RPC methods and
// asynchronous Publishing, Delivery, Ack, Nack and Return messages are
// multiplexed on this channel. There must always be active receivers for every
// asynchronous message on this connection.
type Connection struct {
conn *amqp.Connection
channels []*Channel
errorChans []chan error
shutdownChan, doneChan chan struct{}
mu sync.Mutex
}
// Dial accepts a string in the AMQP URI format and returns a new Connection
// over TCP using PlainAuth. Defaults to a server heartbeat interval of 10
// seconds and sets the handshake deadline to 30 seconds. After handshake,
// deadlines are cleared.
//
// Use `NotifyError` to register a receiver for errors on the connection.
func Dial(url string) *Connection {
conn := &Connection{
shutdownChan: make(chan struct{}),
doneChan: make(chan struct{}),
}
connector := func() (*amqp.Connection, error) {
return amqp.Dial(url)
}
go conn.supervise(connector)
return conn
}
func DialTLS(url string, config *tls.Config) *Connection {
conn := &Connection{
shutdownChan: make(chan struct{}),
doneChan: make(chan struct{}),
}
connector := func() (*amqp.Connection, error) {
return amqp.DialTLS(url, config)
}
go conn.supervise(connector)
return conn
}
func DialBlocked(url string) (*Connection, error) {
conn := &Connection{
shutdownChan: make(chan struct{}),
doneChan: make(chan struct{}),
}
connector := func() (*amqp.Connection, error) {
return amqp.Dial(url)
}
err := conn.connect(connector)
return conn, err
}
func DialTLSBlocked(url string, config *tls.Config) (*Connection, error) {
conn := &Connection{
shutdownChan: make(chan struct{}),
doneChan: make(chan struct{}),
}
connector := func() (*amqp.Connection, error) {
return amqp.DialTLS(url, config)
}
err := conn.connect(connector)
return conn, err
}
func (c *Connection) ConnectionState() tls.ConnectionState {
return c.conn.ConnectionState()
}
func (c *Connection) connect(connector func() (*amqp.Connection, error)) error {
c.mu.Lock()
defer c.mu.Unlock()
conn, err := connector()
if err != nil {
return err
}
for _, ctx := range c.channels {
chanErr := ctx.connected(conn)
if chanErr != nil {
fmt.Println("error during channel (re)construction")
return chanErr
}
}
c.conn = conn
return nil
}
func (c *Connection) disconnect(err error) {
c.mu.Lock()
defer c.mu.Unlock()
if err != nil {
for _, c := range c.errorChans {
c <- err
}
}
c.conn = nil
for _, ctx := range c.channels {
ctx.disconnected()
}
}
func (c *Connection) supervise(connector func() (*amqp.Connection, error)) {
var attempt float64
defer close(c.doneChan)
for {
backoffDelay := time.Duration(math.Pow(multiplier, attempt)) * initialInterval
if backoffDelay > maxInterval {
backoffDelay = maxInterval
}
err := c.connect(connector)
if err != nil {
fmt.Println("Attempt is", attempt, "back off delay", backoffDelay)
for _, c := range c.errorChans {
c <- err
}
attempt++
if AllowSelfTermination && attempt >= maxAttemps {
fmt.Println("Too many errors, killing process")
os.Exit(1)
}
select {
case <-time.After(backoffDelay):
continue
case <-c.shutdownChan:
return
}
}
attempt = 0
notifyClose := make(chan *amqp.Error)
c.conn.NotifyClose(notifyClose)
select {
case err := <-notifyClose:
c.disconnect(err)
case <-c.shutdownChan:
return
}
}
}
// NotifyError registers a listener for error events either initiated by an
// connect or close.
func (c *Connection) NotifyError(receiver chan error) chan error {
c.mu.Lock()
defer c.mu.Unlock()
c.errorChans = append(c.errorChans, receiver)
return receiver
}
// Channel opens a unique, concurrent server channel to process the bulk of AMQP
// messages. Any error from methods on this receiver will cause the Channel to
// recreate itself.
// Note that a channel should not be used from multiple goroutines as it is not
// thread safe.
func (c *Connection) Channel() *Channel {
c.mu.Lock()
defer c.mu.Unlock()
ch := &Channel{}
c.channels = append(c.channels, ch)
if c.conn != nil {
ch.connected(c.conn)
}
return ch
}
func (c *Connection) ChannelWithConfirm(noWait bool) *Channel {
c.mu.Lock()
defer c.mu.Unlock()
ch := &Channel{}
ch.confirm = true
ch.confirmNoWait = noWait
c.channels = append(c.channels, ch)
if c.conn != nil {
ch.connected(c.conn)
}
return ch
}
// Close requests and waits for the response to close the AMQP connection.
func (c *Connection) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
select {
case <-c.shutdownChan:
// Already closed. Nothing to do.
default:
close(c.shutdownChan)
}
<-c.doneChan
if c.conn != nil {
conn := c.conn
c.conn = nil
return conn.Close()
}
return nil
}