-
Notifications
You must be signed in to change notification settings - Fork 824
/
client.go
359 lines (295 loc) · 11.9 KB
/
client.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azservicebus
import (
"context"
"crypto/tls"
"errors"
"net"
"sync"
"sync/atomic"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/exported"
)
// Client provides methods to create Sender and Receiver
// instances to send and receive messages from Service Bus.
type Client struct {
// NOTE: values need to be 64-bit aligned. Simplest way to make sure this happens
// is just to make it the first value in the struct
// See:
// Godoc: https://pkg.go.dev/sync/atomic#pkg-note-BUG
// PR: https://github.com/Azure/azure-sdk-for-go/pull/16847
linkCounter uint64
linksMu *sync.Mutex
links map[uint64]internal.Closeable
creds clientCreds
namespace interface {
// used internally by `Client`
internal.NamespaceWithNewAMQPLinks
// for child clients
internal.NamespaceForAMQPLinks
}
retryOptions RetryOptions
}
// ClientOptions contains options for the `NewClient` and `NewClientFromConnectionString`
// functions.
type ClientOptions struct {
// TLSConfig configures a client with a custom *tls.Config.
TLSConfig *tls.Config
// Application ID that will be passed to the namespace.
ApplicationID string
// NewWebSocketConn is a function that can create a net.Conn for use with websockets.
// For an example, see ExampleNewClient_usingWebsockets() function in example_client_test.go.
NewWebSocketConn func(ctx context.Context, args NewWebSocketConnArgs) (net.Conn, error)
// RetryOptions controls how often operations are retried from this client and any
// Receivers and Senders created from this client.
RetryOptions RetryOptions
}
// RetryOptions controls how often operations are retried from this client and any
// Receivers and Senders created from this client.
type RetryOptions = exported.RetryOptions
// NewWebSocketConnArgs are passed to your web socket creation function (ClientOptions.NewWebSocketConn)
type NewWebSocketConnArgs = exported.NewWebSocketConnArgs
// NewClient creates a new Client for a Service Bus namespace, using a TokenCredential.
// A Client allows you create receivers (for queues or subscriptions) and senders (for queues and topics).
// fullyQualifiedNamespace is the Service Bus namespace name (ex: myservicebus.servicebus.windows.net)
// credential is one of the credentials in the `github.com/Azure/azure-sdk-for-go/sdk/azidentity` package.
func NewClient(fullyQualifiedNamespace string, credential azcore.TokenCredential, options *ClientOptions) (*Client, error) {
if fullyQualifiedNamespace == "" {
return nil, errors.New("fullyQualifiedNamespace must not be empty")
}
if credential == nil {
return nil, errors.New("credential was nil")
}
return newClientImpl(clientCreds{
credential: credential,
fullyQualifiedNamespace: fullyQualifiedNamespace,
}, options)
}
// NewClientFromConnectionString creates a new Client for a Service Bus namespace using a connection string.
// A Client allows you create receivers (for queues or subscriptions) and senders (for queues and topics).
// connectionString can be a Service Bus connection string for the namespace or for an entity, which contains a
// SharedAccessKeyName and SharedAccessKey properties (for instance, from the Azure Portal):
// Endpoint=sb://<sb>.servicebus.windows.net/;SharedAccessKeyName=<key name>;SharedAccessKey=<key value>
// Or it can be a connection string with a SharedAccessSignature:
// Endpoint=sb://<sb>.servicebus.windows.net;SharedAccessSignature=SharedAccessSignature sr=<sb>.servicebus.windows.net&sig=<base64-sig>&se=<expiry>&skn=<keyname>
func NewClientFromConnectionString(connectionString string, options *ClientOptions) (*Client, error) {
if connectionString == "" {
return nil, errors.New("connectionString must not be empty")
}
return newClientImpl(clientCreds{
connectionString: connectionString,
}, options)
}
// Next overloads (ie, credential sticks with the client)
// func NewClientWithNamedKeyCredential(fullyQualifiedNamespace string, credential azcore.TokenCredential, options *ClientOptions) (*Client, error) {
// }
type clientCreds struct {
connectionString string
// the Service Bus namespace name (ex: myservicebus.servicebus.windows.net)
fullyQualifiedNamespace string
credential azcore.TokenCredential
}
func newClientImpl(creds clientCreds, options *ClientOptions) (*Client, error) {
client := &Client{
linksMu: &sync.Mutex{},
creds: creds,
links: map[uint64]internal.Closeable{},
}
var err error
var nsOptions []internal.NamespaceOption
if client.creds.connectionString != "" {
nsOptions = append(nsOptions, internal.NamespaceWithConnectionString(client.creds.connectionString))
} else if client.creds.credential != nil {
option := internal.NamespaceWithTokenCredential(
client.creds.fullyQualifiedNamespace,
client.creds.credential)
nsOptions = append(nsOptions, option)
}
if options != nil {
client.retryOptions = options.RetryOptions
if options.TLSConfig != nil {
nsOptions = append(nsOptions, internal.NamespaceWithTLSConfig(options.TLSConfig))
}
if options.NewWebSocketConn != nil {
nsOptions = append(nsOptions, internal.NamespaceWithWebSocket(options.NewWebSocketConn))
}
if options.ApplicationID != "" {
nsOptions = append(nsOptions, internal.NamespaceWithUserAgent(options.ApplicationID))
}
nsOptions = append(nsOptions, internal.NamespaceWithRetryOptions(options.RetryOptions))
}
client.namespace, err = internal.NewNamespace(nsOptions...)
return client, err
}
// NewReceiverForQueue creates a Receiver for a queue. A receiver allows you to receive messages.
func (client *Client) NewReceiverForQueue(queueName string, options *ReceiverOptions) (*Receiver, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
receiver, err := newReceiver(newReceiverArgs{
cleanupOnClose: cleanupOnClose,
ns: client.namespace,
entity: entity{Queue: queueName},
getRecoveryKindFunc: internal.GetRecoveryKind,
retryOptions: client.retryOptions,
}, options)
if err != nil {
return nil, err
}
client.addCloseable(id, receiver)
return receiver, nil
}
// NewReceiverForSubscription creates a Receiver for a subscription. A receiver allows you to receive messages.
func (client *Client) NewReceiverForSubscription(topicName string, subscriptionName string, options *ReceiverOptions) (*Receiver, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
receiver, err := newReceiver(newReceiverArgs{
cleanupOnClose: cleanupOnClose,
ns: client.namespace,
entity: entity{Topic: topicName, Subscription: subscriptionName},
getRecoveryKindFunc: internal.GetRecoveryKind,
retryOptions: client.retryOptions,
}, options)
if err != nil {
return nil, err
}
client.addCloseable(id, receiver)
return receiver, nil
}
// NewSenderOptions contains optional parameters for Client.NewSender
type NewSenderOptions struct {
// For future expansion
}
// NewSender creates a Sender, which allows you to send messages or schedule messages.
func (client *Client) NewSender(queueOrTopic string, options *NewSenderOptions) (*Sender, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
sender, err := newSender(newSenderArgs{
ns: client.namespace,
queueOrTopic: queueOrTopic,
cleanupOnClose: cleanupOnClose,
retryOptions: client.retryOptions,
})
if err != nil {
return nil, err
}
client.addCloseable(id, sender)
return sender, nil
}
// AcceptSessionForQueue accepts a session from a queue with a specific session ID.
// NOTE: this receiver is initialized immediately, not lazily.
func (client *Client) AcceptSessionForQueue(ctx context.Context, queueName string, sessionID string, options *SessionReceiverOptions) (*SessionReceiver, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
sessionReceiver, err := newSessionReceiver(
ctx,
newSessionReceiverArgs{
sessionID: &sessionID,
ns: client.namespace,
entity: entity{Queue: queueName},
cleanupOnClose: cleanupOnClose,
retryOptions: client.retryOptions,
}, toReceiverOptions(options))
if err != nil {
return nil, err
}
if err := sessionReceiver.init(ctx); err != nil {
return nil, err
}
client.addCloseable(id, sessionReceiver)
return sessionReceiver, nil
}
// AcceptSessionForSubscription accepts a session from a subscription with a specific session ID.
// NOTE: this receiver is initialized immediately, not lazily.
func (client *Client) AcceptSessionForSubscription(ctx context.Context, topicName string, subscriptionName string, sessionID string, options *SessionReceiverOptions) (*SessionReceiver, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
sessionReceiver, err := newSessionReceiver(
ctx,
newSessionReceiverArgs{
sessionID: &sessionID,
ns: client.namespace,
entity: entity{Topic: topicName, Subscription: subscriptionName},
cleanupOnClose: cleanupOnClose,
retryOptions: client.retryOptions,
},
toReceiverOptions(options))
if err != nil {
return nil, err
}
if err := sessionReceiver.init(ctx); err != nil {
return nil, err
}
client.addCloseable(id, sessionReceiver)
return sessionReceiver, nil
}
// AcceptNextSessionForQueue accepts the next available session from a queue.
// NOTE: this receiver is initialized immediately, not lazily.
func (client *Client) AcceptNextSessionForQueue(ctx context.Context, queueName string, options *SessionReceiverOptions) (*SessionReceiver, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
sessionReceiver, err := newSessionReceiver(
ctx,
newSessionReceiverArgs{
sessionID: nil,
ns: client.namespace,
entity: entity{Queue: queueName},
cleanupOnClose: cleanupOnClose,
retryOptions: client.retryOptions,
}, toReceiverOptions(options))
if err != nil {
return nil, err
}
if err := sessionReceiver.init(ctx); err != nil {
return nil, err
}
client.addCloseable(id, sessionReceiver)
return sessionReceiver, nil
}
// AcceptNextSessionForSubscription accepts the next available session from a subscription.
// NOTE: this receiver is initialized immediately, not lazily.
func (client *Client) AcceptNextSessionForSubscription(ctx context.Context, topicName string, subscriptionName string, options *SessionReceiverOptions) (*SessionReceiver, error) {
id, cleanupOnClose := client.getCleanupForCloseable()
sessionReceiver, err := newSessionReceiver(
ctx,
newSessionReceiverArgs{
sessionID: nil,
ns: client.namespace,
entity: entity{Topic: topicName, Subscription: subscriptionName},
cleanupOnClose: cleanupOnClose,
retryOptions: client.retryOptions,
}, toReceiverOptions(options))
if err != nil {
return nil, err
}
if err := sessionReceiver.init(ctx); err != nil {
return nil, err
}
client.addCloseable(id, sessionReceiver)
return sessionReceiver, nil
}
// Close closes the current connection Service Bus as well as any Senders or Receivers created
// using this client.
func (client *Client) Close(ctx context.Context) error {
var links []internal.Closeable
client.linksMu.Lock()
for _, link := range client.links {
links = append(links, link)
}
client.linksMu.Unlock()
for _, link := range links {
if err := link.Close(ctx); err != nil {
log.Writef(EventConn, "Failed to close link (error might be cached): %s", err.Error())
}
}
return client.namespace.Close(ctx, true)
}
func (client *Client) addCloseable(id uint64, closeable internal.Closeable) {
client.linksMu.Lock()
client.links[id] = closeable
client.linksMu.Unlock()
}
func (client *Client) getCleanupForCloseable() (uint64, func()) {
id := atomic.AddUint64(&client.linkCounter, 1)
return id, func() {
client.linksMu.Lock()
delete(client.links, id)
client.linksMu.Unlock()
}
}