| 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 rabbitpubsub |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"net/url" |
| 22 |
"os" |
| 23 |
"path" |
| 24 |
"strconv" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"sync/atomic" |
| 28 |
"time" |
| 29 |
|
| 30 |
amqp "github.com/rabbitmq/amqp091-go" |
| 31 |
"gocloud.dev/gcerrors" |
| 32 |
"gocloud.dev/pubsub" |
| 33 |
"gocloud.dev/pubsub/driver" |
| 34 |
) |
| 35 |
|
| 36 |
func init() { |
| 37 |
o := new(defaultDialer) |
| 38 |
pubsub.DefaultURLMux().RegisterTopic(Scheme, o) |
| 39 |
pubsub.DefaultURLMux().RegisterSubscription(Scheme, o) |
| 40 |
} |
| 41 |
|
| 42 |
// defaultDialer dials a default Rabbit server based on the environment |
| 43 |
// variable "RABBIT_SERVER_URL". |
| 44 |
type defaultDialer struct { |
| 45 |
mu sync.Mutex |
| 46 |
conn *amqp.Connection |
| 47 |
opener *URLOpener |
| 48 |
} |
| 49 |
|
| 50 |
func (o *defaultDialer) defaultConn(ctx context.Context) (*URLOpener, error) { |
| 51 |
o.mu.Lock() |
| 52 |
defer o.mu.Unlock() |
| 53 |
|
| 54 |
// Re-use the connection if possible. |
| 55 |
if o.opener != nil && o.conn != nil && !o.conn.IsClosed() { |
| 56 |
return o.opener, nil |
| 57 |
} |
| 58 |
|
| 59 |
// First time through, or last time resulted in an error, or connection |
| 60 |
// was closed. Initialize the connection. |
| 61 |
serverURL := os.Getenv("RABBIT_SERVER_URL") |
| 62 |
if serverURL == "" { |
| 63 |
return nil, errors.New("RABBIT_SERVER_URL environment variable not set") |
| 64 |
} |
| 65 |
conn, err := amqp.Dial(serverURL) |
| 66 |
if err != nil { |
| 67 |
return nil, fmt.Errorf("failed to dial RABBIT_SERVER_URL %q: %w", serverURL, err) |
| 68 |
} |
| 69 |
o.conn = conn |
| 70 |
o.opener = &URLOpener{Connection: conn} |
| 71 |
return o.opener, nil |
| 72 |
} |
| 73 |
|
| 74 |
func (o *defaultDialer) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 75 |
opener, err := o.defaultConn(ctx) |
| 76 |
if err != nil { |
| 77 |
return nil, fmt.Errorf("open topic %v: failed to open default connection: %w", u, err) |
| 78 |
} |
| 79 |
return opener.OpenTopicURL(ctx, u) |
| 80 |
} |
| 81 |
|
| 82 |
func (o *defaultDialer) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 83 |
opener, err := o.defaultConn(ctx) |
| 84 |
if err != nil { |
| 85 |
return nil, fmt.Errorf("open subscription %v: failed to open default connection: %w", u, err) |
| 86 |
} |
| 87 |
return opener.OpenSubscriptionURL(ctx, u) |
| 88 |
} |
| 89 |
|
| 90 |
// Scheme is the URL scheme rabbitpubsub registers its URLOpeners under on pubsub.DefaultMux. |
| 91 |
const Scheme = "rabbit" |
| 92 |
|
| 93 |
// URLOpener opens RabbitMQ URLs like "rabbit://myexchange" for |
| 94 |
// topics or "rabbit://myqueue" for subscriptions. |
| 95 |
// |
| 96 |
// For topics, the URL's host+path is used as the exchange name. |
| 97 |
// |
| 98 |
// For subscriptions, the URL's host+path is used as the queue name. |
| 99 |
// |
| 100 |
// An optional query string can be used to set the Qos consumer prefetch on subscriptions |
| 101 |
// like "rabbit://myqueue?prefetch_count=1000" to set the consumer prefetch count to 1000 |
| 102 |
// see also https://www.rabbitmq.com/docs/consumer-prefetch |
| 103 |
type URLOpener struct { |
| 104 |
// Connection to use for communication with the server. |
| 105 |
Connection *amqp.Connection |
| 106 |
|
| 107 |
// TopicOptions specifies the options to pass to OpenTopic. |
| 108 |
TopicOptions TopicOptions |
| 109 |
// SubscriptionOptions specifies the options to pass to OpenSubscription. |
| 110 |
SubscriptionOptions SubscriptionOptions |
| 111 |
} |
| 112 |
|
| 113 |
// OpenTopicURL opens a pubsub.Topic based on u. |
| 114 |
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 115 |
opts := o.TopicOptions |
| 116 |
for param, value := range u.Query() { |
| 117 |
switch param { |
| 118 |
case "key_name": |
| 119 |
if len(value) != 1 || len(value[0]) == 0 { |
| 120 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 121 |
} |
| 122 |
|
| 123 |
opts.KeyName = value[0] |
| 124 |
default: |
| 125 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
exchangeName := path.Join(u.Host, u.Path) |
| 130 |
return OpenTopic(o.Connection, exchangeName, &opts), nil |
| 131 |
} |
| 132 |
|
| 133 |
// OpenSubscriptionURL opens a pubsub.Subscription based on u. |
| 134 |
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 135 |
opts := o.SubscriptionOptions |
| 136 |
for param, value := range u.Query() { |
| 137 |
switch param { |
| 138 |
case "prefetch_count": |
| 139 |
if len(value) != 1 || len(value[0]) == 0 { |
| 140 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 141 |
} |
| 142 |
|
| 143 |
prefetchCount, err := strconv.Atoi(value[0]) |
| 144 |
if err != nil { |
| 145 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: %w", u, param, err) |
| 146 |
} |
| 147 |
|
| 148 |
opts.PrefetchCount = &prefetchCount |
| 149 |
default: |
| 150 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
queueName := path.Join(u.Host, u.Path) |
| 155 |
return OpenSubscription(o.Connection, queueName, &opts), nil |
| 156 |
} |
| 157 |
|
| 158 |
type topic struct { |
| 159 |
exchange string // the AMQP exchange |
| 160 |
conn amqpConnection |
| 161 |
opts *TopicOptions |
| 162 |
|
| 163 |
mu sync.Mutex |
| 164 |
ch amqpChannel // AMQP channel used for all communication. |
| 165 |
pubc <-chan amqp.Confirmation // Go channel for server acks of publishes |
| 166 |
retc <-chan amqp.Return // Go channel for "returned" undeliverable messages |
| 167 |
closec <-chan *amqp.Error // Go channel for AMQP channel close notifications |
| 168 |
} |
| 169 |
|
| 170 |
// TopicOptions sets options for constructing a *pubsub.Topic backed by |
| 171 |
// RabbitMQ. |
| 172 |
type TopicOptions struct { |
| 173 |
// KeyName optionally sets the Message.Metadata key to use as the optional |
| 174 |
// RabbitMQ message key. If set, and if a matching Message.Metadata key is found, |
| 175 |
// the value for that key will be used as the routing key when sending to |
| 176 |
// RabbitMQ, instead of being added to the message headers. |
| 177 |
KeyName string |
| 178 |
} |
| 179 |
|
| 180 |
// SubscriptionOptions sets options for constructing a *pubsub.Subscription |
| 181 |
// backed by RabbitMQ. |
| 182 |
type SubscriptionOptions struct { |
| 183 |
// KeyName optionally sets the Message.Metadata key in which to store the |
| 184 |
// RabbitMQ message key. If set, and if the RabbitMQ message key is non-empty, |
| 185 |
// the key value will be stored in Message.Metadata under KeyName. |
| 186 |
KeyName string |
| 187 |
|
| 188 |
// Qos property prefetch count. Optional. |
| 189 |
PrefetchCount *int |
| 190 |
} |
| 191 |
|
| 192 |
// OpenTopic returns a *pubsub.Topic corresponding to the named exchange. |
| 193 |
// See the package documentation for an example. |
| 194 |
// |
| 195 |
// The exchange should already exist (for instance, by using |
| 196 |
// amqp.Channel.ExchangeDeclare), although this won't be checked until the first call |
| 197 |
// to SendBatch. For the Go CDK Pub/Sub model to make sense, the exchange should |
| 198 |
// be a fanout exchange, although nothing in this package enforces that. |
| 199 |
// |
| 200 |
// OpenTopic uses the supplied amqp.Connection for all communication. It is the |
| 201 |
// caller's responsibility to establish this connection before calling OpenTopic, and |
| 202 |
// to close it when Close has been called on all Topics opened with it. |
| 203 |
// |
| 204 |
// The documentation of the amqp package recommends using separate connections for |
| 205 |
// publishing and subscribing. |
| 206 |
func OpenTopic(conn *amqp.Connection, name string, opts *TopicOptions) *pubsub.Topic { |
| 207 |
return pubsub.NewTopic(newTopic(&connection{conn}, name, opts), nil) |
| 208 |
} |
| 209 |
|
| 210 |
func newTopic(conn amqpConnection, name string, opts *TopicOptions) *topic { |
| 211 |
if opts == nil { |
| 212 |
opts = &TopicOptions{} |
| 213 |
} |
| 214 |
|
| 215 |
return &topic{ |
| 216 |
conn: conn, |
| 217 |
exchange: name, |
| 218 |
opts: opts, |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
// establishChannel creates an AMQP channel if necessary. According to the amqp |
| 223 |
// package docs, once an error is returned from the channel, it must be discarded and |
| 224 |
// a new one created. |
| 225 |
// |
| 226 |
// Must be called with t.mu held. |
| 227 |
func (t *topic) establishChannel(ctx context.Context) error { |
| 228 |
if t.ch != nil { // We already have a channel. |
| 229 |
select { |
| 230 |
// If it was closed, open a new one. |
| 231 |
// (Ignore the error, if any.) |
| 232 |
case <-t.closec: |
| 233 |
|
| 234 |
// If it isn't closed, nothing to do. |
| 235 |
default: |
| 236 |
return nil |
| 237 |
} |
| 238 |
} |
| 239 |
var ch amqpChannel |
| 240 |
err := runWithContext(ctx, func() error { |
| 241 |
// Create a new channel in confirm mode. |
| 242 |
var err error |
| 243 |
ch, err = t.conn.Channel() |
| 244 |
return err |
| 245 |
}) |
| 246 |
if err != nil { |
| 247 |
return err |
| 248 |
} |
| 249 |
t.ch = ch |
| 250 |
// Get Go channels which will hold acks and returns from the server. The server |
| 251 |
// will send an ack for each published message to confirm that it was received. |
| 252 |
// It will return undeliverable messages. |
| 253 |
// All the Notify methods return their arg. |
| 254 |
t.pubc = ch.NotifyPublish(make(chan amqp.Confirmation)) |
| 255 |
t.retc = ch.NotifyReturn(make(chan amqp.Return)) |
| 256 |
t.closec = ch.NotifyClose(make(chan *amqp.Error, 1)) // closec will get at most one element |
| 257 |
return nil |
| 258 |
} |
| 259 |
|
| 260 |
// Run f while checking to see if ctx is done. |
| 261 |
// Return the error from f if it completes, or ctx.Err() if ctx is done. |
| 262 |
func runWithContext(ctx context.Context, f func() error) error { |
| 263 |
c := make(chan error, 1) // buffer so the goroutine can finish even if ctx is done |
| 264 |
go func() { c <- f() }() |
| 265 |
select { |
| 266 |
case <-ctx.Done(): |
| 267 |
return ctx.Err() |
| 268 |
case err := <-c: |
| 269 |
return err |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
// SendBatch implements driver.SendBatch. |
| 274 |
func (t *topic) SendBatch(ctx context.Context, ms []*driver.Message) error { |
| 275 |
// It is simplest to allow only one SendBatch at a time. Allowing concurrent |
| 276 |
// calls to SendBatch would complicate the logic of receiving publish |
| 277 |
// confirmations and returns. We can go that route if performance warrants it. |
| 278 |
t.mu.Lock() |
| 279 |
defer t.mu.Unlock() |
| 280 |
|
| 281 |
if err := t.establishChannel(ctx); err != nil { |
| 282 |
return err |
| 283 |
} |
| 284 |
|
| 285 |
// Receive from Go channels concurrently or we will deadlock with the Publish |
| 286 |
// RPC. (The amqp package docs recommend setting the capacity of the Go channel |
| 287 |
// to the number of messages to be published, but we can't do that because we |
| 288 |
// want to reuse the channel for all calls to SendBatch--it takes two RPCs to set |
| 289 |
// up.) |
| 290 |
errc := make(chan error, 1) |
| 291 |
cctx, cancel := context.WithCancel(ctx) |
| 292 |
defer cancel() |
| 293 |
ch := t.ch // Avoid touching t.ch while goroutine is running. |
| 294 |
go func() { |
| 295 |
// This goroutine runs with t.mu held because its lifetime is within the |
| 296 |
// lifetime of the t.mu.Lock call at the start of SendBatch. |
| 297 |
errc <- t.receiveFromPublishChannels(cctx, len(ms)) |
| 298 |
}() |
| 299 |
|
| 300 |
var perr error |
| 301 |
for _, m := range ms { |
| 302 |
routingKey, pub := toRoutingKeyAndAMQPPublishing(m, t.opts) |
| 303 |
if m.BeforeSend != nil { |
| 304 |
asFunc := func(i any) bool { |
| 305 |
if p, ok := i.(**amqp.Publishing); ok { |
| 306 |
*p = &pub |
| 307 |
return true |
| 308 |
} |
| 309 |
return false |
| 310 |
} |
| 311 |
if err := m.BeforeSend(asFunc); err != nil { |
| 312 |
return err |
| 313 |
} |
| 314 |
} |
| 315 |
if perr = ch.Publish(t.exchange, routingKey, pub); perr != nil { |
| 316 |
cancel() |
| 317 |
break |
| 318 |
} |
| 319 |
if m.AfterSend != nil { |
| 320 |
asFunc := func(i any) bool { return false } |
| 321 |
if err := m.AfterSend(asFunc); err != nil { |
| 322 |
return err |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
// Wait for the goroutine to finish. |
| 327 |
err := <-errc |
| 328 |
// If we got an error from Publish, prefer that. |
| 329 |
if perr != nil { |
| 330 |
// Set t.ch to nil because an AMQP channel is broken after error. |
| 331 |
// Do this here, after the goroutine has finished, rather than in the Publish loop |
| 332 |
// above, to avoid a race condition. |
| 333 |
t.ch = nil |
| 334 |
err = perr |
| 335 |
} |
| 336 |
// If there is only one error, return it rather than a MultiError. That |
| 337 |
// will work better with ErrorCode and ErrorAs. |
| 338 |
var merr MultiError |
| 339 |
if errors.As(err, &merr) && len(merr) == 1 { |
| 340 |
return merr[0] |
| 341 |
} |
| 342 |
return err |
| 343 |
} |
| 344 |
|
| 345 |
// Read from the channels established with NotifyPublish and NotifyReturn. |
| 346 |
// Must be called with t.mu held. |
| 347 |
func (t *topic) receiveFromPublishChannels(ctx context.Context, nMessages int) error { |
| 348 |
// Consume all the acknowledgments for the messages we are publishing, and also |
| 349 |
// get returned messages. The server will send exactly one ack for each published |
| 350 |
// message (successful or not), and one return for each undeliverable message. |
| 351 |
// Since SendBatch (the only caller of this method) holds the lock, we expect |
| 352 |
// exactly as many acks as messages. |
| 353 |
var merr MultiError |
| 354 |
nAcks := 0 |
| 355 |
for nAcks < nMessages { |
| 356 |
select { |
| 357 |
case <-ctx.Done(): |
| 358 |
if t.ch != nil { |
| 359 |
// Channel will be in a weird state (not all publish acks consumed, perhaps) |
| 360 |
// so re-create it next time. |
| 361 |
t.ch.Close() |
| 362 |
t.ch = nil |
| 363 |
} |
| 364 |
return ctx.Err() |
| 365 |
|
| 366 |
case ret, ok := <-t.retc: |
| 367 |
if !ok { |
| 368 |
// Channel closed. Handled in the pubc case below. But set |
| 369 |
// the channel to nil to prevent it from being selected again. |
| 370 |
t.retc = nil |
| 371 |
} else { |
| 372 |
// The message was returned from the server because it is unroutable. |
| 373 |
// Record the error and continue so we drain all |
| 374 |
// items from pubc. We don't need to re-establish the channel on this |
| 375 |
// error. |
| 376 |
merr = append(merr, fmt.Errorf("rabbitpubsub: message returned from %s: %s (code %d)", |
| 377 |
ret.Exchange, ret.ReplyText, ret.ReplyCode)) |
| 378 |
} |
| 379 |
|
| 380 |
case conf, ok := <-t.pubc: |
| 381 |
if !ok { |
| 382 |
// t.pubc was closed unexpectedly. |
| 383 |
t.ch = nil // re-create the channel on next use |
| 384 |
if merr != nil { |
| 385 |
return merr |
| 386 |
} |
| 387 |
// t.closec must be closed too. See if it has an error. |
| 388 |
if err := closeErr(t.closec); err != nil { |
| 389 |
merr = append(merr, err) |
| 390 |
return merr |
| 391 |
} |
| 392 |
// We shouldn't be here, but if we are, we still want to return an |
| 393 |
// error. |
| 394 |
merr = append(merr, errors.New("rabbitpubsub: publish listener closed unexpectedly")) |
| 395 |
return merr |
| 396 |
} |
| 397 |
nAcks++ |
| 398 |
if !conf.Ack { |
| 399 |
merr = append(merr, errors.New("rabbitpubsub: ack failed on publish")) |
| 400 |
} |
| 401 |
} |
| 402 |
} |
| 403 |
if merr != nil { |
| 404 |
return merr |
| 405 |
} |
| 406 |
// Returning a nil merr would mean the returned error interface value is non-nil, so return nil explicitly. |
| 407 |
return nil |
| 408 |
} |
| 409 |
|
| 410 |
// A MultiError is an error that contains multiple errors. |
| 411 |
type MultiError []error |
| 412 |
|
| 413 |
func (m MultiError) Error() string { |
| 414 |
var s []string |
| 415 |
for _, e := range m { |
| 416 |
s = append(s, e.Error()) |
| 417 |
} |
| 418 |
return strings.Join(s, "; ") |
| 419 |
} |
| 420 |
|
| 421 |
// Return the error from a Go channel monitoring the closing of an AMQP channel. |
| 422 |
// closec must have been registered via Channel.NotifyClose. |
| 423 |
// When closeErr is called, we expect closec to be closed. If it isn't, we also |
| 424 |
// consider that an error. |
| 425 |
func closeErr(closec <-chan *amqp.Error) error { |
| 426 |
select { |
| 427 |
case aerr := <-closec: |
| 428 |
// This nil check is necessary. aerr is of type *amqp.Error. If we |
| 429 |
// returned it directly (effectively assigning it to a variable of |
| 430 |
// type error), then the return value would not be a nil interface |
| 431 |
// value even if aerr was a nil pointer, and that would break tests |
| 432 |
// like "if err == nil ...". |
| 433 |
if aerr == nil { |
| 434 |
return nil |
| 435 |
} |
| 436 |
return aerr |
| 437 |
default: |
| 438 |
return errors.New("rabbitpubsub: NotifyClose Go channel is unexpectedly open") |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
// toRoutingKeyAndAMQPPublishing converts a driver.Message to a pair routingKey + amqp.Publishing. |
| 443 |
func toRoutingKeyAndAMQPPublishing(m *driver.Message, opts *TopicOptions) (routingKey string, msg amqp.Publishing) { |
| 444 |
h := amqp.Table{} |
| 445 |
for k, v := range m.Metadata { |
| 446 |
if opts.KeyName == k { |
| 447 |
routingKey = v |
| 448 |
} else { |
| 449 |
h[k] = v |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
msg = amqp.Publishing{ |
| 454 |
Headers: h, |
| 455 |
Body: m.Body, |
| 456 |
} |
| 457 |
|
| 458 |
return routingKey, msg |
| 459 |
} |
| 460 |
|
| 461 |
// IsRetryable implements driver.Topic.IsRetryable. |
| 462 |
func (*topic) IsRetryable(err error) bool { |
| 463 |
return isRetryable(err) |
| 464 |
} |
| 465 |
|
| 466 |
func (*topic) ErrorCode(err error) gcerrors.ErrorCode { |
| 467 |
return errorCode(err) |
| 468 |
} |
| 469 |
|
| 470 |
var errorCodes = map[int]gcerrors.ErrorCode{ |
| 471 |
amqp.NotFound: gcerrors.NotFound, |
| 472 |
amqp.PreconditionFailed: gcerrors.FailedPrecondition, |
| 473 |
// These next indicate a bug in our driver, not the user's code. |
| 474 |
amqp.SyntaxError: gcerrors.Internal, |
| 475 |
amqp.CommandInvalid: gcerrors.Internal, |
| 476 |
amqp.InternalError: gcerrors.Internal, |
| 477 |
amqp.NotImplemented: gcerrors.Unimplemented, |
| 478 |
amqp.ChannelError: gcerrors.FailedPrecondition, // typically channel closed |
| 479 |
} |
| 480 |
|
| 481 |
func errorCode(err error) gcerrors.ErrorCode { |
| 482 |
var aerr *amqp.Error |
| 483 |
if !errors.As(err, &aerr) { |
| 484 |
return gcerrors.Unknown |
| 485 |
} |
| 486 |
if ec, ok := errorCodes[aerr.Code]; ok { |
| 487 |
return ec |
| 488 |
} |
| 489 |
return gcerrors.Unknown |
| 490 |
} |
| 491 |
|
| 492 |
func isRetryable(err error) bool { |
| 493 |
var aerr *amqp.Error |
| 494 |
if !errors.As(err, &aerr) { |
| 495 |
return false |
| 496 |
} |
| 497 |
// amqp.Error has a Recover field which sounds like it should mean "retryable". |
| 498 |
// But it actually means "can be recovered by retrying later or with different |
| 499 |
// parameters," which is not what we want. The error codes for which Recover is |
| 500 |
// true, defined in the isSoftExceptionCode function of |
| 501 |
// https://github.com/rabbitmq/amqp091-go/blob/main/spec091.go, including things |
| 502 |
// like NotFound and AccessRefused, which require outside action. |
| 503 |
// |
| 504 |
// The following are the codes which might be resolved by retry without external |
| 505 |
// action, according to the AMQP 0.91 spec |
| 506 |
// (https://www.rabbitmq.com/amqp-0-9-1-reference.html#constants). The quotations |
| 507 |
// are from that page. |
| 508 |
switch aerr.Code { |
| 509 |
case amqp.ContentTooLarge: |
| 510 |
// "The client attempted to transfer content larger than the server could |
| 511 |
// accept at the present time. The client may retry at a later time." |
| 512 |
return true |
| 513 |
|
| 514 |
case amqp.ConnectionForced: |
| 515 |
// "An operator intervened to close the connection for some reason. The |
| 516 |
// client may retry at some later date." |
| 517 |
return true |
| 518 |
|
| 519 |
default: |
| 520 |
return false |
| 521 |
} |
| 522 |
} |
| 523 |
|
| 524 |
// As implements driver.Topic.As. |
| 525 |
func (t *topic) As(i any) bool { |
| 526 |
c, ok := i.(**amqp.Connection) |
| 527 |
if !ok { |
| 528 |
return false |
| 529 |
} |
| 530 |
conn, ok := t.conn.(*connection) |
| 531 |
if !ok { // running against the fake |
| 532 |
return false |
| 533 |
} |
| 534 |
*c = conn.conn |
| 535 |
return true |
| 536 |
} |
| 537 |
|
| 538 |
// ErrorAs implements driver.Topic.ErrorAs |
| 539 |
func (*topic) ErrorAs(err error, i any) bool { |
| 540 |
return errorAs(err, i) |
| 541 |
} |
| 542 |
|
| 543 |
func errorAs(err error, i any) bool { |
| 544 |
var aerr *amqp.Error |
| 545 |
if errors.As(err, &aerr) { |
| 546 |
if p, ok := i.(**amqp.Error); ok { |
| 547 |
*p = aerr |
| 548 |
return true |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
var merr MultiError |
| 553 |
if errors.As(err, &merr) { |
| 554 |
if p, ok := i.(*MultiError); ok { |
| 555 |
*p = merr |
| 556 |
return true |
| 557 |
} |
| 558 |
} |
| 559 |
|
| 560 |
return false |
| 561 |
} |
| 562 |
|
| 563 |
// Close implements driver.Topic.Close. |
| 564 |
func (*topic) Close() error { return nil } |
| 565 |
|
| 566 |
// OpenSubscription returns a *pubsub.Subscription corresponding to the named queue. |
| 567 |
// See the package documentation for an example. |
| 568 |
// |
| 569 |
// The queue must have been previously created (for instance, by using |
| 570 |
// amqp.Channel.QueueDeclare) and bound to an exchange. |
| 571 |
// |
| 572 |
// OpenSubscription uses the supplied amqp.Connection for all communication. It is |
| 573 |
// the caller's responsibility to establish this connection before calling |
| 574 |
// OpenSubscription and to close it when Close has been called on all Subscriptions |
| 575 |
// opened with it. |
| 576 |
// |
| 577 |
// The documentation of the amqp package recommends using separate connections for |
| 578 |
// publishing and subscribing. |
| 579 |
func OpenSubscription(conn *amqp.Connection, name string, opts *SubscriptionOptions) *pubsub.Subscription { |
| 580 |
return pubsub.NewSubscription(newSubscription(&connection{conn}, name, opts), nil, nil) |
| 581 |
} |
| 582 |
|
| 583 |
type subscription struct { |
| 584 |
conn amqpConnection |
| 585 |
queue string // the AMQP queue name |
| 586 |
consumer string // the client-generated name for this particular subscriber |
| 587 |
|
| 588 |
opts *SubscriptionOptions |
| 589 |
|
| 590 |
mu sync.Mutex |
| 591 |
ch amqpChannel // AMQP channel used for all communication. |
| 592 |
delc <-chan amqp.Delivery |
| 593 |
closec <-chan *amqp.Error |
| 594 |
|
| 595 |
receiveBatchHook func() // for testing |
| 596 |
} |
| 597 |
|
| 598 |
var nextConsumer int64 // atomic |
| 599 |
|
| 600 |
func newSubscription(conn amqpConnection, name string, opts *SubscriptionOptions) *subscription { |
| 601 |
if opts == nil { |
| 602 |
opts = &SubscriptionOptions{} |
| 603 |
} |
| 604 |
|
| 605 |
return &subscription{ |
| 606 |
conn: conn, |
| 607 |
queue: name, |
| 608 |
consumer: fmt.Sprintf("c%d", atomic.AddInt64(&nextConsumer, 1)), |
| 609 |
opts: opts, |
| 610 |
receiveBatchHook: func() {}, |
| 611 |
} |
| 612 |
} |
| 613 |
|
| 614 |
// Must be called with s.mu held. |
| 615 |
func (s *subscription) establishChannel(ctx context.Context) error { |
| 616 |
if s.ch != nil { // We already have a channel. |
| 617 |
select { |
| 618 |
// If it was closed, open a new one. |
| 619 |
// (Ignore the error, if any.) |
| 620 |
case <-s.closec: |
| 621 |
|
| 622 |
// If it isn't closed, nothing to do. |
| 623 |
default: |
| 624 |
return nil |
| 625 |
} |
| 626 |
} |
| 627 |
var ch amqpChannel |
| 628 |
err := runWithContext(ctx, func() error { |
| 629 |
// Create a new channel. |
| 630 |
var err error |
| 631 |
ch, err = s.conn.Channel() |
| 632 |
if err != nil { |
| 633 |
return err |
| 634 |
} |
| 635 |
// Apply subscription options to channel. |
| 636 |
err = applyOptionsToChannel(s.opts, ch) |
| 637 |
if err != nil { |
| 638 |
return err |
| 639 |
} |
| 640 |
// Subscribe to messages from the queue. |
| 641 |
s.delc, err = ch.Consume(s.queue, s.consumer) |
| 642 |
return err |
| 643 |
}) |
| 644 |
if err != nil { |
| 645 |
return err |
| 646 |
} |
| 647 |
|
| 648 |
s.ch = ch |
| 649 |
s.closec = ch.NotifyClose(make(chan *amqp.Error, 1)) // closec will get at most one element |
| 650 |
|
| 651 |
return nil |
| 652 |
} |
| 653 |
|
| 654 |
func applyOptionsToChannel(opts *SubscriptionOptions, ch amqpChannel) error { |
| 655 |
if opts.PrefetchCount == nil { |
| 656 |
return nil |
| 657 |
} |
| 658 |
|
| 659 |
if err := ch.Qos(*opts.PrefetchCount, 0, false); err != nil { |
| 660 |
return fmt.Errorf("unable to set channel Qos: %w", err) |
| 661 |
} |
| 662 |
|
| 663 |
return nil |
| 664 |
} |
| 665 |
|
| 666 |
// ReceiveBatch implements driver.Subscription.ReceiveBatch. |
| 667 |
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) { |
| 668 |
s.mu.Lock() |
| 669 |
defer s.mu.Unlock() |
| 670 |
|
| 671 |
if err := s.establishChannel(ctx); err != nil { |
| 672 |
return nil, err |
| 673 |
} |
| 674 |
|
| 675 |
s.receiveBatchHook() |
| 676 |
|
| 677 |
// Get up to maxMessages waiting messages, but don't take too long. |
| 678 |
var ms []*driver.Message |
| 679 |
maxTime := time.NewTimer(50 * time.Millisecond) |
| 680 |
for { |
| 681 |
select { |
| 682 |
case <-ctx.Done(): |
| 683 |
// Cancel the Consume. |
| 684 |
_ = s.ch.Cancel(s.consumer) // ignore the error |
| 685 |
s.ch = nil |
| 686 |
return nil, ctx.Err() |
| 687 |
|
| 688 |
case d, ok := <-s.delc: |
| 689 |
if !ok { // channel closed |
| 690 |
s.ch = nil // re-establish the channel next time |
| 691 |
if len(ms) > 0 { |
| 692 |
return ms, nil |
| 693 |
} |
| 694 |
// s.closec must be closed too. See if it has an error. |
| 695 |
if err := closeErr(s.closec); err != nil { |
| 696 |
// PreconditionFailed can happen if we send an Ack or Nack for a |
| 697 |
// message that has already been acked/nacked. Ignore those errors. |
| 698 |
var aerr *amqp.Error |
| 699 |
if errors.As(err, &aerr) && aerr.Code == amqp.PreconditionFailed { |
| 700 |
return nil, nil |
| 701 |
} |
| 702 |
return nil, err |
| 703 |
} |
| 704 |
// We shouldn't be here, but if we are, we still want to return an |
| 705 |
// error. |
| 706 |
return nil, errors.New("rabbitpubsub: delivery channel closed unexpectedly") |
| 707 |
} |
| 708 |
ms = append(ms, toDriverMessage(d, s.opts)) |
| 709 |
if len(ms) >= maxMessages { |
| 710 |
return ms, nil |
| 711 |
} |
| 712 |
|
| 713 |
case <-maxTime.C: |
| 714 |
// Timed out. Return whatever we have. If we have nothing, we'll get |
| 715 |
// called again soon, but returning allows us to give up the lock in |
| 716 |
// case there are acks/nacks to be sent. |
| 717 |
return ms, nil |
| 718 |
} |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
// toDriverMessage converts an amqp.Delivery (a received message) to a driver.Message. |
| 723 |
func toDriverMessage(d amqp.Delivery, opts *SubscriptionOptions) *driver.Message { |
| 724 |
// Delivery.Headers is a map[string]any, so we have to |
| 725 |
// convert each value to a string. |
| 726 |
md := map[string]string{} |
| 727 |
for k, v := range d.Headers { |
| 728 |
md[k] = fmt.Sprint(v) |
| 729 |
} |
| 730 |
// Add a metadata entry for the message routing key if appropriate. |
| 731 |
if d.RoutingKey != "" && opts.KeyName != "" { |
| 732 |
md[opts.KeyName] = d.RoutingKey |
| 733 |
} |
| 734 |
loggableID := d.MessageId |
| 735 |
if loggableID == "" { |
| 736 |
loggableID = d.CorrelationId |
| 737 |
} |
| 738 |
if loggableID == "" { |
| 739 |
loggableID = fmt.Sprintf("DeliveryTag %d", d.DeliveryTag) |
| 740 |
} |
| 741 |
return &driver.Message{ |
| 742 |
LoggableID: loggableID, |
| 743 |
Body: d.Body, |
| 744 |
AckID: d.DeliveryTag, |
| 745 |
Metadata: md, |
| 746 |
AsFunc: func(i any) bool { |
| 747 |
p, ok := i.(*amqp.Delivery) |
| 748 |
if !ok { |
| 749 |
return false |
| 750 |
} |
| 751 |
*p = d |
| 752 |
return true |
| 753 |
}, |
| 754 |
} |
| 755 |
} |
| 756 |
|
| 757 |
// SendAcks implements driver.Subscription.SendAcks. |
| 758 |
func (s *subscription) SendAcks(ctx context.Context, ackIDs []driver.AckID) error { |
| 759 |
return s.sendAcksOrNacks(ctx, ackIDs, true) |
| 760 |
} |
| 761 |
|
| 762 |
// CanNack implements driver.CanNack. |
| 763 |
func (s *subscription) CanNack() bool { return true } |
| 764 |
|
| 765 |
// SendNacks implements driver.Subscription.SendNacks. |
| 766 |
func (s *subscription) SendNacks(ctx context.Context, ackIDs []driver.AckID) error { |
| 767 |
return s.sendAcksOrNacks(ctx, ackIDs, false) |
| 768 |
} |
| 769 |
|
| 770 |
func (s *subscription) sendAcksOrNacks(ctx context.Context, ackIDs []driver.AckID, ack bool) error { |
| 771 |
s.mu.Lock() |
| 772 |
defer s.mu.Unlock() |
| 773 |
|
| 774 |
if err := s.establishChannel(ctx); err != nil { |
| 775 |
return err |
| 776 |
} |
| 777 |
|
| 778 |
// Ack/Nack calls don't wait for a response, so this loop should execute relatively |
| 779 |
// quickly. |
| 780 |
// It wouldn't help to make it concurrent, because Channel.Ack/Nack grabs a |
| 781 |
// channel-wide mutex. (We could consider using multiple channels if performance |
| 782 |
// becomes an issue.) |
| 783 |
for _, id := range ackIDs { |
| 784 |
if ctx.Err() != nil { |
| 785 |
return ctx.Err() |
| 786 |
} |
| 787 |
var err error |
| 788 |
if ack { |
| 789 |
err = s.ch.Ack(id.(uint64)) |
| 790 |
} else { |
| 791 |
err = s.ch.Nack(id.(uint64)) |
| 792 |
} |
| 793 |
if err != nil { |
| 794 |
s.ch = nil // re-establish channel after an error |
| 795 |
return err |
| 796 |
} |
| 797 |
} |
| 798 |
return nil |
| 799 |
} |
| 800 |
|
| 801 |
// IsRetryable implements driver.Subscription.IsRetryable. |
| 802 |
func (*subscription) IsRetryable(err error) bool { |
| 803 |
return isRetryable(err) |
| 804 |
} |
| 805 |
|
| 806 |
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode { |
| 807 |
return errorCode(err) |
| 808 |
} |
| 809 |
|
| 810 |
// As implements driver.Subscription.As. |
| 811 |
func (s *subscription) As(i any) bool { |
| 812 |
c, ok := i.(**amqp.Connection) |
| 813 |
if !ok { |
| 814 |
return false |
| 815 |
} |
| 816 |
conn, ok := s.conn.(*connection) |
| 817 |
if !ok { // running against the fake |
| 818 |
return false |
| 819 |
} |
| 820 |
*c = conn.conn |
| 821 |
return true |
| 822 |
} |
| 823 |
|
| 824 |
// ErrorAs implements driver.Subscription.ErrorAs |
| 825 |
func (*subscription) ErrorAs(err error, i any) bool { |
| 826 |
return errorAs(err, i) |
| 827 |
} |
| 828 |
|
| 829 |
// Close implements driver.Subscription.Close. |
| 830 |
func (*subscription) Close() error { return nil } |