This repository has been archived by the owner on Oct 20, 2021. It is now read-only.
forked from Azure/azure-service-bus-go
/
receiver.go
355 lines (300 loc) · 9.11 KB
/
receiver.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
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"
"fmt"
"time"
"pack.ag/amqp"
"github.com/Azure/azure-amqp-common-go"
"github.com/Azure/azure-amqp-common-go/log"
"github.com/opentracing/opentracing-go"
)
// receiver provides session and link handling for a receiving entity path
type (
receiver struct {
namespace *Namespace
connection *amqp.Client
session *session
receiver *amqp.Receiver
entityPath string
done func()
Name string
requiredSessionID *string
lastError error
mode ReceiveMode
prefetch uint32
}
// receiverOption provides a structure for configuring receivers
receiverOption func(receiver *receiver) error
// ListenerHandle provides the ability to close or listen to the close of a Receiver
ListenerHandle struct {
r *receiver
ctx context.Context
}
)
// newReceiver creates a new Service Bus message listener given an AMQP client and an entity path
func (ns *Namespace) newReceiver(ctx context.Context, entityPath string, opts ...receiverOption) (*receiver, error) {
span, ctx := ns.startSpanFromContext(ctx, "sb.Hub.newReceiver")
defer span.Finish()
receiver := &receiver{
namespace: ns,
entityPath: entityPath,
mode: PeekLockMode,
prefetch: 1,
}
for _, opt := range opts {
if err := opt(receiver); err != nil {
return nil, err
}
}
err := receiver.newSessionAndLink(ctx)
return receiver, err
}
// Close will close the AMQP session and link of the receiver
func (r *receiver) Close(ctx context.Context) error {
if r.done != nil {
r.done()
}
return r.connection.Close()
}
// Recover will attempt to close the current session and link, then rebuild them
func (r *receiver) Recover(ctx context.Context) error {
_ = r.Close(ctx) // we expect the receiver is in an error state
return r.newSessionAndLink(ctx)
}
func (r *receiver) ReceiveOne(ctx context.Context) (*MessageWithContext, error) {
span, ctx := r.startConsumerSpanFromContext(ctx, "sb.receiver.ReceiveOne")
defer span.Finish()
amqpMsg, err := r.listenForMessage(ctx)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
msg, err := messageFromAMQPMessage(amqpMsg)
if err != nil {
log.For(ctx).Error(err)
return nil, err
}
return r.messageToMessageWithContext(ctx, msg), nil
}
func (r *receiver) messageToMessageWithContext(ctx context.Context, msg *Message) *MessageWithContext {
const optName = "sb.receiver.amqpEventToMessageWithContext"
var span opentracing.Span
wireContext, err := extractWireContext(msg)
if err == nil {
span, ctx = r.startConsumerSpanFromWire(ctx, optName, wireContext)
} else {
span, ctx = r.startConsumerSpanFromContext(ctx, optName)
}
defer span.Finish()
span.SetTag("amqp.message-id", msg.ID)
return &MessageWithContext{
Message: msg,
Ctx: ctx,
}
}
// Listen start a listener for messages sent to the entity path
func (r *receiver) Listen(handler Handler) *ListenerHandle {
ctx, done := context.WithCancel(context.Background())
r.done = done
span, ctx := r.startConsumerSpanFromContext(ctx, "sb.receiver.Listen")
defer span.Finish()
messages := make(chan *amqp.Message)
go r.listenForMessages(ctx, messages)
go r.handleMessages(ctx, messages, handler)
return &ListenerHandle{
r: r,
ctx: ctx,
}
}
func (r *receiver) handleMessages(ctx context.Context, messages chan *amqp.Message, handler Handler) {
span, ctx := r.startConsumerSpanFromContext(ctx, "sb.receiver.handleMessages")
defer span.Finish()
for {
select {
case <-ctx.Done():
return
case msg := <-messages:
r.handleMessage(ctx, msg, handler)
}
}
}
func (r *receiver) handleMessage(ctx context.Context, msg *amqp.Message, handler Handler) {
const optName = "sb.receiver.handleMessage"
event, err := messageFromAMQPMessage(msg)
if err != nil {
_, ctx := r.startConsumerSpanFromContext(ctx, optName)
log.For(ctx).Error(err)
}
var span opentracing.Span
wireContext, err := extractWireContext(event)
if err == nil {
span, ctx = r.startConsumerSpanFromWire(ctx, optName, wireContext)
} else {
span, ctx = r.startConsumerSpanFromContext(ctx, optName)
}
defer span.Finish()
id := messageID(msg)
span.SetTag("amqp.message-id", id)
dispositionAction := handler(ctx, event)
if r.mode == ReceiveAndDeleteMode {
return
}
if dispositionAction != nil {
dispositionAction(ctx)
} else {
log.For(ctx).Info(fmt.Sprintf("disposition action not provided auto accepted message id %q", id))
event.Complete()
}
}
func extractWireContext(reader opentracing.TextMapReader) (opentracing.SpanContext, error) {
return opentracing.GlobalTracer().Extract(opentracing.TextMap, reader)
}
func (r *receiver) listenForMessages(ctx context.Context, msgChan chan *amqp.Message) {
span, ctx := r.startConsumerSpanFromContext(ctx, "sb.receiver.listenForMessages")
defer span.Finish()
for {
msg, err := r.listenForMessage(ctx)
if ctx.Err() != nil && ctx.Err() == context.DeadlineExceeded {
return
}
if err != nil {
_, retryErr := common.Retry(5, 10*time.Second, func() (interface{}, error) {
sp, ctx := r.startConsumerSpanFromContext(ctx, "sb.receiver.listenForMessages.tryRecover")
defer sp.Finish()
err := r.Recover(ctx)
if ctx.Err() != nil && ctx.Err() == context.DeadlineExceeded {
return nil, ctx.Err()
}
if err != nil {
log.For(ctx).Error(err)
return nil, common.Retryable(err.Error())
}
return nil, nil
})
if retryErr != nil {
r.lastError = retryErr
r.Close(ctx)
return
}
continue
}
select {
case msgChan <- msg:
case <-ctx.Done():
return
}
}
}
func (r *receiver) listenForMessage(ctx context.Context) (*amqp.Message, error) {
span, ctx := r.startConsumerSpanFromContext(ctx, "sb.receiver.listenForMessage")
defer span.Finish()
msg, err := r.receiver.Receive(ctx)
if err != nil {
log.For(ctx).Debug(err.Error())
return nil, err
}
id := messageID(msg)
span.SetTag("amqp.message-id", id)
return msg, nil
}
// newSessionAndLink will replace the session and link on the receiver
func (r *receiver) newSessionAndLink(ctx context.Context) error {
connection, err := r.namespace.newConnection()
if err != nil {
return err
}
r.connection = connection
err = r.namespace.negotiateClaim(ctx, connection, r.entityPath)
if err != nil {
log.For(ctx).Error(err)
return err
}
amqpSession, err := connection.NewSession()
if err != nil {
log.For(ctx).Error(err)
return err
}
r.session, err = newSession(amqpSession)
if err != nil {
log.For(ctx).Error(err)
return err
}
receiveMode := amqp.ModeSecond
sendMode := amqp.ModeUnsettled
if r.mode == ReceiveAndDeleteMode {
receiveMode = amqp.ModeFirst
sendMode = amqp.ModeSettled
}
opts := []amqp.LinkOption{
amqp.LinkSourceAddress(r.entityPath),
amqp.LinkSenderSettle(sendMode),
amqp.LinkReceiverSettle(receiveMode),
amqp.LinkCredit(r.prefetch),
}
if r.requiredSessionID != nil {
opts = append(opts, amqp.LinkSessionFilter(*r.requiredSessionID))
r.session.SessionID = *r.requiredSessionID
}
amqpReceiver, err := amqpSession.NewReceiver(opts...)
if err != nil {
return err
}
r.receiver = amqpReceiver
return nil
}
// receiverWithSession configures a receiver to use a session
func receiverWithSession(sessionID string) receiverOption {
return func(r *receiver) error {
r.requiredSessionID = &sessionID
return nil
}
}
func receiverWithReceiveMode(mode ReceiveMode) receiverOption {
return func(r *receiver) error {
r.mode = mode
return nil
}
}
func messageID(msg *amqp.Message) interface{} {
var id interface{} = "null"
if msg.Properties != nil {
id = msg.Properties.MessageID
}
return id
}
// Close will close the listener
func (lc *ListenerHandle) Close(ctx context.Context) error {
return lc.r.Close(ctx)
}
// Done will close the channel when the listener has stopped
func (lc *ListenerHandle) Done() <-chan struct{} {
return lc.ctx.Done()
}
// Err will return the last error encountered
func (lc *ListenerHandle) Err() error {
if lc.r.lastError != nil {
return lc.r.lastError
}
return lc.ctx.Err()
}