Debian Codegraph @

pubsub/pubsub.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 pubsub provides an easy and portable way to interact with
16 // publish/subscribe systems. Subpackages contain driver implementations of
17 // pubsub for supported services
18 //
19 // See https://gocloud.dev/howto/pubsub/ for a detailed how-to guide.
20 //
21 // # At-most-once and At-least-once Delivery
22 //
23 // The semantics of message delivery vary across PubSub services.
24 // Some services guarantee that messages received by subscribers but not
25 // acknowledged are delivered again (at-least-once semantics). In others,
26 // a message will be delivered only once, if it is delivered at all
27 // (at-most-once semantics). Some services support both modes via options.
28 //
29 // This package accommodates both kinds of systems, but application developers
30 // should think carefully about which kind of semantics the application needs.
31 // Even though the application code may look similar, system-level
32 // characteristics are quite different. See the driver package
33 // documentation for more information about message delivery semantics.
34 //
35 // After receiving a Message via Subscription.Receive:
36 // - Always call Message.Ack or Message.Nack after processing the message.
37 // - For some drivers, Ack will be a no-op.
38 // - For some drivers, Nack is not supported and will panic; you can call
39 // Message.Nackable to see.
40 //
41 // # OpenTelemetry Integration.
42 //
43 // OpenTelemetry supports tracing and metric collection for multiple languages and
44 // backend providers. See https://opentelemetry.io.
45 //
46 // This API collects OpenTelemetry traces and metrics for the following methods:
47 // - Topic.Send
48 // - Topic.Shutdown
49 // - Subscription.Receive
50 // - Subscription.Shutdown
51 // - The internal driver methods SendBatch, SendAcks and ReceiveBatch.
52 //
53 // All trace and metric names begin with the package import path.
54 // The traces add the method name.
55 // For example, "gocloud.dev/pubsub/Topic.Send".
56 // The metrics are "completed_calls", a count of completed method calls by driver,
57 // method and status (error code); and "latency", a distribution of method latency
58 // by driver and method.
59 // For example, "gocloud.dev/pubsub/latency".
60 //
61 // To enable trace collection in your application, see "Configure an Exporter" at
62 // https://opentelemetry.io/docs/languages/go/getting-started/.
63 // To enable metric collection in your application, see "Metrics" at
64 // https://opentelemetry.io/docs/languages/go/metrics/.
65 package pubsub // import "gocloud.dev/pubsub"
66
67 import (
68 "context"
69 "errors"
70 "fmt"
71 "log"
72 "math"
73 "net/url"
74 "reflect"
75 "runtime"
76 "sync"
77 "time"
78 "unicode/utf8"
79
80 "github.com/googleapis/gax-go/v2"
81 "gocloud.dev/gcerrors"
82 "gocloud.dev/internal/gcerr"
83 "gocloud.dev/internal/openurl"
84 gcdkotel "gocloud.dev/internal/otel"
85 "gocloud.dev/internal/retry"
86 "gocloud.dev/pubsub/batcher"
87 "gocloud.dev/pubsub/driver"
88 "golang.org/x/sync/errgroup"
89 )
90
91 // Message contains data to be published.
92 type Message struct {
93 // LoggableID will be set to an opaque message identifer for
94 // received messages, useful for debug logging. No assumptions should
95 // be made about the content.
96 LoggableID string
97
98 // Body contains the content of the message.
99 Body []byte
100
101 // Metadata has key/value metadata for the message.
102 //
103 // When sending a message, set any key/value pairs you want associated with
104 // the message. It is acceptable for Metadata to be nil.
105 // Note that some services limit the number of key/value pairs per message.
106 //
107 // When receiving a message, Metadata will be nil if the message has no
108 // associated metadata.
109 Metadata map[string]string
110
111 // BeforeSend is a callback used when sending a message. It will always be
112 // set to nil for received messages.
113 //
114 // The callback will be called exactly once, before the message is sent.
115 //
116 // asFunc converts its argument to driver-specific types.
117 // See https://gocloud.dev/concepts/as/ for background information.
118 BeforeSend func(asFunc func(any) bool) error
119
120 // AfterSend is a callback used when sending a message. It will always be
121 // set to nil for received messages.
122 //
123 // The callback will be called at most once, after the message is sent.
124 // If Send returns an error, AfterSend will not be called.
125 //
126 // asFunc converts its argument to driver-specific types.
127 // See https://gocloud.dev/concepts/as/ for background information.
128 AfterSend func(asFunc func(any) bool) error
129
130 // asFunc invokes driver.Message.AsFunc.
131 asFunc func(any) bool
132
133 // ack is a closure that queues this message for the action (ack or nack).
134 ack func(isAck bool)
135
136 // nackable is true iff Nack can be called without panicking.
137 nackable bool
138
139 // mu guards isAcked in case Ack/Nack is called concurrently.
140 mu sync.Mutex
141
142 // isAcked tells whether this message has already had its Ack or Nack
143 // method called.
144 isAcked bool
145 }
146
147 // Ack acknowledges the message, telling the server that it does not need to be
148 // sent again to the associated Subscription. It will be a no-op for some
149 // drivers; see
150 // https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
151 // for more info.
152 //
153 // Ack returns immediately, but the actual ack is sent in the background, and
154 // is not guaranteed to succeed. If background acks persistently fail, the error
155 // will be returned from a subsequent Receive.
156 func (m *Message) Ack() {
157 m.mu.Lock()
158 defer m.mu.Unlock()
159 if m.isAcked {
160 panic(fmt.Sprintf("Ack/Nack called twice on message: %+v", m))
161 }
162 m.ack(true)
163 m.isAcked = true
164 }
165
166 // Nackable returns true iff Nack can be called without panicking.
167 //
168 // Some services do not support Nack; for example, at-most-once services
169 // can't redeliver a message. See
170 // https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
171 // for more info.
172 func (m *Message) Nackable() bool {
173 return m.nackable
174 }
175
176 // Nack (short for negative acknowledgment) tells the server that this Message
177 // was not processed and should be redelivered.
178 //
179 // Nack panics for some drivers, as Nack is meaningless when messages can't be
180 // redelivered. You can call Nackable to determine if Nack is available. See
181 // https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
182 // fore more info.
183 //
184 // Nack returns immediately, but the actual nack is sent in the background,
185 // and is not guaranteed to succeed.
186 //
187 // Nack is a performance optimization for retrying transient failures. It
188 // must not be used for message parse errors or other messages that the
189 // application will never be able to process: calling Nack will cause them to
190 // be redelivered and overload the server. Instead, an application should call
191 // Ack and log the failure in some monitored way.
192 func (m *Message) Nack() {
193 m.mu.Lock()
194 defer m.mu.Unlock()
195 if m.isAcked {
196 panic(fmt.Sprintf("Ack/Nack called twice on message: %+v", m))
197 }
198 if !m.nackable {
199 panic("Message.Nack is not supported by this driver")
200 }
201 m.ack(false)
202 m.isAcked = true
203 }
204
205 // As converts i to driver-specific types.
206 // See https://gocloud.dev/concepts/as/ for background information, the "As"
207 // examples in this package for examples, and the driver package
208 // documentation for the specific types supported for that driver.
209 // As panics unless it is called on a message obtained from Subscription.Receive.
210 func (m *Message) As(i any) bool {
211 if m.asFunc == nil {
212 panic("As called on a Message that was not obtained from Receive")
213 }
214 return m.asFunc(i)
215 }
216
217 // Topic publishes messages to all its subscribers.
218 type Topic struct {
219 driver driver.Topic
220 batcher *batcher.Batcher
221 tracer *gcdkotel.Tracer
222 mu sync.Mutex
223 err error
224
225 // cancel cancels all SendBatch calls.
226 cancel func()
227 }
228
229 // Send publishes a message. It only returns after the message has been
230 // sent, or failed to be sent. Send can be called from multiple goroutines
231 // at once.
232 func (t *Topic) Send(ctx context.Context, m *Message) (err error) {
233 ctx, span := t.tracer.Start(ctx, "Topic.Send")
234 defer func() { t.tracer.End(ctx, span, err) }()
235
236 // Check for doneness before we do any work.
237 if err := ctx.Err(); err != nil {
238 return err // Return context errors unwrapped.
239 }
240 t.mu.Lock()
241 err = t.err
242 t.mu.Unlock()
243 if err != nil {
244 return err // t.err wrapped when set
245 }
246 if m.LoggableID != "" {
247 return gcerr.Newf(gcerr.InvalidArgument, nil, "pubsub: Message.LoggableID should not be set when sending a message")
248 }
249 for k, v := range m.Metadata {
250 if !utf8.ValidString(k) {
251 return gcerr.Newf(gcerr.InvalidArgument, nil, "pubsub: Message.Metadata keys must be valid UTF-8 strings: %q", k)
252 }
253 if !utf8.ValidString(v) {
254 return gcerr.Newf(gcerr.InvalidArgument, nil, "pubsub: Message.Metadata values must be valid UTF-8 strings: %q", v)
255 }
256 }
257 dm := &driver.Message{
258 Body: m.Body,
259 Metadata: m.Metadata,
260 BeforeSend: m.BeforeSend,
261 AfterSend: m.AfterSend,
262 }
263 return t.batcher.Add(ctx, dm)
264 }
265
266 var errTopicShutdown = gcerr.Newf(gcerr.FailedPrecondition, nil, "pubsub: Topic has been Shutdown")
267
268 // Shutdown flushes pending message sends and disconnects the Topic.
269 // It only returns after all pending messages have been sent.
270 func (t *Topic) Shutdown(ctx context.Context) (err error) {
271 ctx, span := t.tracer.Start(ctx, "Topic.Shutdown")
272 defer func() { t.tracer.End(ctx, span, err) }()
273
274 t.mu.Lock()
275 if errors.Is(t.err, errTopicShutdown) {
276 defer t.mu.Unlock()
277 return t.err
278 }
279 t.err = errTopicShutdown
280 t.mu.Unlock()
281 c := make(chan struct{})
282 go func() {
283 defer close(c)
284 t.batcher.Shutdown()
285 }()
286 select {
287 case <-ctx.Done():
288 case <-c:
289 }
290 t.cancel()
291 if err := t.driver.Close(); err != nil {
292 return wrapError(t.driver, err)
293 }
294 return ctx.Err()
295 }
296
297 // As converts i to driver-specific types.
298 // See https://gocloud.dev/concepts/as/ for background information, the "As"
299 // examples in this package for examples, and the driver package
300 // documentation for the specific types supported for that driver.
301 func (t *Topic) As(i any) bool {
302 return t.driver.As(i)
303 }
304
305 // ErrorAs converts err to driver-specific types.
306 // ErrorAs panics if i is nil or not a pointer.
307 // ErrorAs returns false if err == nil.
308 // See https://gocloud.dev/concepts/as/ for background information.
309 func (t *Topic) ErrorAs(err error, i any) bool {
310 return gcerr.ErrorAs(err, i, t.driver.ErrorAs)
311 }
312
313 // NewTopic is for use by drivers only. Do not use in application code.
314 var NewTopic = newTopic
315
316 // newSendBatcher creates a batcher for topics, for use with NewTopic.
317 func newSendBatcher(ctx context.Context, t *Topic, dt driver.Topic, opts *batcher.Options) *batcher.Batcher {
318 handler := func(items any) error {
319 dms := items.([]*driver.Message)
320 err := retry.Call(ctx, gax.Backoff{}, dt.IsRetryable, func() (err error) {
321 spanCtx, span := t.tracer.Start(ctx, "driver.Topic.SendBatch")
322 defer func() { t.tracer.End(spanCtx, span, err) }()
323 return dt.SendBatch(spanCtx, dms)
324 })
325 if err != nil {
326 return wrapError(dt, err)
327 }
328 return nil
329 }
330 return batcher.New(reflect.TypeFor[*driver.Message](), opts, handler)
331 }
332
333 // newTopic makes a pubsub.Topic from a driver.Topic.
334 //
335 // opts may be nil to accept defaults.
336 func newTopic(d driver.Topic, opts *batcher.Options) *Topic {
337 ctx, cancel := context.WithCancel(context.Background())
338 t := &Topic{
339 driver: d,
340 tracer: gcdkotel.NewTracer(pkgName, gcdkotel.ProviderName(d)),
341 cancel: cancel,
342 }
343 t.batcher = newSendBatcher(ctx, t, d, opts)
344 return t
345 }
346
347 const pkgName = "gocloud.dev/pubsub"
348
349 var (
350
351 // OpenTelemetryViews are predefined views for OpenTelemetry metrics.
352 // The views include counts and latency distributions for API method calls.
353 // See the explanations at https://opentelemetry.io/docs/specs/otel/metrics/data-model/ for usage.
354 OpenTelemetryViews = gcdkotel.Views(pkgName)
355 )
356
357 // Subscription receives published messages.
358 type Subscription struct {
359 driver driver.Subscription
360 tracer *gcdkotel.Tracer
361 // ackBatcher makes batches of acks and nacks and sends them to the server.
362 ackBatcher *batcher.Batcher
363 canNack bool // true iff the driver supports Nack
364 backgroundCtx context.Context // for background SendAcks and ReceiveBatch calls
365 cancel func() // for canceling backgroundCtx
366
367 recvBatchOpts *batcher.Options
368
369 mu sync.Mutex // protects everything below
370 q []*driver.Message // local queue of messages downloaded from server
371 err error // permanent error
372 unreportedAckErr error // permanent error from background SendAcks that hasn't been returned to the user yet
373 waitc chan struct{} // for goroutines waiting on ReceiveBatch
374 runningBatchSize float64 // running number of messages to request via ReceiveBatch
375 throughputStart time.Time // start time for throughput measurement
376 throughputCount int // number of msgs given out via Receive since throughputStart
377
378 // Used in tests.
379 preReceiveBatchHook func(maxMessages int)
380 }
381
382 const (
383 // The desired duration of a subscription's queue of messages (the messages pulled
384 // and waiting in memory to be doled out to Receive callers). This is how long
385 // it would take to drain the queue at the current processing rate.
386 // The relationship to queue length (number of messages) is
387 //
388 // lengthInMessages = desiredQueueDuration / averageProcessTimePerMessage
389 //
390 // In other words, if it takes 100ms to process a message on average, and we want
391 // 2s worth of queued messages, then we need 2/.1 = 20 messages in the queue.
392 //
393 // If desiredQueueDuration is too small, then there won't be a large enough buffer
394 // of messages to handle fluctuations in processing time, and the queue is likely
395 // to become empty, reducing throughput. If desiredQueueDuration is too large, then
396 // messages will wait in memory for a long time, possibly timing out (that is,
397 // their ack deadline will be exceeded). Those messages could have been handled
398 // by another process receiving from the same subscription.
399 desiredQueueDuration = 2 * time.Second
400
401 // Expected duration of calls to driver.ReceiveBatch, at some high percentile.
402 // We'll try to fetch more messages when the current queue is predicted
403 // to be used up in expectedReceiveBatchDuration.
404 expectedReceiveBatchDuration = 1 * time.Second
405
406 // s.runningBatchSize holds our current best guess for how many messages to
407 // fetch in order to have a buffer of desiredQueueDuration. When we have
408 // fewer than prefetchRatio * s.runningBatchSize messages left, that means
409 // we expect to run out of messages in expectedReceiveBatchDuration, so we
410 // should initiate another ReceiveBatch call.
411 prefetchRatio = float64(expectedReceiveBatchDuration) / float64(desiredQueueDuration)
412
413 // The initial # of messages to request via ReceiveBatch.
414 initialBatchSize = 1
415
416 // The factor by which old batch sizes decay when a new value is added to the
417 // running value. The larger this number, the more weight will be given to the
418 // newest value in preference to older ones.
419 //
420 // The delta based on a single value is capped by the constants below.
421 decay = 0.5
422
423 // The maximum growth factor in a single jump. Higher values mean that the
424 // batch size can increase more aggressively. For example, 2.0 means that the
425 // batch size will at most double from one ReceiveBatch call to the next.
426 maxGrowthFactor = 2.0
427
428 // Similarly, the maximum shrink factor. Lower values mean that the batch size
429 // can shrink more aggressively. For example; 0.75 means that the batch size
430 // will at most shrink to 75% of what it was before. Note that values less
431 // than (1-decay) will have no effect because the running value can't change
432 // by more than that.
433 maxShrinkFactor = 0.75
434
435 // The maximum batch size to request. Setting this too low doesn't allow
436 // drivers to get lots of messages at once; setting it too small risks having
437 // drivers spend a long time in ReceiveBatch trying to achieve it.
438 maxBatchSize = 3000
439 )
440
441 // updateBatchSize updates the number of messages to request in ReceiveBatch
442 // based on the previous batch size and the rate of messages being pulled from
443 // the queue, measured using s.throughput*.
444 //
445 // It returns the number of messages to request in this ReceiveBatch call.
446 //
447 // s.mu must be held.
448 func (s *Subscription) updateBatchSize() int {
449 // If we're always only doing one at a time, there's no point in this.
450 if s.recvBatchOpts != nil && s.recvBatchOpts.MaxBatchSize == 1 && s.recvBatchOpts.MaxHandlers == 1 {
451 return 1
452 }
453 now := time.Now()
454 if s.throughputStart.IsZero() {
455 // No throughput measurement; don't update s.runningBatchSize.
456 } else {
457 // Update s.runningBatchSize based on throughput since our last time here,
458 // as measured by the ratio of the number of messages returned to elapsed
459 // time.
460 elapsed := max(now.Sub(s.throughputStart),
461 // Avoid divide-by-zero and huge numbers.
462 100*time.Millisecond)
463 msgsPerSec := float64(s.throughputCount) / elapsed.Seconds()
464
465 // The "ideal" batch size is how many messages we'd need in the queue to
466 // support desiredQueueDuration at the msgsPerSec rate.
467 idealBatchSize := desiredQueueDuration.Seconds() * msgsPerSec
468
469 // Move s.runningBatchSize towards the ideal.
470 // We first combine the previous value and the new value, with weighting
471 // based on decay, and then cap the growth/shrinkage.
472 newBatchSize := s.runningBatchSize*(1-decay) + idealBatchSize*decay
473 if maxSize := s.runningBatchSize * maxGrowthFactor; newBatchSize > maxSize {
474 s.runningBatchSize = maxSize
475 } else if minSize := s.runningBatchSize * maxShrinkFactor; newBatchSize < minSize {
476 s.runningBatchSize = minSize
477 } else {
478 s.runningBatchSize = newBatchSize
479 }
480 }
481
482 // Reset throughput measurement markers.
483 s.throughputStart = now
484 s.throughputCount = 0
485
486 // Using Ceil guarantees at least one message.
487 return int(math.Ceil(math.Min(s.runningBatchSize, maxBatchSize)))
488 }
489
490 // Receive receives and returns the next message from the Subscription's queue,
491 // blocking and polling if none are available. It can be called
492 // concurrently from multiple goroutines.
493 //
494 // Receive retries retryable errors from the underlying driver forever.
495 // Therefore, if Receive returns an error, either:
496 // 1. It is a non-retryable error from the underlying driver, either from
497 //
498 // an attempt to fetch more messages or from an attempt to ack messages.
499 // Operator intervention may be required (e.g., invalid resource, quota
500 // error, etc.). Receive will return the same error from then on, so the
501 // application should log the error and either recreate the Subscription,
502 // or exit.
503 //
504 // 2. The provided ctx is Done. Error() on the returned error will include both
505 //
506 // the ctx error and the underlying driver error, and ErrorAs on it
507 // can access the underlying driver error type if needed. Receive may
508 // be called again with a fresh ctx.
509 //
510 // Callers can distinguish between the two by checking if the ctx they passed
511 // is Done, or via xerrors.Is(err, context.DeadlineExceeded or context.Canceled)
512 // on the returned error.
513 //
514 // The Ack method of the returned Message must be called once the message has
515 // been processed, to prevent it from being received again.
516 func (s *Subscription) Receive(ctx context.Context) (_ *Message, err error) {
517 ctx, span := s.tracer.Start(ctx, "Subscription.Receive")
518 defer func() { s.tracer.End(ctx, span, err) }()
519
520 s.mu.Lock()
521 defer s.mu.Unlock()
522 for {
523 // The lock is always held here, at the top of the loop.
524 if s.err != nil {
525 // The Subscription is in a permanent error state. Return the error.
526 s.unreportedAckErr = nil
527 return nil, s.err // s.err wrapped when set
528 }
529
530 // Short circuit if ctx is Done.
531 // Otherwise, we'll continue to return messages from the queue, and even
532 // get new messages if driver.ReceiveBatch doesn't return an error when
533 // ctx is done.
534 if err := ctx.Err(); err != nil {
535 return nil, err
536 }
537
538 if s.waitc == nil && float64(len(s.q)) <= s.runningBatchSize*prefetchRatio {
539 // We think we're going to run out of messages in expectedReceiveBatchDuration,
540 // and there's no outstanding ReceiveBatch call, so initiate one in the
541 // background.
542 // Completion will be signalled to this goroutine, and to any other
543 // waiting goroutines, by closing s.waitc.
544 s.waitc = make(chan struct{})
545 batchSize := s.updateBatchSize()
546 // log.Printf("BATCH SIZE %d", batchSize)
547
548 go func() {
549 if s.preReceiveBatchHook != nil {
550 s.preReceiveBatchHook(batchSize)
551 }
552 resultChannel := s.getNextBatch(batchSize)
553 for msgsOrError := range resultChannel {
554 if len(msgsOrError.msgs) > 0 {
555 // messages received from channel
556 s.mu.Lock()
557 s.q = append(s.q, msgsOrError.msgs...)
558 s.mu.Unlock()
559 // notify that queue should now have messages
560 s.waitc <- struct{}{}
561 } else if msgsOrError.err != nil {
562 // err can receive message only after batch group completes
563 // Non-retryable error from ReceiveBatch -> permanent error
564 s.mu.Lock()
565 s.err = msgsOrError.err
566 s.mu.Unlock()
567 }
568 }
569 // batch reception finished
570 s.mu.Lock()
571 close(s.waitc)
572 s.waitc = nil
573 s.mu.Unlock()
574 }()
575 }
576 if len(s.q) > 0 {
577 // At least one message is available. Return it.
578 m := s.q[0]
579 s.q = s.q[1:]
580 s.throughputCount++
581
582 // Convert driver.Message to Message.
583 id := m.AckID
584 md := m.Metadata
585 if len(md) == 0 {
586 md = nil
587 }
588 loggableID := m.LoggableID
589 if loggableID == "" {
590 // This shouldn't happen, but just in case it's better to be explicit.
591 loggableID = "unknown"
592 }
593 m2 := &Message{
594 LoggableID: loggableID,
595 Body: m.Body,
596 Metadata: md,
597 asFunc: m.AsFunc,
598 nackable: s.canNack,
599 }
600 m2.ack = func(isAck bool) {
601 // Ignore the error channel. Errors are dealt with
602 // in the ackBatcher handler.
603 _ = s.ackBatcher.AddNoWait(&driver.AckInfo{AckID: id, IsAck: isAck})
604 }
605 // Add a finalizer that complains if the Message we return isn't
606 // acked or nacked.
607 _, file, lineno, ok := runtime.Caller(1) // the caller of Receive
608 runtime.SetFinalizer(m2, func(m *Message) {
609 m.mu.Lock()
610 defer m.mu.Unlock()
611 if !m.isAcked {
612 var caller string
613 if ok {
614 caller = fmt.Sprintf(" (%s:%d)", file, lineno)
615 }
616 log.Printf("A pubsub.Message was never Acked or Nacked%s", caller)
617 }
618 })
619 return m2, nil
620 }
621 // A call to ReceiveBatch must be in flight. Wait for it.
622 waitc := s.waitc
623 s.mu.Unlock() // unlock to allow message or error processing from background goroutine
624 select {
625 case <-waitc:
626 // Continue to top of loop.
627 s.mu.Lock()
628 case <-ctx.Done():
629 s.mu.Lock()
630 return nil, ctx.Err()
631 }
632 }
633 }
634
635 type msgsOrError struct {
636 msgs []*driver.Message
637 err error
638 }
639
640 // getNextBatch gets the next batch of messages from the server. It will return a channel that will itself return the
641 // messages as they come from each independent batch, or an operation error
642 func (s *Subscription) getNextBatch(nMessages int) chan msgsOrError {
643 // Split nMessages into batches based on recvBatchOpts; we'll make a
644 // separate ReceiveBatch call for each batch, and aggregate the results in
645 // msgs.
646 batches := batcher.Split(nMessages, s.recvBatchOpts)
647 result := make(chan msgsOrError, len(batches))
648 g, ctx := errgroup.WithContext(s.backgroundCtx)
649 for _, maxMessagesInBatch := range batches {
650 // Make a copy of the loop variable since it will be used by a goroutine.
651 curMaxMessagesInBatch := maxMessagesInBatch
652 g.Go(func() error {
653 var msgs []*driver.Message
654 err := retry.Call(ctx, gax.Backoff{}, s.driver.IsRetryable, func() error {
655 var err error
656 spanCtx, span := s.tracer.Start(ctx, "driver.Subscription.ReceiveBatch")
657 defer func() { s.tracer.End(spanCtx, span, err) }()
658 msgs, err = s.driver.ReceiveBatch(spanCtx, curMaxMessagesInBatch)
659 return err
660 })
661 if err != nil {
662 return wrapError(s.driver, err)
663 }
664 result <- msgsOrError{msgs: msgs}
665 return nil
666 })
667 }
668 go func() {
669 // wait on group completion on the background and proper channel closing
670 if err := g.Wait(); err != nil {
671 result <- msgsOrError{err: err}
672 }
673 close(result)
674 }()
675 return result
676 }
677
678 var errSubscriptionShutdown = gcerr.Newf(gcerr.FailedPrecondition, nil, "pubsub: Subscription has been Shutdown")
679
680 // Shutdown flushes pending ack sends and disconnects the Subscription.
681 func (s *Subscription) Shutdown(ctx context.Context) (err error) {
682 ctx, span := s.tracer.Start(ctx, "Subscription.Shutdown")
683 defer func() { s.tracer.End(ctx, span, err) }()
684
685 s.mu.Lock()
686 if errors.Is(s.err, errSubscriptionShutdown) {
687 // Already Shutdown.
688 defer s.mu.Unlock()
689 return s.err
690 }
691 s.err = errSubscriptionShutdown
692 s.mu.Unlock()
693 c := make(chan struct{})
694 go func() {
695 defer close(c)
696 if s.ackBatcher != nil {
697 s.ackBatcher.Shutdown()
698 }
699 }()
700 select {
701 case <-ctx.Done():
702 case <-c:
703 }
704 s.cancel()
705 if err := s.driver.Close(); err != nil {
706 return wrapError(s.driver, err)
707 }
708 s.mu.Lock()
709 defer s.mu.Unlock()
710 if err := s.unreportedAckErr; err != nil {
711 s.unreportedAckErr = nil
712 return err
713 }
714 return ctx.Err()
715 }
716
717 // As converts i to driver-specific types.
718 // See https://gocloud.dev/concepts/as/ for background information, the "As"
719 // examples in this package for examples, and the driver package
720 // documentation for the specific types supported for that driver.
721 func (s *Subscription) As(i any) bool {
722 return s.driver.As(i)
723 }
724
725 // ErrorAs converts err to driver-specific types.
726 // ErrorAs panics if i is nil or not a pointer.
727 // ErrorAs returns false if err == nil.
728 // See Topic.As for more details.
729 func (s *Subscription) ErrorAs(err error, i any) bool {
730 return gcerr.ErrorAs(err, i, s.driver.ErrorAs)
731 }
732
733 // NewSubscription is for use by drivers only. Do not use in application code.
734 var NewSubscription = newSubscription
735
736 // newSubscription creates a Subscription from a driver.Subscription.
737 //
738 // recvBatchOpts sets options for Receive batching. May be nil to accept
739 // defaults. The ideal number of messages to receive at a time is determined
740 // dynamically, then split into multiple possibly concurrent calls to
741 // driver.ReceiveBatch based on recvBatchOptions.
742 //
743 // ackBatcherOpts sets options for ack+nack batching. May be nil to accept
744 // defaults.
745 func newSubscription(ds driver.Subscription, recvBatchOpts, ackBatcherOpts *batcher.Options) *Subscription {
746 ctx, cancel := context.WithCancel(context.Background())
747 s := &Subscription{
748 driver: ds,
749 tracer: gcdkotel.NewTracer(pkgName, gcdkotel.ProviderName(ds)),
750 cancel: cancel,
751 backgroundCtx: ctx,
752 recvBatchOpts: recvBatchOpts,
753 runningBatchSize: initialBatchSize,
754 canNack: ds.CanNack(),
755 }
756 s.ackBatcher = newAckBatcher(ctx, s, ds, ackBatcherOpts)
757 return s
758 }
759
760 func newAckBatcher(ctx context.Context, s *Subscription, ds driver.Subscription, opts *batcher.Options) *batcher.Batcher {
761 handler := func(items any) error {
762 var acks, nacks []driver.AckID
763 for _, a := range items.([]*driver.AckInfo) {
764 if a.IsAck {
765 acks = append(acks, a.AckID)
766 } else {
767 nacks = append(nacks, a.AckID)
768 }
769 }
770 g, ctx := errgroup.WithContext(ctx)
771 if len(acks) > 0 {
772 g.Go(func() error {
773 return retry.Call(ctx, gax.Backoff{}, ds.IsRetryable, func() (err error) {
774 spanCtx, span := s.tracer.Start(ctx, "driver.Subscription.SendAcks")
775 defer func() { s.tracer.End(spanCtx, span, err) }()
776 return ds.SendAcks(spanCtx, acks)
777 })
778 })
779 }
780 if len(nacks) > 0 {
781 g.Go(func() error {
782 return retry.Call(ctx, gax.Backoff{}, ds.IsRetryable, func() (err error) {
783 spanCtx, span := s.tracer.Start(ctx, "driver.Subscription.SendNacks")
784 defer func() { s.tracer.End(spanCtx, span, err) }()
785 return ds.SendNacks(spanCtx, nacks)
786 })
787 })
788 }
789 err := g.Wait()
790 // Remember a non-retryable error from SendAcks/Nacks. It will be returned on the
791 // next call to Receive.
792 if err != nil {
793 err = wrapError(s.driver, err)
794 s.mu.Lock()
795 s.err = err
796 s.unreportedAckErr = err
797 s.mu.Unlock()
798 }
799 return err
800 }
801 return batcher.New(reflect.TypeFor[[]*driver.AckInfo]().Elem(), opts, handler)
802 }
803
804 type errorCoder interface {
805 ErrorCode(error) gcerrors.ErrorCode
806 }
807
808 func wrapError(ec errorCoder, err error) error {
809 if err == nil {
810 return nil
811 }
812 if gcerr.DoNotWrap(err) {
813 return err
814 }
815 return gcerr.New(ec.ErrorCode(err), err, 2, "pubsub")
816 }
817
818 // TopicURLOpener represents types than can open Topics based on a URL.
819 // The opener must not modify the URL argument. OpenTopicURL must be safe to
820 // call from multiple goroutines.
821 //
822 // This interface is generally implemented by types in driver packages.
823 type TopicURLOpener interface {
824 OpenTopicURL(ctx context.Context, u *url.URL) (*Topic, error)
825 }
826
827 // SubscriptionURLOpener represents types than can open Subscriptions based on a URL.
828 // The opener must not modify the URL argument. OpenSubscriptionURL must be safe to
829 // call from multiple goroutines.
830 //
831 // This interface is generally implemented by types in driver packages.
832 type SubscriptionURLOpener interface {
833 OpenSubscriptionURL(ctx context.Context, u *url.URL) (*Subscription, error)
834 }
835
836 // URLMux is a URL opener multiplexer. It matches the scheme of the URLs
837 // against a set of registered schemes and calls the opener that matches the
838 // URL's scheme.
839 // See https://gocloud.dev/concepts/urls/ for more information.
840 //
841 // The zero value is a multiplexer with no registered schemes.
842 type URLMux struct {
843 subscriptionSchemes openurl.SchemeMap
844 topicSchemes openurl.SchemeMap
845 }
846
847 // TopicSchemes returns a sorted slice of the registered Topic schemes.
848 func (mux *URLMux) TopicSchemes() []string { return mux.topicSchemes.Schemes() }
849
850 // ValidTopicScheme returns true iff scheme has been registered for Topics.
851 func (mux *URLMux) ValidTopicScheme(scheme string) bool { return mux.topicSchemes.ValidScheme(scheme) }
852
853 // SubscriptionSchemes returns a sorted slice of the registered Subscription schemes.
854 func (mux *URLMux) SubscriptionSchemes() []string { return mux.subscriptionSchemes.Schemes() }
855
856 // ValidSubscriptionScheme returns true iff scheme has been registered for Subscriptions.
857 func (mux *URLMux) ValidSubscriptionScheme(scheme string) bool {
858 return mux.subscriptionSchemes.ValidScheme(scheme)
859 }
860
861 // RegisterTopic registers the opener with the given scheme. If an opener
862 // already exists for the scheme, RegisterTopic panics.
863 func (mux *URLMux) RegisterTopic(scheme string, opener TopicURLOpener) {
864 mux.topicSchemes.Register("pubsub", "Topic", scheme, opener)
865 }
866
867 // RegisterSubscription registers the opener with the given scheme. If an opener
868 // already exists for the scheme, RegisterSubscription panics.
869 func (mux *URLMux) RegisterSubscription(scheme string, opener SubscriptionURLOpener) {
870 mux.subscriptionSchemes.Register("pubsub", "Subscription", scheme, opener)
871 }
872
873 // OpenTopic calls OpenTopicURL with the URL parsed from urlstr.
874 // OpenTopic is safe to call from multiple goroutines.
875 func (mux *URLMux) OpenTopic(ctx context.Context, urlstr string) (*Topic, error) {
876 opener, u, err := mux.topicSchemes.FromString("Topic", urlstr)
877 if err != nil {
878 return nil, err
879 }
880 return opener.(TopicURLOpener).OpenTopicURL(ctx, u)
881 }
882
883 // OpenSubscription calls OpenSubscriptionURL with the URL parsed from urlstr.
884 // OpenSubscription is safe to call from multiple goroutines.
885 func (mux *URLMux) OpenSubscription(ctx context.Context, urlstr string) (*Subscription, error) {
886 opener, u, err := mux.subscriptionSchemes.FromString("Subscription", urlstr)
887 if err != nil {
888 return nil, err
889 }
890 return opener.(SubscriptionURLOpener).OpenSubscriptionURL(ctx, u)
891 }
892
893 // OpenTopicURL dispatches the URL to the opener that is registered with the
894 // URL's scheme. OpenTopicURL is safe to call from multiple goroutines.
895 func (mux *URLMux) OpenTopicURL(ctx context.Context, u *url.URL) (*Topic, error) {
896 opener, err := mux.topicSchemes.FromURL("Topic", u)
897 if err != nil {
898 return nil, err
899 }
900 return opener.(TopicURLOpener).OpenTopicURL(ctx, u)
901 }
902
903 // OpenSubscriptionURL dispatches the URL to the opener that is registered with the
904 // URL's scheme. OpenSubscriptionURL is safe to call from multiple goroutines.
905 func (mux *URLMux) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*Subscription, error) {
906 opener, err := mux.subscriptionSchemes.FromURL("Subscription", u)
907 if err != nil {
908 return nil, err
909 }
910 return opener.(SubscriptionURLOpener).OpenSubscriptionURL(ctx, u)
911 }
912
913 var defaultURLMux = &URLMux{}
914
915 // DefaultURLMux returns the URLMux used by OpenTopic and OpenSubscription.
916 //
917 // Driver packages can use this to register their TopicURLOpener and/or
918 // SubscriptionURLOpener on the mux.
919 func DefaultURLMux() *URLMux {
920 return defaultURLMux
921 }
922
923 // OpenTopic opens the Topic identified by the URL given.
924 // See the URLOpener documentation in driver subpackages for
925 // details on supported URL formats, and https://gocloud.dev/concepts/urls
926 // for more information.
927 func OpenTopic(ctx context.Context, urlstr string) (*Topic, error) {
928 return defaultURLMux.OpenTopic(ctx, urlstr)
929 }
930
931 // OpenSubscription opens the Subscription identified by the URL given.
932 // See the URLOpener documentation in driver subpackages for
933 // details on supported URL formats, and https://gocloud.dev/concepts/urls
934 // for more information.
935 func OpenSubscription(ctx context.Context, urlstr string) (*Subscription, error) {
936 return defaultURLMux.OpenSubscription(ctx, urlstr)
937 }