This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
sender.go
372 lines (321 loc) · 9.54 KB
/
sender.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
package servicebus
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"errors"
"sync"
"time"
common "github.com/Azure/azure-amqp-common-go/v3"
"github.com/Azure/azure-amqp-common-go/v3/uuid"
"github.com/Azure/go-amqp"
"github.com/devigned/tab"
)
type (
// Sender provides connection, session and link handling for an sending to an entity path
Sender struct {
namespace *Namespace
client *amqp.Client
clientMu sync.RWMutex
session *session
sender *amqp.Sender
entityPath string
Name string
sessionID *string
cancelAuthRefresh func() <-chan struct{}
}
// SendOption provides a way to customize a message on sending
SendOption func(event *Message) error
eventer interface {
toMsg() (*amqp.Message, error)
GetKeyValues() map[string]interface{}
Set(key string, value interface{})
}
// SenderOption provides a way to customize a Sender
SenderOption func(*Sender) error
)
// NewSender creates a new Service Bus message Sender given an AMQP client and entity path
func (ns *Namespace) NewSender(ctx context.Context, entityPath string, opts ...SenderOption) (*Sender, error) {
ctx, span := ns.startSpanFromContext(ctx, "sb.Namespace.NewSender")
defer span.End()
s := &Sender{
namespace: ns,
entityPath: entityPath,
}
for _, opt := range opts {
if err := opt(s); err != nil {
tab.For(ctx).Error(err)
return nil, err
}
}
// no need to take the write lock as we're creating a new Sender
err := s.newSessionAndLink(ctx)
if err != nil {
tab.For(ctx).Error(err)
}
return s, err
}
// Recover will attempt to close the current session and link, then rebuild them
func (s *Sender) Recover(ctx context.Context) error {
ctx, span := s.startProducerSpanFromContext(ctx, "sb.Sender.Recover")
defer span.End()
// we expect the Sender, session or client is in an error state, ignore errors
closeCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
closeCtx = tab.NewContext(closeCtx, span)
defer cancel()
// we must close then rebuild the session/link atomically
s.clientMu.Lock()
defer s.clientMu.Unlock()
_ = s.close(closeCtx)
return s.newSessionAndLink(ctx)
}
// Close will close the AMQP connection, session and link of the Sender
func (s *Sender) Close(ctx context.Context) error {
ctx, span := s.startProducerSpanFromContext(ctx, "sb.Sender.Close")
defer span.End()
s.clientMu.Lock()
defer s.clientMu.Unlock()
return s.close(ctx)
}
// closes the connection. callers *must* hold the client write lock before calling!
func (s *Sender) close(ctx context.Context) error {
if s.cancelAuthRefresh != nil {
<-s.cancelAuthRefresh()
}
var lastErr error
if s.sender != nil {
if lastErr = s.sender.Close(ctx); lastErr != nil {
tab.For(ctx).Error(lastErr)
}
}
if s.session != nil {
if err := s.session.Close(ctx); err != nil {
tab.For(ctx).Error(err)
lastErr = err
}
}
if s.client != nil {
if err := s.client.Close(); err != nil {
tab.For(ctx).Error(err)
lastErr = err
}
}
s.sender = nil
s.session = nil
s.client = nil
return lastErr
}
// Send will send a message to the entity path with options
//
// This will retry sending the message if the server responds with a busy error.
func (s *Sender) Send(ctx context.Context, msg *Message, opts ...SendOption) error {
ctx, span := s.startProducerSpanFromContext(ctx, "sb.Sender.Send")
defer span.End()
if msg.SessionID == nil {
s.clientMu.RLock()
if s.session == nil {
// another goroutine has closed the connection
s.clientMu.RUnlock()
return s.connClosedError(ctx)
}
msg.SessionID = &s.session.SessionID
next := s.session.getNext()
s.clientMu.RUnlock()
msg.GroupSequence = &next
}
if msg.ID == "" {
id, err := uuid.NewV4()
if err != nil {
tab.For(ctx).Error(err)
return err
}
msg.ID = id.String()
}
for _, opt := range opts {
err := opt(msg)
if err != nil {
tab.For(ctx).Error(err)
return err
}
}
return s.trySend(ctx, msg)
}
func (s *Sender) trySend(ctx context.Context, evt eventer) error {
ctx, sp := s.startProducerSpanFromContext(ctx, "sb.Sender.trySend")
defer sp.End()
err := sp.Inject(evt)
if err != nil {
tab.For(ctx).Error(err)
return err
}
msg, err := evt.toMsg()
if err != nil {
tab.For(ctx).Error(err)
return err
}
if msg.Properties != nil {
sp.AddAttributes(tab.StringAttribute("sb.message.id", msg.Properties.MessageID.(string)))
}
for {
select {
case <-ctx.Done():
if err = ctx.Err(); err != nil {
tab.For(ctx).Error(err)
}
return err
default:
// try as long as the context is not dead
s.clientMu.RLock()
if s.sender == nil {
// another goroutine has closed the connection
s.clientMu.RUnlock()
return s.connClosedError(ctx)
}
err = s.sender.Send(ctx, msg)
s.clientMu.RUnlock()
if err == nil {
// successful send
return err
}
switch err.(type) {
case *amqp.Error, *amqp.DetachError:
err = s.handleAMQPError(ctx, err)
if err != nil {
tab.For(ctx).Error(err)
return err
}
default:
tab.For(ctx).Error(err)
return err
}
}
}
}
// handleAMQPError is called internally when an event has failed to send so we
// can parse the error to determine whether we should attempt to retry sending the event again.
func (s *Sender) handleAMQPError(ctx context.Context, err error) error {
var amqpError *amqp.Error
if errors.As(err, &amqpError) {
switch amqpError.Condition {
case errorServerBusy:
return s.retryRetryableAmqpError(ctx, amqpRetryDefaultTimes, amqpRetryBusyServerDelay)
case errorTimeout:
return s.retryRetryableAmqpError(ctx, amqpRetryDefaultTimes, amqpRetryDefaultDelay)
case errorOperationCancelled:
return s.retryRetryableAmqpError(ctx, amqpRetryDefaultTimes, amqpRetryDefaultDelay)
case errorContainerClose:
return s.retryRetryableAmqpError(ctx, amqpRetryDefaultTimes, amqpRetryDefaultDelay)
default:
return err
}
}
return s.retryRetryableAmqpError(ctx, amqpRetryDefaultTimes, amqpRetryDefaultDelay)
}
func (s *Sender) retryRetryableAmqpError(ctx context.Context, times int, delay time.Duration) error {
tab.For(ctx).Debug("recovering sender connection")
_, retryErr := common.Retry(times, delay, func() (interface{}, error) {
ctx, sp := s.startProducerSpanFromContext(ctx, "sb.Sender.trySend.tryRecover")
defer sp.End()
err := s.Recover(ctx)
if err == nil {
tab.For(ctx).Debug("recovered connection")
return nil, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
return nil, common.Retryable(err.Error())
}
})
if retryErr != nil {
tab.For(ctx).Debug("sender recovering retried, but error was unrecoverable")
return retryErr
}
return nil
}
func (s *Sender) connClosedError(ctx context.Context) error {
name := "Sender"
if s.Name != "" {
name = s.Name
}
err := ErrConnectionClosed(name)
tab.For(ctx).Error(err)
return err
}
func (s *Sender) String() string {
return s.Name
}
func (s *Sender) getAddress() string {
return s.entityPath
}
func (s *Sender) getFullIdentifier() string {
return s.namespace.getEntityAudience(s.getAddress())
}
// newSessionAndLink will replace the existing session and link
// NOTE: this does *not* take the write lock, callers must hold it as required!
func (s *Sender) newSessionAndLink(ctx context.Context) error {
ctx, span := s.startProducerSpanFromContext(ctx, "sb.Sender.newSessionAndLink")
defer span.End()
connection, err := s.namespace.newClient(ctx)
if err != nil {
tab.For(ctx).Error(err)
return err
}
s.client = connection
s.cancelAuthRefresh, err = s.namespace.negotiateClaim(ctx, connection, s.getAddress())
if err != nil {
tab.For(ctx).Error(err)
return err
}
amqpSession, err := connection.NewSession()
if err != nil {
tab.For(ctx).Error(err)
return err
}
amqpSender, err := amqpSession.NewSender(
amqp.LinkSenderSettle(amqp.ModeMixed),
amqp.LinkReceiverSettle(amqp.ModeFirst),
amqp.LinkTargetAddress(s.getAddress()))
if err != nil {
tab.For(ctx).Error(err)
return err
}
s.session, err = newSession(amqpSession)
if err != nil {
tab.For(ctx).Error(err)
return err
}
if s.sessionID != nil {
s.session.SessionID = *s.sessionID
}
s.sender = amqpSender
return nil
}
// SenderWithSession configures the message to send with a specific session and sequence. By default, a Sender has a
// default session (uuid.NewV4()) and sequence generator.
func SenderWithSession(sessionID *string) SenderOption {
return func(sender *Sender) error {
sender.sessionID = sessionID
return nil
}
}