Documentation
¶
Overview ¶
Package amqp provides an opinionated RabbitMQ transport for event-driven architectures, built on the gomessaging spec module for naming conventions, topology, and CloudEvents support.
Index ¶
- Constants
- Variables
- func CollectTopology(serviceName string, setups ...Setup) (spec.Topology, error)
- func InitMetrics(registerer prometheus.Registerer, opts ...MetricsOption) error
- func Must[T any](t *T, err error) *T
- func TypeMappingHandler(handler spec.EventHandler[any], routingKeyToType TypeMapper) spec.EventHandler[any]
- type Connection
- func (c *Connection) Close() error
- func (c *Connection) PublishServiceResponse(ctx context.Context, targetService, routingKey string, msg any) error
- func (c *Connection) Start(ctx context.Context, opts ...Setup) (err error)
- func (c *Connection) Topology() spec.Topology
- func (c *Connection) URI() amqp.URI
- type ConsumerOptions
- type Header
- type MetricsOption
- type OutboxRawPublisher
- type Publisher
- type PublisherOption
- type ReconnectOption
- type ServicePublisherOption
- type ServiceResponsePublisher
- type Setup
- func CloseListener(e chan error) Setup
- func EventStreamConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
- func EventStreamPublisher(publisher *Publisher) Setup
- func QueuePublisher(publisher *Publisher, destinationQueueName string) Setup
- func RequestResponseHandler[T any, R any](routingKey string, handler spec.RequestResponseEventHandler[T, R]) Setup
- func ServicePublisher(targetService string, publisher *Publisher, opts ...ServicePublisherOption) Setup
- func ServiceRequestConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
- func ServiceResponseConsumer[T any](targetService, routingKey string, handler spec.EventHandler[T], ...) Setup
- func StreamConsumer[T any](exchange, routingKey string, handler spec.EventHandler[T], ...) Setup
- func StreamPublisher(exchange string, publisher *Publisher) Setup
- func TransientEventStreamConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
- func TransientStreamConsumer[T any](exchange, routingKey string, handler spec.EventHandler[T], ...) Setup
- func WithErrorChannel(errorCh chan<- spec.ErrorNotification) Setup
- func WithLegacySupport() Setup
- func WithLogger(logger *slog.Logger) Setup
- func WithNotificationChannel(notificationCh chan<- spec.Notification) Setup
- func WithPrefetchLimit(limit int) Setup
- func WithPropagator(p propagation.TextMapPropagator) Setup
- func WithPublishSpanNameFn(f func(exchange, routingKey string) string) Setup
- func WithReconnect(opts ...ReconnectOption) Setup
- func WithSpanNameFn(f func(spec.DeliveryInfo) string) Setup
- func WithTracing(tp trace.TracerProvider) Setup
- type TypeMapper
Constants ¶
const ( DefaultReconnectInterval = 1 * time.Second DefaultReconnectMaxInterval = 30 * time.Second DefaultReconnectMaxElapsed = 2 * time.Minute )
Defaults for WithReconnect, used for any option left unset.
Variables ¶
var ( // ErrEmptySuffix is returned when an empty suffix is passed to AddQueueNameSuffix. ErrEmptySuffix = fmt.Errorf("empty queue suffix not allowed") // ErrAlreadyStarted is returned when Start is called on an already-started connection. ErrAlreadyStarted = fmt.Errorf("already started") )
var ErrEmptyHeaderKey = errors.New("empty key not allowed")
ErrEmptyHeaderKey is returned when a Header is created with an empty key.
var ErrNoMessageTypeForRouteKey = fmt.Errorf("no message type for routing key configured")
ErrNoMessageTypeForRouteKey is returned when a TypeMapper has no type registered for the routing key.
var ErrNotConnected = errors.New("amqp connection not established")
ErrNotConnected is returned when a publish is attempted while the connection is down, typically between a disconnect and a successful reconnect.
Functions ¶
func CollectTopology ¶
CollectTopology runs the given setup functions against a no-op channel to collect the topology that would be declared, without connecting to a broker. This is useful for generating topology JSON for visualization or validation.
func InitMetrics ¶
func InitMetrics(registerer prometheus.Registerer, opts ...MetricsOption) error
InitMetrics registers all AMQP Prometheus metrics with the given registerer. Call this once during application startup before Start(), e.g. InitMetrics(prometheus.DefaultRegisterer). The mapper is applied globally and subsequent calls overwrite the previous mapper.
func Must ¶
Must is a helper that wraps a call to a function returning (*T, error) and panics if the error is non-nil. It is intended for use in variable initializations such as var c = goamqp.Must(goamqp.NewFromURL("service", "amqp://"))
func TypeMappingHandler ¶
func TypeMappingHandler(handler spec.EventHandler[any], routingKeyToType TypeMapper) spec.EventHandler[any]
TypeMappingHandler wraps an EventHandler[any] and uses the TypeMapper to unmarshal each message payload into the correct concrete type before passing it to the handler. This is useful when a single consumer handles multiple event types on a wildcard routing key.
Types ¶
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection is a wrapper around the actual amqp.Connection and amqp.Channel
func NewFromURL ¶
func NewFromURL(serviceName string, amqpURL string) (*Connection, error)
NewFromURL creates a new Connection by parsing an AMQP URL. The serviceName is used for exchange/queue naming and tracing.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close closes the amqp connection, see amqp.Connection.Close
func (*Connection) PublishServiceResponse ¶
func (c *Connection) PublishServiceResponse(ctx context.Context, targetService, routingKey string, msg any) error
PublishServiceResponse sends a message to targetService as a handler response
func (*Connection) Start ¶
func (c *Connection) Start(ctx context.Context, opts ...Setup) (err error)
Start connects to AMQP, applies each Setup function to declare exchanges, queues, and bindings, then starts all consumers. It returns ErrAlreadyStarted if called twice.
func (*Connection) Topology ¶
func (c *Connection) Topology() spec.Topology
Topology returns the messaging topology declared by this connection's setup. It is populated during Start() as setup functions execute.
func (*Connection) URI ¶
func (c *Connection) URI() amqp.URI
URI returns the parsed AMQP URI used by this connection.
type ConsumerOptions ¶
type ConsumerOptions func(config *consumerConfig) error
ConsumerOptions is a setup function that takes a consumerConfig and provide custom changes to the configuration
func AddQueueNameSuffix ¶
func AddQueueNameSuffix(suffix string) ConsumerOptions
AddQueueNameSuffix appends the provided suffix to the queue name Useful when multiple queueConsumers are needed for a routing key in the same service
func DisableSingleActiveConsumer ¶
func DisableSingleActiveConsumer() ConsumerOptions
DisableSingleActiveConsumer will define the queue as non exclusive and set the x-single-active-consumer header to false https://www.rabbitmq.com/docs/consumers#exclusivity
func WithDeadLetter ¶
func WithDeadLetter(exchange ...string) ConsumerOptions
WithDeadLetter enables dead-lettering for the consumer's queue: rejected (nacked, no requeue), TTL-expired, and over-length messages are routed to a dead letter exchange.
With no argument it uses the managed per-service dead letter topology — a fanout exchange (<service>.fanout.exchange.deadletter) and a bound quorum queue — which the library declares automatically.
Pass a single exchange name to route to an existing external exchange instead; that exchange (and any bindings) must already exist.
func WithDeadLetterRoutingKey ¶
func WithDeadLetterRoutingKey(key string) ConsumerOptions
WithDeadLetterRoutingKey sets a custom routing key for dead-lettered messages. If not set, the original routing key is preserved.
type Header ¶
Header represents a key-value pair attached to an AMQP message. Value types are constrained by amqp.Table; see the AMQP 0-9-1 spec for allowed types.
type MetricsOption ¶
type MetricsOption func(*metricsConfig)
MetricsOption configures Prometheus metric behavior.
func WithRoutingKeyMapper ¶
func WithRoutingKeyMapper(fn func(string) string) MetricsOption
WithRoutingKeyMapper sets a function applied to every routing key before it is used as a Prometheus label value. Use this to normalize or redact dynamic segments (e.g. UUIDs) from routing keys to prevent unbounded label cardinality. The default is the identity function (labels pass through unchanged). The mapper must return a non-empty string; empty returns are replaced with "unknown".
type OutboxRawPublisher ¶
type OutboxRawPublisher struct {
// contains filtered or unexported fields
}
OutboxRawPublisher wraps an AMQP Publisher to satisfy the outbox.RawPublisher interface. Headers are received as ce-* prefixed keys and normalized to the AMQP cloudEvents:* wire format before publishing.
func NewOutboxRawPublisher ¶
func NewOutboxRawPublisher(publisher *Publisher) *OutboxRawPublisher
NewOutboxRawPublisher creates an adapter that wraps publisher for use with the outbox relay. The publisher must already be wired to a connection.
func (*OutboxRawPublisher) PublishRaw ¶
func (a *OutboxRawPublisher) PublishRaw(ctx context.Context, routingKey string, payload []byte, headers map[string]string) error
PublishRaw publishes a pre-serialized message to AMQP with the given headers. ce-* headers are normalized to cloudEvents:* per the AMQP binding spec.
type Publisher ¶
type Publisher struct {
// contains filtered or unexported fields
}
Publisher is used to send messages. It is safe for concurrent use from multiple goroutines.
func NewPublisher ¶
func NewPublisher(opts ...PublisherOption) *Publisher
NewPublisher creates an uninitialized Publisher. Pass it to a publisher Setup function (e.g. EventStreamPublisher, ServicePublisher) which wires it to the connection's channel and exchange. After Start completes, call Publish to send messages.
func (*Publisher) Publish ¶
func (p *Publisher) Publish(ctx context.Context, routingKey string, msg any, headers ...Header) error
Publish sends msg as a JSON-encoded AMQP message with the given routing key. Additional headers can be provided to attach metadata to the message. By default, Publish waits for broker confirmation and returns an error if the broker nacks. Use WithoutPublisherConfirms to disable this behavior.
type PublisherOption ¶
type PublisherOption func(*Publisher)
PublisherOption is a functional option for NewPublisher.
func WithConfirm ¶
func WithConfirm(ch chan amqp.Confirmation) PublisherOption
WithConfirm enables publisher confirms on this publisher's own AMQP channel. Confirmations are delivered to the provided channel. Note that the caller then owns the channel's lifetime. The transport closes any channel registered for notifications when the AMQP channel closes, so with WithReconnect the supplied channel is closed by the disconnect and is not replaced — a publisher that must survive reconnects should let the library own its confirm channel instead.
func WithoutPublisherConfirms ¶
func WithoutPublisherConfirms() PublisherOption
WithoutPublisherConfirms disables publisher confirms for this publisher. By default, Publish() waits for broker confirmation and returns error on nack. Use this opt-out for high-throughput scenarios where occasional message loss is acceptable.
type ReconnectOption ¶ added in v0.0.4
type ReconnectOption func(*reconnectConfig)
ReconnectOption configures WithReconnect.
func ReconnectInterval ¶ added in v0.0.4
func ReconnectInterval(d time.Duration) ReconnectOption
ReconnectInterval sets the delay before the first retry. Each subsequent attempt doubles it, up to ReconnectMaxInterval.
func ReconnectMaxElapsed ¶ added in v0.0.4
func ReconnectMaxElapsed(d time.Duration) ReconnectOption
ReconnectMaxElapsed bounds how long reconnection is attempted before giving up. Zero means never give up.
Giving up is not a silent state: the error is delivered to the CloseListener channel exactly as an unrecovered disconnect is today, so a caller that exits on that signal still exits — just later than it would have without this option.
func ReconnectMaxInterval ¶ added in v0.0.4
func ReconnectMaxInterval(d time.Duration) ReconnectOption
ReconnectMaxInterval caps the delay between attempts.
Without a cap, exponential growth quickly reaches delays long enough that a broker which came back minutes ago is still not being retried.
type ServicePublisherOption ¶ added in v0.0.3
type ServicePublisherOption func(*servicePublisherConfig)
ServicePublisherOption configures a service request publisher.
func VerifyTarget ¶ added in v0.0.3
func VerifyTarget() ServicePublisherOption
VerifyTarget asserts at Start() that the target service's request queue already exists, failing the connection if it does not.
The request queue is declared by the target's own consumer registration, so its absence does not mean "the consumer is busy" -- it means that service has never run against this broker, and every message published to the exchange is discarded.
Off by default: it makes the target's availability a startup dependency of the caller. Use it where a request nobody can execute is a deployment error worth catching at rollout rather than on the first real request.
type ServiceResponsePublisher ¶
type ServiceResponsePublisher[T any] func(ctx context.Context, targetService, routingKey string, event T) error
ServiceResponsePublisher is the callback signature used to publish a response back to the originating service in the request-response pattern.
type Setup ¶
type Setup func(conn *Connection) error
Setup is a setup function that takes a Connection and use it to set up AMQP An example is to create exchanges and queues
func CloseListener ¶
CloseListener receives close errors from both AMQP channels and the underlying connection. Use this to detect unexpected disconnects and implement fail-fast behavior (e.g. os.Exit).
func EventStreamConsumer ¶
func EventStreamConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
EventStreamConsumer sets up a durable, persistent event stream consumer on the default "events" topic exchange. For a transient queue, use TransientEventStreamConsumer instead.
func EventStreamPublisher ¶
EventStreamPublisher sets up an event stream publisher
func QueuePublisher ¶
QueuePublisher sets up a publisher that will send events to a specific queue instead of using the exchange, so called Sender-Selected distribution https://www.rabbitmq.com/sender-selected.html#:~:text=The%20RabbitMQ%20broker%20treats%20the,key%20if%20they%20are%20present.
func RequestResponseHandler ¶
func RequestResponseHandler[T any, R any](routingKey string, handler spec.RequestResponseEventHandler[T, R]) Setup
RequestResponseHandler is a convenience func to set up ServiceRequestConsumer and combines it with PublishServiceResponse
func ServicePublisher ¶
func ServicePublisher(targetService string, publisher *Publisher, opts ...ServicePublisherOption) Setup
ServicePublisher sets up a publisher that sends messages to the targetService's request exchange.
func ServiceRequestConsumer ¶
func ServiceRequestConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
ServiceRequestConsumer sets up a durable, persistent consumer for incoming service requests. It binds to the connection's own service request exchange using direct routing.
func ServiceResponseConsumer ¶
func ServiceResponseConsumer[T any](targetService, routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
ServiceResponseConsumer sets up a durable, persistent consumer for responses from targetService. It binds to the target service's response exchange using header-based routing.
func StreamConsumer ¶
func StreamConsumer[T any](exchange, routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
StreamConsumer sets up a durable, persistent event stream consumer on a named topic exchange.
func StreamPublisher ¶
StreamPublisher sets up an event stream publisher
func TransientEventStreamConsumer ¶
func TransientEventStreamConsumer[T any](routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
TransientEventStreamConsumer sets up an event stream consumer that will clean up resources when the connection is closed. For a durable queue, use the EventStreamConsumer function instead.
func TransientStreamConsumer ¶
func TransientStreamConsumer[T any](exchange, routingKey string, handler spec.EventHandler[T], opts ...ConsumerOptions) Setup
TransientStreamConsumer sets up an event stream consumer that will clean up resources when the connection is closed. For a durable queue, use the StreamConsumer function instead.
func WithErrorChannel ¶
func WithErrorChannel(errorCh chan<- spec.ErrorNotification) Setup
WithErrorChannel specifies a go channel to receive messages such as event failed
func WithLegacySupport ¶
func WithLegacySupport() Setup
WithLegacySupport enables automatic metadata enrichment for messages from legacy (pre-CloudEvents) publishers. When enabled, incoming messages that lack CloudEvents headers will have their Metadata populated with synthetic values (generated UUID, current timestamp, routing key as type, exchange as source).
Without this option, legacy messages arrive with zero-valued Metadata, which is the existing default behavior.
func WithLogger ¶
WithLogger configures structured logging for the connection. If not set, slog.Default() is used.
func WithNotificationChannel ¶
func WithNotificationChannel(notificationCh chan<- spec.Notification) Setup
WithNotificationChannel specifies a go channel to receive messages such as connection event published, consumed, etc.
func WithPrefetchLimit ¶
WithPrefetchLimit configures the number of messages to prefetch from the server. To get round-robin behavior between queueConsumers consuming from the same queue on different connections, set the prefetch count to 1, and the next available message on the server will be delivered to the next available consumer. If your consumer work time is reasonably consistent and not much greater than two times your network round trip time, you will see significant throughput improvements starting with a prefetch count of 2 or slightly greater, as described by benchmarks on RabbitMQ.
http://www.rabbitmq.com/blog/2012/04/25/rabbitmq-performance-measurements-part-2/
func WithPropagator ¶
func WithPropagator(p propagation.TextMapPropagator) Setup
WithPropagator configures a TextMapPropagator for the connection. If not set, the global propagator (otel.GetTextMapPropagator()) is used.
func WithPublishSpanNameFn ¶
WithPublishSpanNameFn specifies a function that will get called when a new publish span is created. The function receives the exchange name and routing key. By default "publish {routingKey}" is used.
func WithReconnect ¶ added in v0.0.4
func WithReconnect(opts ...ReconnectOption) Setup
WithReconnect re-establishes the connection after an unexpected disconnect, rather than reporting it and leaving the connection dead.
Off by default. Without it a disconnect goes straight to the CloseListener channel and the connection stays down, so a caller that exits on that signal fails fast — the behaviour every existing caller already has.
With it, the same signal is delayed rather than removed. The library redials with exponential backoff, and re-runs every Setup passed to Start against the new connection, so exchanges, queues, consumers and publishers are restored; a *Publisher held by the caller is rebound in place and keeps working. Only when the retry budget is exhausted does the error reach the CloseListener channel, so "reconnecting forever in silence" is not a state this can reach.
The point is to stop a broker outage taking down work that does not depend on the broker — an HTTP API served from a database, say — while keeping the eventual failure just as visible.
func WithSpanNameFn ¶
func WithSpanNameFn(f func(spec.DeliveryInfo) string) Setup
WithSpanNameFn specifies a function that will get called when a new consumer span is created. By default defaultSpanName will be used.
func WithTracing ¶
func WithTracing(tp trace.TracerProvider) Setup
WithTracing configures a TracerProvider for the connection. If not set, the global TracerProvider (otel.GetTracerProvider()) is used.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
tck-adapter
command
Binary amqp-adapter is the reference AMQP adapter for the TCK subprocess protocol.
|
Binary amqp-adapter is the reference AMQP adapter for the TCK subprocess protocol. |