Debian Codegraph @

pubsub/azuresb/azuresb.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package azuresb provides an implementation of pubsub using Azure Service
16 // Bus Topic and Subscription.
17 // See https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-overview for an overview.
18 //
19 // # URLs
20 //
21 // For pubsub.OpenTopic and pubsub.OpenSubscription, azuresb registers
22 // for the scheme "azuresb".
23 // The default URL opener will use a Service Bus Connection String based on
24 // AZURE_SERVICEBUS_HOSTNAME or SERVICEBUS_CONNECTION_STRING environment variables.
25 // SERVICEBUS_CONNECTION_STRING takes precedence.
26 // To customize the URL opener, or for more details on the URL format,
27 // see URLOpener.
28 // See https://gocloud.dev/concepts/urls/ for background information.
29 //
30 // # Message Delivery Semantics
31 //
32 // Azure ServiceBus supports at-least-once semantics in the default Peek-Lock
33 // mode; messages will be redelivered if they are not Acked, or if they are
34 // explicitly Nacked.
35 //
36 // ServiceBus also supports a Receive-Delete mode, which essentially auto-acks a
37 // message when it is delivered, resulting in at-most-once semantics. Set
38 // SubscriberOptions.ReceiveAndDelete to true to tell azuresb.Subscription that
39 // you've enabled Receive-Delete mode. When enabled, pubsub.Message.Ack is a
40 // no-op, pubsub.Message.Nackable will return false, and pubsub.Message.Nack
41 // will panic.
42 //
43 // See https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
44 // for more background.
45 //
46 // # As
47 //
48 // azuresb exposes the following types for As:
49 // - Topic: *servicebus.Topic
50 // - Subscription: *servicebus.Subscription
51 // - Message.BeforeSend: *servicebus.Message
52 // - Message.AfterSend: None
53 // - Message: *servicebus.Message
54 // - Error: common.Retryable, *amqp.Error, *amqp.LinkError
55 package azuresb // import "gocloud.dev/pubsub/azuresb"
56
57 import (
58 "context"
59 "errors"
60 "fmt"
61 "net/url"
62 "os"
63 "path"
64 "strconv"
65 "strings"
66 "sync"
67 "time"
68
69 common "github.com/Azure/azure-amqp-common-go/v3"
70 "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
71 servicebus "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus"
72 "github.com/Azure/go-amqp"
73 "gocloud.dev/gcerrors"
74 "gocloud.dev/pubsub"
75 "gocloud.dev/pubsub/batcher"
76 "gocloud.dev/pubsub/driver"
77 )
78
79 const (
80 defaultListenerTimeout = 2 * time.Second
81 )
82
83 var sendBatcherOpts = &batcher.Options{
84 MaxBatchSize: 1, // SendBatch only supports one message at a time
85 MaxHandlers: 100, // max concurrency for sends
86 }
87
88 var recvBatcherOpts = &batcher.Options{
89 MaxBatchSize: 50,
90 MaxHandlers: 100, // max concurrency for reads
91 }
92
93 var ackBatcherOpts = &batcher.Options{
94 MaxBatchSize: 1,
95 MaxHandlers: 100, // max concurrency for acks
96 }
97
98 func init() {
99 o := new(defaultOpener)
100 pubsub.DefaultURLMux().RegisterTopic(Scheme, o)
101 pubsub.DefaultURLMux().RegisterSubscription(Scheme, o)
102 }
103
104 // defaultURLOpener creates an URLOpener with ConnectionString initialized from
105 // AZURE_SERVICEBUS_HOSTNAME or SERVICEBUS_CONNECTION_STRING environment variables.
106 // SERVICEBUS_CONNECTION_STRING takes precedence.
107 type defaultOpener struct {
108 init sync.Once
109 opener *URLOpener
110 err error
111 }
112
113 func (o *defaultOpener) defaultOpener() (*URLOpener, error) {
114 o.init.Do(func() {
115 cs := os.Getenv("SERVICEBUS_CONNECTION_STRING")
116 sbHostname := os.Getenv("AZURE_SERVICEBUS_HOSTNAME")
117 if cs == "" && sbHostname == "" {
118 o.err = errors.New("Neither SERVICEBUS_CONNECTION_STRING nor AZURE_SERVICEBUS_HOSTNAME environment variables are set")
119 return
120 }
121 o.opener = &URLOpener{ConnectionString: cs, ServiceBusHostname: sbHostname}
122 })
123 return o.opener, o.err
124 }
125
126 func (o *defaultOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
127 opener, err := o.defaultOpener()
128 if err != nil {
129 return nil, fmt.Errorf("open topic %v: %v", u, err)
130 }
131 return opener.OpenTopicURL(ctx, u)
132 }
133
134 func (o *defaultOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
135 opener, err := o.defaultOpener()
136 if err != nil {
137 return nil, fmt.Errorf("open subscription %v: %v", u, err)
138 }
139 return opener.OpenSubscriptionURL(ctx, u)
140 }
141
142 // Scheme is the URL scheme azuresb registers its URLOpeners under on pubsub.DefaultMux.
143 const Scheme = "azuresb"
144
145 // URLOpener opens Azure Service Bus URLs like "azuresb://mytopic" for
146 // topics or "azuresb://mytopic?subscription=mysubscription" for subscriptions.
147 //
148 // - The URL's host+path is used as the topic name.
149 // - For subscriptions, the subscription name must be provided in the
150 // "subscription" query parameter.
151 // - For subscriptions, the ListenerTimeout can be overridden with time.Duration parseable values in "listener_timeout".
152 //
153 // No other query parameters are supported.
154 type URLOpener struct {
155 // ConnectionString is the Service Bus connection string (required if ServiceBusHostname is not defined).
156 // https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
157 ConnectionString string
158
159 // Azure ServiceBus hostname.
160 // https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-go-how-to-use-queues?tabs=bash
161 ServiceBusHostname string
162
163 // ClientOptions are options when creating the Client.
164 ServiceBusClientOptions *servicebus.ClientOptions
165
166 // Options passed when creating the ServiceBus Topic/Subscription.
167 ServiceBusSenderOptions *servicebus.NewSenderOptions
168 ServiceBusReceiverOptions *servicebus.ReceiverOptions
169
170 // TopicOptions specifies the options to pass to OpenTopic.
171 TopicOptions TopicOptions
172 // SubscriptionOptions specifies the options to pass to OpenSubscription.
173 SubscriptionOptions SubscriptionOptions
174 }
175
176 func (o *URLOpener) sbClient(kind string, u *url.URL) (*servicebus.Client, error) {
177 if o.ConnectionString == "" && o.ServiceBusHostname == "" {
178 return nil, fmt.Errorf("open %s %v: one of ConnectionString or ServiceBusHostname is required", kind, u)
179 }
180
181 // Auth using shared key.
182 if o.ConnectionString != "" {
183 client, err := NewClientFromConnectionString(o.ConnectionString, o.ServiceBusClientOptions)
184 if err != nil {
185 return nil, fmt.Errorf("open %s %v: invalid connection string %q: %v", kind, u, o.ConnectionString, err)
186 }
187 return client, nil
188 }
189
190 // Auth using Azure AAD Workload Identity/AAD Pod Identities/AKS Kubelet Identity/Service Principal.
191 client, err := NewClientFromServiceBusHostname(o.ServiceBusHostname, o.ServiceBusClientOptions)
192 if err != nil {
193 return nil, fmt.Errorf("open %s %v: invalid service bus hostname %q: %v", kind, u, o.ServiceBusHostname, err)
194 }
195 return client, nil
196 }
197
198 // OpenTopicURL opens a pubsub.Topic based on u.
199 func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
200 sbClient, err := o.sbClient("topic", u)
201 if err != nil {
202 return nil, err
203 }
204 for param := range u.Query() {
205 return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param)
206 }
207 topicName := path.Join(u.Host, u.Path)
208 sbSender, err := NewSender(sbClient, topicName, o.ServiceBusSenderOptions)
209 if err != nil {
210 return nil, fmt.Errorf("open topic %v: couldn't open topic %q: %v", u, topicName, err)
211 }
212 return OpenTopic(ctx, sbSender, &o.TopicOptions)
213 }
214
215 // OpenSubscriptionURL opens a pubsub.Subscription based on u.
216 func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
217 sbClient, err := o.sbClient("subscription", u)
218 if err != nil {
219 return nil, err
220 }
221 topicName := path.Join(u.Host, u.Path)
222 q := u.Query()
223 subName := q.Get("subscription")
224 q.Del("subscription")
225 if subName == "" {
226 return nil, fmt.Errorf("open subscription %v: missing required query parameter subscription", u)
227 }
228 opts := o.SubscriptionOptions
229 if lts := q.Get("listener_timeout"); lts != "" {
230 q.Del("listener_timeout")
231 d, err := time.ParseDuration(lts)
232 if err != nil {
233 return nil, fmt.Errorf("open subscription %v: invalid listener_timeout %q: %v", u, lts, err)
234 }
235 opts.ListenerTimeout = d
236 }
237 if mrbss := q.Get("max_recv_batch_size"); mrbss != "" {
238 q.Del("max_recv_batch_size")
239 mrbs, err := strconv.Atoi(mrbss)
240 if err != nil {
241 return nil, fmt.Errorf("open subscription %v: invalid max_recv_batch_size %q: %v", u, mrbss, err)
242 }
243 opts.ReceiveBatcherOptions.MaxBatchSize = mrbs
244 }
245 for param := range q {
246 return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param)
247 }
248 sbReceiver, err := NewReceiver(sbClient, topicName, subName, o.ServiceBusReceiverOptions)
249 if err != nil {
250 return nil, fmt.Errorf("open subscription %v: couldn't open subscription %q: %v", u, subName, err)
251 }
252 return OpenSubscription(ctx, sbClient, sbReceiver, &opts)
253 }
254
255 type topic struct {
256 sbSender *servicebus.Sender
257 }
258
259 // TopicOptions provides configuration options for an Azure SB Topic.
260 type TopicOptions struct {
261 // BatcherOptions adds constraints to the default batching done for sends.
262 BatcherOptions batcher.Options
263 }
264
265 // NewClientFromConnectionString returns a *servicebus.Client from a Service Bus connection string, using shared key for auth.
266 // https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
267 func NewClientFromConnectionString(connectionString string, opts *servicebus.ClientOptions) (*servicebus.Client, error) {
268 return servicebus.NewClientFromConnectionString(connectionString, opts)
269 }
270
271 // NewClientFromConnectionString returns a *servicebus.Client from a Service Bus connection string, using shared key for auth.
272 // for example you can use workload identity autorization.
273 // https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-go-how-to-use-queues?tabs=bash
274 func NewClientFromServiceBusHostname(serviceBusHostname string, opts *servicebus.ClientOptions) (*servicebus.Client, error) {
275 cred, err := azidentity.NewDefaultAzureCredential(nil)
276 if err != nil {
277 return nil, err
278 }
279 client, err := servicebus.NewClient(serviceBusHostname, cred, opts)
280 if err != nil {
281 return nil, err
282 }
283 return client, nil
284 }
285
286 // NewSender returns a *servicebus.Sender associated with a Service Bus Client.
287 func NewSender(sbClient *servicebus.Client, topicName string, opts *servicebus.NewSenderOptions) (*servicebus.Sender, error) {
288 return sbClient.NewSender(topicName, opts)
289 }
290
291 // NewReceiver returns a *servicebus.Receiver associated with a Service Bus Topic.
292 func NewReceiver(sbClient *servicebus.Client, topicName, subscriptionName string, opts *servicebus.ReceiverOptions) (*servicebus.Receiver, error) {
293 return sbClient.NewReceiverForSubscription(topicName, subscriptionName, opts)
294 }
295
296 // OpenTopic initializes a pubsub Topic on a given Service Bus Sender.
297 func OpenTopic(ctx context.Context, sbSender *servicebus.Sender, opts *TopicOptions) (*pubsub.Topic, error) {
298 t, err := openTopic(ctx, sbSender, opts)
299 if err != nil {
300 return nil, err
301 }
302 if opts == nil {
303 opts = &TopicOptions{}
304 }
305 bo := sendBatcherOpts.NewMergedOptions(&opts.BatcherOptions)
306 return pubsub.NewTopic(t, bo), nil
307 }
308
309 // openTopic returns the driver for OpenTopic. This function exists so the test
310 // harness can get the driver interface implementation if it needs to.
311 func openTopic(ctx context.Context, sbSender *servicebus.Sender, _ *TopicOptions) (driver.Topic, error) {
312 if sbSender == nil {
313 return nil, errors.New("azuresb: OpenTopic requires a Service Bus Sender")
314 }
315 return &topic{sbSender: sbSender}, nil
316 }
317
318 // SendBatch implements driver.Topic.SendBatch.
319 func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error {
320 if len(dms) != 1 {
321 panic("azuresb.SendBatch should only get one message at a time")
322 }
323 dm := dms[0]
324 sbms := &servicebus.Message{Body: dm.Body}
325 if len(dm.Metadata) > 0 {
326 sbms.ApplicationProperties = map[string]any{}
327 for k, v := range dm.Metadata {
328 sbms.ApplicationProperties[k] = v
329 }
330 }
331 if dm.BeforeSend != nil {
332 asFunc := func(i any) bool {
333 if p, ok := i.(**servicebus.Message); ok {
334 *p = sbms
335 return true
336 }
337 return false
338 }
339 if err := dm.BeforeSend(asFunc); err != nil {
340 return err
341 }
342 }
343 err := t.sbSender.SendMessage(ctx, sbms, nil)
344 if err != nil {
345 return err
346 }
347 if dm.AfterSend != nil {
348 asFunc := func(i any) bool { return false }
349 if err := dm.AfterSend(asFunc); err != nil {
350 return err
351 }
352 }
353 return nil
354 }
355
356 func (t *topic) IsRetryable(err error) bool {
357 _, retryable := errorCode(err)
358 return retryable
359 }
360
361 func (t *topic) As(i any) bool {
362 p, ok := i.(**servicebus.Sender)
363 if !ok {
364 return false
365 }
366 *p = t.sbSender
367 return true
368 }
369
370 // ErrorAs implements driver.Topic.ErrorAs
371 func (*topic) ErrorAs(err error, i any) bool {
372 return errorAs(err, i)
373 }
374
375 func errorAs(err error, i any) bool {
376 switch v := err.(type) {
377 case *amqp.LinkError:
378 if p, ok := i.(**amqp.LinkError); ok {
379 *p = v
380 return true
381 }
382 case *amqp.Error:
383 if p, ok := i.(**amqp.Error); ok {
384 *p = v
385 return true
386 }
387 case common.Retryable:
388 if p, ok := i.(*common.Retryable); ok {
389 *p = v
390 return true
391 }
392 }
393 return false
394 }
395
396 func (*topic) ErrorCode(err error) gcerrors.ErrorCode {
397 code, _ := errorCode(err)
398 return code
399 }
400
401 // Close implements driver.Topic.Close.
402 func (*topic) Close() error { return nil }
403
404 type subscription struct {
405 sbReceiver *servicebus.Receiver
406 opts *SubscriptionOptions
407 }
408
409 // SubscriptionOptions will contain configuration for subscriptions.
410 type SubscriptionOptions struct {
411 // If false, the serviceBus.Subscription MUST be in the default Peek-Lock mode.
412 // If true, the serviceBus.Subscription MUST be in Receive-and-Delete mode.
413 // When true: pubsub.Message.Ack will be a no-op, pubsub.Message.Nackable
414 // will return true, and pubsub.Message.Nack will panic.
415 ReceiveAndDelete bool
416
417 // ReceiveBatcherOptions adds constraints to the default batching done for receives.
418 ReceiveBatcherOptions batcher.Options
419
420 // AckBatcherOptions adds constraints to the default batching done for acks.
421 // Only used when ReceiveAndDelete is false.
422 AckBatcherOptions batcher.Options
423
424 // ListenerTimeout is the amount of time to wait before timing out the
425 // ReceiveMessages RPC call. This is used to ensure the receive operation is
426 // non-blocking as the RPC blocks if there are no messages.
427 // Defaults to 2 seconds.
428 ListenerTimeout time.Duration
429 }
430
431 // OpenSubscription initializes a pubsub Subscription on a given Service Bus Subscription and its parent Service Bus Topic.
432 func OpenSubscription(ctx context.Context, sbClient *servicebus.Client, sbReceiver *servicebus.Receiver, opts *SubscriptionOptions) (*pubsub.Subscription, error) {
433 ds, err := openSubscription(ctx, sbClient, sbReceiver, opts)
434 if err != nil {
435 return nil, err
436 }
437 if opts == nil {
438 opts = &SubscriptionOptions{}
439 }
440 rbo := recvBatcherOpts.NewMergedOptions(&opts.ReceiveBatcherOptions)
441 abo := ackBatcherOpts.NewMergedOptions(&opts.AckBatcherOptions)
442 return pubsub.NewSubscription(ds, rbo, abo), nil
443 }
444
445 // openSubscription returns a driver.Subscription.
446 func openSubscription(ctx context.Context, sbClient *servicebus.Client, sbReceiver *servicebus.Receiver, opts *SubscriptionOptions) (driver.Subscription, error) {
447 if sbClient == nil {
448 return nil, errors.New("azuresb: OpenSubscription requires a Service Bus Client")
449 }
450 if sbReceiver == nil {
451 return nil, errors.New("azuresb: OpenSubscription requires a Service Bus Receiver")
452 }
453 if opts == nil {
454 opts = &SubscriptionOptions{}
455 }
456 if opts.ListenerTimeout == 0 {
457 opts.ListenerTimeout = defaultListenerTimeout
458 }
459 return &subscription{sbReceiver: sbReceiver, opts: opts}, nil
460 }
461
462 // IsRetryable implements driver.Subscription.IsRetryable.
463 func (s *subscription) IsRetryable(err error) bool {
464 _, retryable := errorCode(err)
465 return retryable
466 }
467
468 // As implements driver.Subscription.As.
469 func (s *subscription) As(i any) bool {
470 p, ok := i.(**servicebus.Receiver)
471 if !ok {
472 return false
473 }
474 *p = s.sbReceiver
475 return true
476 }
477
478 // ErrorAs implements driver.Subscription.ErrorAs
479 func (s *subscription) ErrorAs(err error, i any) bool {
480 return errorAs(err, i)
481 }
482
483 func (s *subscription) ErrorCode(err error) gcerrors.ErrorCode {
484 code, _ := errorCode(err)
485 return code
486 }
487
488 // ReceiveBatch implements driver.Subscription.ReceiveBatch.
489 func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
490 // ReceiveMessages will block until rctx is Done; we want to return after
491 // a reasonably short delay even if there are no messages. So, create a
492 // sub context for the RPC.
493 rctx, cancel := context.WithTimeout(ctx, s.opts.ListenerTimeout)
494 defer cancel()
495
496 var messages []*driver.Message
497 sbmsgs, err := s.sbReceiver.ReceiveMessages(rctx, maxMessages, nil)
498 for _, sbmsg := range sbmsgs {
499 metadata := map[string]string{}
500 for key, value := range sbmsg.ApplicationProperties {
501 if strVal, ok := value.(string); ok {
502 metadata[key] = strVal
503 }
504 }
505 messages = append(messages, &driver.Message{
506 LoggableID: sbmsg.MessageID,
507 Body: sbmsg.Body,
508 Metadata: metadata,
509 AckID: sbmsg,
510 AsFunc: messageAsFunc(sbmsg),
511 })
512 }
513 // Mask rctx timeouts, they are expected if no messages are available.
514 if err == rctx.Err() {
515 err = nil
516 }
517 return messages, err
518 }
519
520 func messageAsFunc(sbmsg *servicebus.ReceivedMessage) func(any) bool {
521 return func(i any) bool {
522 p, ok := i.(**servicebus.ReceivedMessage)
523 if !ok {
524 return false
525 }
526 *p = sbmsg
527 return true
528 }
529 }
530
531 // SendAcks implements driver.Subscription.SendAcks.
532 func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error {
533 if s.opts.ReceiveAndDelete {
534 // Ack is a no-op in Receive-and-Delete mode.
535 return nil
536 }
537 var err error
538 for _, id := range ids {
539 oneErr := s.sbReceiver.CompleteMessage(ctx, id.(*servicebus.ReceivedMessage), nil)
540 if oneErr != nil {
541 err = oneErr
542 }
543 }
544 return err
545 }
546
547 // CanNack implements driver.CanNack.
548 func (s *subscription) CanNack() bool {
549 if s == nil {
550 return false
551 }
552 return !s.opts.ReceiveAndDelete
553 }
554
555 // SendNacks implements driver.Subscription.SendNacks.
556 func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error {
557 if !s.CanNack() {
558 panic("unreachable")
559 }
560 var err error
561 for _, id := range ids {
562 oneErr := s.sbReceiver.AbandonMessage(ctx, id.(*servicebus.ReceivedMessage), nil)
563 if oneErr != nil {
564 err = oneErr
565 }
566 }
567 return err
568 }
569
570 // errorCode returns an error code and whether err is retryable.
571 func errorCode(err error) (gcerrors.ErrorCode, bool) {
572 // Unfortunately Azure sometimes returns common.Retryable or even
573 // errors.errorString, which don't expose anything other than the error
574 // string :-(.
575 if strings.Contains(err.Error(), "status code 404") {
576 return gcerrors.NotFound, false
577 }
578 if strings.Contains(err.Error(), "status code 401") {
579 return gcerrors.PermissionDenied, false
580 }
581 var cond amqp.ErrCond
582 var aderr *amqp.LinkError
583 var aerr *amqp.Error
584 if errors.As(err, &aderr) {
585 if aderr.RemoteErr == nil {
586 return gcerrors.NotFound, false
587 }
588 cond = aderr.RemoteErr.Condition
589 } else if errors.As(err, &aerr) {
590 cond = aerr.Condition
591 }
592 switch cond {
593 case amqp.ErrCondNotFound:
594 return gcerrors.NotFound, false
595
596 case amqp.ErrCondPreconditionFailed:
597 return gcerrors.FailedPrecondition, false
598
599 case amqp.ErrCondInternalError:
600 return gcerrors.Internal, true
601
602 case amqp.ErrCondNotImplemented:
603 return gcerrors.Unimplemented, false
604
605 case amqp.ErrCondUnauthorizedAccess, amqp.ErrCondNotAllowed:
606 return gcerrors.PermissionDenied, false
607
608 case amqp.ErrCondResourceLimitExceeded:
609 return gcerrors.ResourceExhausted, true
610
611 case amqp.ErrCondInvalidField:
612 return gcerrors.InvalidArgument, false
613 }
614 return gcerrors.Unknown, true
615 }
616
617 // Close implements driver.Subscription.Close.
618 func (*subscription) Close() error { return nil }