diff --git a/kafka/README.md b/kafka/README.md index e69de29..4d7b006 100644 --- a/kafka/README.md +++ b/kafka/README.md @@ -0,0 +1,129 @@ +# Kafka + +Consumer processing failures are classified by the application. The SDK controls +retry timing, offset commits, and confirmed dead-letter publication. + +## Processing policy + +`ConsumerOptions.RetryPolicy` is optional. With no policy, the consumer allows +three retries with jittered exponential backoff under a ten-second total budget, +then returns an error wrapping `ErrConsumerPaused`. The failed record and later +unprocessed records are not committed. Earlier successful records may commit. + +A non-nil policy uses `MaxRetries` literally: zero means no retries. Backoff and +elapsed-time fields default when zero. Handlers must honor their context. + +| Classification | Behavior | +| --- | --- | +| `UnknownFailure` (default) | Bounded retries, then stop and preserve input; never automatically DLQ | +| `RetryableFailure` | Bounded retries, then stop; park only with explicit `OnExhausted: DeadLetter` | +| `PermanentFailure` | Skip retries; park if configured, otherwise stop and preserve input | +| `DependencyUnavailable` | Stop immediately; optional recovery probes gate a fresh consumer | +| `ConfigurationFailure` | Stop immediately for operator intervention | + +Use `errors.Is` or typed errors to classify application failures. Do not classify +by matching error-message text. Shutdown cancellation bypasses classification and +leaves unfinished work uncommitted. `ProcessingError` exposes `Kind`, `Attempts` +and the original wrapped error; the returned error also names the source topic, +partition and offset. Retry budgets and attempt metadata apply per invocation; +supervisors must not repeatedly restart unknown/configuration failures. + +## Dead-letter topic configuration + +A nil `DeadLetter` disables parking. Example for an existing topic: + +```go +options := kafka.ConsumerOptions{ + RetryPolicy: &kafka.RetryPolicy{ + Classify: classifyApplicationError, + MaxRetries: 3, + MaxElapsedTime: 10 * time.Second, + OnExhausted: kafka.DeadLetter, + }, + DeadLetter: &kafka.DeadLetterConfig{ + Topic: "cards.failed", + Provision: kafka.UseExisting, + Partitions: 3, + ReplicationFactor: 3, + Configs: map[string]string{ + "retention.ms": "604800000", + "retention.bytes": "1073741824", + "min.insync.replicas": "2", + }, + }, +} +``` + +`OnExhausted: DeadLetter` requires a configured destination, and only applies to +explicitly retryable errors. Unknown errors remain preserved even with a DLQ. + +`UseExisting` checks topic existence and any specified partition, replication, +and topic-config requirements before polling. Zero partition/replication fields +in this mode mean no requirement. `Declare` creates the topic if absent and +requires explicit positive partitions/replication. Existing incompatible topics +cause startup failure rather than silent reconfiguration. Topic configuration +validation requires the relevant Kafka describe permissions. Provisioning needs +create permissions. If exactly one source topic is configured, an empty +configured destination name defaults to `.dlq`. + +The consumer's client must use `AllISRAcks` for DLQ writes and cannot be +transactional. Consumers require a group, must disable auto-commit and use +`BlockRebalanceOnPoll`; `NewKafkaClientFromConfig` configures those group options. +The SDK waits for synchronous publication before committing the original offset. +A failed publication returns `ErrDLQPublish` and preserves the input. Retention, +replication and ISR policy determine broker-side durability. + +Payload, key and application headers are preserved. Reserved `fiddle.dlq.*` +headers hold source topic/partition/offset, classification, attempts and failure +time. Error metadata defaults to an error class/type; opt into sanitized details +with `DeadLetterConfig.ErrorFormatter`. A dead-letter topic must differ from +source topics. Redrive is explicit; the SDK never sends a DLQ back to its source. + +## Recovery without consuming an outage backlog + +`Start` returns on an outage, allowing the application to release the client. +Do not reuse a client that has fetched past a failed record. Use the same group +with a fresh client so broker-committed offsets determine redelivery. + +```go +err := kafka.RunWithRecovery(ctx, kafka.RecoveryPolicy{ + Probe: checkCardServiceHealth, // application dependency, not broker health + Interval: 30 * time.Second, + Timeout: 5 * time.Second, +}, func(ctx context.Context) error { + client, err := kafka.NewKafkaClientFromConfig(ctx, cfg) + if err != nil { return err } + defer client.Close() + err = kafka.NewConsumer(client, options).Start(ctx, handleCard) + // Record err here so the original cause is observable while probing. + return err +}) +``` + +Only a classified dependency outage triggers probes. No consumer exists while +probing; a successful, timely probe permits one fresh consumer run. Unknown, +configuration, setup, and DLQ transfer failures return to the caller. The outer +context bounds recovery; probes must honor their contexts. + +Delivery is at least once. A crash after DLQ publication but before offset commit +can create duplicates. Handlers and redrive tools must be idempotent. + +## Migration and verification + +Previously, exhausted failures could be committed with no DLQ. They now stop. +`DLQProducer` is deprecated and rejected at startup; use `DeadLetterConfig` so the +SDK can verify topology, acknowledgements and metadata. The standalone +`Producer.SendToDLQ` convenience method also requires `AllISRAcks`. + +Run `make check` from this module with Go 1.27.2 and the configured lint tools. +Unit tests use fake broker-operation interfaces. The optional broker test verifies +that a fresh consumer redelivers a failed record after earlier offsets commit: + +```sh +FIDDLE_KAFKA_BROKERS=localhost:9092 go test -run TestIntegration -count=1 -timeout 60s +``` + +Use a disposable plaintext cluster: the test creates/deletes a uniquely named +topic; the unique consumer group follows broker offset retention. Without the +environment variable it is skipped. No +Docker orchestration is needed by the test suite. diff --git a/kafka/adr.md b/kafka/adr.md new file mode 100644 index 0000000..d834d79 --- /dev/null +++ b/kafka/adr.md @@ -0,0 +1,26 @@ +# Processing failures and dead-letter delivery + +Status: implemented; executable verification pending the declared Go toolchain. + +The application classifies business failures; the SDK owns retry budgets and +settlement. Unknown failures stop without committing. Dependency outages stop +immediately; an optional SDK recovery loop probes before constructing a fresh +consumer. Only permanent failures or explicitly configured retry exhaustion are +parked. This avoids moving an outage backlog into a DLQ. + +Keep the existing Handler signature and add optional RetryPolicy/DeadLetterConfig. +Validate topic requirements before polling. Use the managed consumer's native +synchronous producer with AllISRAcks rather than an arbitrary DLQ producer whose +acknowledgement and metadata behavior cannot be verified. Reject automatic group +offset commits, which could advance past failures. Preserve the original cause +and record location for application observability. + +Use franz-go/kadm's topic APIs for provisioning and validation. Existing topics +are not silently altered. Kafka partition/replication/retention settings remain +explicit operational choices. Do not add a shared policy module dependency to +this standalone multi-module repository; RabbitMQ has the same policy contract. + +At-least-once semantics permit duplicate processing or parking after a crash. +Fresh-client recovery uses broker-committed offsets. Caller-owned resources must +be closed before entering the probe loop. Budgets are per run, and user callbacks +must respect context deadlines. Unknown errors never authorize deletion. diff --git a/kafka/client.go b/kafka/client.go index 845376c..22dce54 100644 --- a/kafka/client.go +++ b/kafka/client.go @@ -33,9 +33,10 @@ type Producer interface { // handler can stop on shutdown. With Config.EnableOTel it also carries the // record's receive span, so spans started from it join the producer's trace. // -// A non-nil error is retried (ConsumerOptions.MaxRetries) and then sent to the -// DLQ. The record's dlq_error header holds the error's class or type, not its -// message (see WithDLQClass and WithDLQErrorFormatter). +// RetryPolicy classifies a non-nil error. Unknown errors have a bounded retry +// budget and then stop consumption without advancing offsets. Permanent errors +// can be parked through DeadLetterConfig; dependency outages stop immediately. +// DLQ error text is opt-in through DeadLetterConfig.ErrorFormatter. type Handler func(ctx context.Context, record *kgo.Record) error // Consumer consumes messages from Kafka topics. diff --git a/kafka/consumer.go b/kafka/consumer.go index a9778a1..0c1cf68 100644 --- a/kafka/consumer.go +++ b/kafka/consumer.go @@ -16,6 +16,11 @@ const commitTimeout = 10 * time.Second // ConsumerOptions configures consumer behavior. type ConsumerOptions struct { + // RetryPolicy is optional. An explicit policy overrides legacy retry fields. + RetryPolicy *RetryPolicy + DeadLetter *DeadLetterConfig + // Deprecated: configure DeadLetter instead. Setting DLQProducer is rejected + // before consumption because its topology and write guarantees are unknown. DLQProducer Producer OnDLQPublish func(topic string, err error) MaxRetries int @@ -23,10 +28,19 @@ type ConsumerOptions struct { Logger *slog.Logger } +// recordIO captures the broker operations that settle one poll. +type recordIO interface { + CommitRecords(context.Context, ...*kgo.Record) error + ProduceSync(context.Context, ...*kgo.Record) kgo.ProduceResults +} + // consumer implements the Consumer interface. type consumer struct { client *kgo.Client + records recordIO options ConsumerOptions + policy RetryPolicy + initErr error } // NewConsumer creates a new Consumer with the given client and options. @@ -46,10 +60,31 @@ func NewConsumer(client *kgo.Client, opts ...ConsumerOptions) Consumer { if o.Logger != nil { options.Logger = o.Logger } + if o.RetryPolicy != nil { + options.RetryPolicy = o.RetryPolicy + } + if o.DeadLetter != nil { + options.DeadLetter = o.DeadLetter + } options.DLQProducer = o.DLQProducer options.OnDLQPublish = o.OnDLQPublish } - return &consumer{client: client, options: options} + var topics []string + if client != nil { + topics, _ = client.OptValue(kgo.ConsumeTopics).([]string) + } + options.DeadLetter = options.DeadLetter.normalized(topics) + policy := options.RetryPolicy.normalized() + if options.RetryPolicy == nil { + policy.MaxRetries = options.MaxRetries + policy.InitialBackoff = options.RetryBackoff + policy.MaxBackoff = max(policy.MaxBackoff, policy.InitialBackoff) + } + initErr := errors.Join(policy.validate(options.DeadLetter != nil), options.DeadLetter.validate(topics)) + if options.DLQProducer != nil { + initErr = errors.Join(initErr, errors.New("DLQProducer is deprecated; configure DeadLetter instead")) + } + return &consumer{client: client, records: client, options: options, policy: policy, initErr: initErr} } // Start begins consuming messages and processing them with the handler. @@ -58,11 +93,30 @@ func NewConsumer(client *kgo.Client, opts ...ConsumerOptions) Consumer { // Offsets of processed records are committed once per poll, so records still in // flight at shutdown are redelivered on restart (at-least-once). // -// If publishing a failed record to the DLQ fails, Start returns an error -// wrapping ErrDLQPublish without committing that record or any later one. The +// If processing stops or publishing to the DLQ fails, Start returns an error +// without committing that record or any later one. DLQ failures wrap ErrDLQPublish. The // client has already fetched past them, so close it and create a new one to have // them redelivered. func (c *consumer) Start(ctx context.Context, handler Handler) error { + if c.initErr != nil { + return c.initErr + } + if c.client == nil || handler == nil { + return errors.New("consumer requires a client and handler") + } + if group, _ := c.client.OptValue(kgo.ConsumerGroup).(string); group == "" { + return errors.New("reliable consumption requires a consumer group") + } else { + if disabled, _ := c.client.OptValue(kgo.DisableAutoCommit).(bool); !disabled { + return errors.New("consumer requires DisableAutoCommit") + } + if blocked, _ := c.client.OptValue(kgo.BlockRebalanceOnPoll).(bool); !blocked { + return errors.New("consumer requires BlockRebalanceOnPoll") + } + } + if err := prepareDeadLetter(ctx, c.client, c.options.DeadLetter); err != nil { + return fmt.Errorf("prepare dead-letter topic: %w", err) + } for { if err := ctx.Err(); err != nil { return err @@ -88,11 +142,14 @@ func (c *consumer) Start(ctx context.Context, handler Handler) error { func (c *consumer) processFetches(ctx context.Context, fetches kgo.Fetches, handler Handler) error { logger := c.options.Logger - // A fetch error on one partition must not drop records fetched from healthy ones. + // Process healthy partitions before returning fetch errors; never busy-loop + // on a persistent broker/authorization failure. + var fetchErr error fetches.EachError(func(topic string, partition int32, err error) { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return } + fetchErr = errors.Join(fetchErr, fmt.Errorf("fetch topic %s partition %d: %w", topic, partition, err)) logger.Error("fetch error", "topic", topic, "partition", partition, "error", err) }) @@ -114,87 +171,34 @@ func (c *consumer) processFetches(ctx context.Context, fetches kgo.Fetches, hand // redeliver records that were already handled. commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), commitTimeout) defer cancel() - if err := c.client.CommitRecords(commitCtx, processed...); err != nil { - logger.Error("commit error", "error", err) + if err := c.records.CommitRecords(commitCtx, processed...); err != nil { + return errors.Join(procErr, fetchErr, fmt.Errorf("commit processed offsets: %w", err)) } } - return procErr + return errors.Join(procErr, fetchErr) } -// handleRecord runs handler with retries and routes a final failure to the DLQ. -// A non-nil error means the record must not be committed. +// handleRecord leaves all settlement to processFetches. A non-nil error +// stops the poll at this record; neither it nor later records are committed. func (c *consumer) handleRecord(ctx context.Context, r *kgo.Record, handler Handler) error { - logger := c.options.Logger - - var lastErr error - for attempt := 0; attempt <= c.options.MaxRetries; attempt++ { - if attempt > 0 { - backoff := time.Duration(attempt) * c.options.RetryBackoff - select { - case <-ctx.Done(): - return ctx.Err() - case <-time.After(backoff): - } - } - - if lastErr = handler(recordContext(ctx, r), r); lastErr == nil { - return nil - } - // A handler that failed because Start's ctx was cancelled did not fail - // on its merits: neither retry it nor dead-letter the record. It stays - // uncommitted and is redelivered after restart. - if err := ctx.Err(); err != nil { - return err - } - logger.Warn("handler error, retrying", - "topic", r.Topic, - "partition", r.Partition, - "offset", r.Offset, - "attempt", attempt+1, - "max_retries", c.options.MaxRetries, - "error", lastErr, - ) + failure := c.policy.process(ctx, func(attemptCtx context.Context) error { return handler(recordContext(attemptCtx, r), r) }) + if err := ctx.Err(); err != nil { + return err } - - return c.deadLetter(ctx, r, lastErr) -} - -// deadLetter publishes a record whose handler kept failing to the DLQ. A -// non-nil error means the record must not be committed. -func (c *consumer) deadLetter(ctx context.Context, r *kgo.Record, handlerErr error) error { - logger := c.options.Logger - - if c.options.DLQProducer == nil { - logger.Error("handler failed, no DLQ configured", - "topic", r.Topic, - "partition", r.Partition, - "offset", r.Offset, - "error", handlerErr, - ) + if failure.err == nil { return nil } - - if err := c.options.DLQProducer.SendToDLQ(ctx, r.Topic, r.Value, r.Key, handlerErr); err != nil { - logger.Error("failed to send message to DLQ", - "error", err, - "topic", r.Topic, - "partition", r.Partition, - "offset", r.Offset, - "dlq_error", handlerErr, - ) - return fmt.Errorf("%w: topic %s partition %d offset %d: %w", ErrDLQPublish, r.Topic, r.Partition, r.Offset, err) - } - - logger.Error("message sent to DLQ", - "topic", r.Topic, - "partition", r.Partition, - "offset", r.Offset, - "dlq_topic", dlqTopic(r.Topic), - "error", handlerErr, - ) + if !failure.park || c.options.DeadLetter == nil || c.options.DeadLetter.Topic == r.Topic { + return fmt.Errorf("topic %s partition %d offset %d: %w", r.Topic, r.Partition, r.Offset, failure.paused()) + } + publishCtx, cancel := context.WithTimeout(ctx, c.options.DeadLetter.Timeout) + defer cancel() + if err := c.records.ProduceSync(publishCtx, deadLetterRecord(c.options.DeadLetter, r, failure)).FirstErr(); err != nil { + return fmt.Errorf("%w: topic %s partition %d offset %d: %w", ErrDLQPublish, r.Topic, r.Partition, r.Offset, errors.Join(failure.paused(), err)) + } if c.options.OnDLQPublish != nil { - c.options.OnDLQPublish(r.Topic, handlerErr) + c.options.OnDLQPublish(r.Topic, failure.err) } return nil } diff --git a/kafka/consumer_test.go b/kafka/consumer_test.go index 1ba749f..cd78ee6 100644 --- a/kafka/consumer_test.go +++ b/kafka/consumer_test.go @@ -6,7 +6,6 @@ import ( "io" "log/slog" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -14,25 +13,30 @@ import ( "go.opentelemetry.io/otel/trace" ) -// recordingDLQ is a Producer that only records SendToDLQ calls. -type recordingDLQ struct { - calls []error +type recordingIO struct { + committed []*kgo.Record + published []*kgo.Record + publishErr error + commitErr error } -func (*recordingDLQ) Produce(context.Context, *Message) error { return nil } -func (*recordingDLQ) SendMessage(context.Context, string, any) error { return nil } -func (d *recordingDLQ) SendToDLQ(_ context.Context, _ string, _, _ []byte, err error) error { - d.calls = append(d.calls, err) - return nil +func (r *recordingIO) CommitRecords(_ context.Context, records ...*kgo.Record) error { + r.committed = append(r.committed, records...) + return r.commitErr } - -func newTestConsumer(dlq Producer) *consumer { - return &consumer{options: ConsumerOptions{ - DLQProducer: dlq, - MaxRetries: 2, - RetryBackoff: time.Millisecond, - Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), - }} +func (r *recordingIO) ProduceSync(_ context.Context, records ...*kgo.Record) kgo.ProduceResults { + var results kgo.ProduceResults + for _, record := range records { + r.published = append(r.published, record) + results = append(results, kgo.ProduceResult{Record: record, Err: r.publishErr}) + } + return results +} +func newTestConsumer(records *recordingIO) *consumer { + if records == nil { + records = &recordingIO{} + } + return &consumer{records: records, policy: quickPolicy(UnknownFailure), options: ConsumerOptions{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}} } func TestHandleRecord_PassesContextToHandler(t *testing.T) { @@ -50,7 +54,7 @@ func TestHandleRecord_PassesContextToHandler(t *testing.T) { func TestHandleRecord_HandlerSeesShutdown(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) - dlq := &recordingDLQ{} + dlq := &recordingIO{} err := newTestConsumer(dlq).handleRecord(ctx, &kgo.Record{Topic: "t"}, func(ctx context.Context, _ *kgo.Record) error { cancel() // shutdown arrives while the handler runs @@ -59,22 +63,21 @@ func TestHandleRecord_HandlerSeesShutdown(t *testing.T) { }) assert.ErrorIs(t, err, context.Canceled) - assert.Empty(t, dlq.calls, "a record interrupted by shutdown must not be dead-lettered") + assert.Empty(t, dlq.published, "a record interrupted by shutdown must not be dead-lettered") } -func TestHandleRecord_DeadLettersAfterRetries(t *testing.T) { - dlq := &recordingDLQ{} - boom := errors.New("boom") - attempts := 0 - - err := newTestConsumer(dlq).handleRecord(context.Background(), &kgo.Record{Topic: "t"}, func(context.Context, *kgo.Record) error { - attempts++ - return boom - }) - - require.NoError(t, err) - assert.Equal(t, 3, attempts, "1 attempt + MaxRetries retries") - assert.Equal(t, []error{boom}, dlq.calls) +func TestHandleRecord_UnknownFailureDoesNotPublishOrCommit(t *testing.T) { + records := &recordingIO{} + c := newTestConsumer(records) + c.options.DeadLetter = (&DeadLetterConfig{Topic: "failed"}).normalized(nil) + boom := errors.New("service failure") + calls := 0 + err := c.handleRecord(context.Background(), &kgo.Record{Topic: "orders"}, func(context.Context, *kgo.Record) error { calls++; return boom }) + require.ErrorIs(t, err, ErrConsumerPaused) + require.ErrorIs(t, err, boom) + assert.Equal(t, 3, calls) + assert.Empty(t, records.published) + assert.Empty(t, records.committed) } func TestRecordContext_CarriesRecordSpan(t *testing.T) { diff --git a/kafka/dead_letter.go b/kafka/dead_letter.go new file mode 100644 index 0000000..4dea52f --- /dev/null +++ b/kafka/dead_letter.go @@ -0,0 +1,185 @@ +package kafka + +import ( + "context" + "errors" + "fmt" + "maps" + "strconv" + "strings" + "time" + + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" +) + +type ProvisionMode uint8 + +const ( + UseExisting ProvisionMode = iota + Declare +) + +// DeadLetterConfig describes a single destination for this consumer. Nil +// disables dead-lettering. Topic defaults to .dlq only when exactly one +// source topic is configured. Configs accepts Kafka topic settings, including +// retention.ms, retention.bytes, and min.insync.replicas. Unspecified settings +// retain broker defaults; existing topics are never silently reconfigured. +type DeadLetterConfig struct { + Topic string + Provision ProvisionMode + Partitions int32 + ReplicationFactor int16 + Configs map[string]string + Timeout time.Duration + // ErrorFormatter defaults to DLQErrorType; opt into messages deliberately. + ErrorFormatter func(error) string +} + +func (d *DeadLetterConfig) normalized(topics []string) *DeadLetterConfig { + if d == nil { + return nil + } + out := *d + out.Configs = maps.Clone(d.Configs) + if out.Topic == "" && len(topics) == 1 { + out.Topic = dlqTopic(topics[0]) + } + if out.Timeout == 0 { + out.Timeout = 10 * time.Second + } + if out.ErrorFormatter == nil { + out.ErrorFormatter = DLQErrorType + } + return &out +} + +func (d *DeadLetterConfig) validate(topics []string) error { + if d == nil { + return nil + } + if strings.TrimSpace(d.Topic) == "" || d.Topic == "." || d.Topic == ".." || len(d.Topic) > 249 || strings.ContainsAny(d.Topic, " /\\\t\n") { + return errors.New("invalid dead-letter topic") + } + for _, source := range topics { + if d.Topic == source { + return errors.New("dead-letter topic must differ from source topics") + } + } + if d.Provision > Declare || d.Timeout <= 0 || d.Partitions < 0 || d.ReplicationFactor < 0 { + return errors.New("invalid dead-letter configuration") + } + if d.Provision == Declare && (d.Partitions == 0 || d.ReplicationFactor == 0) { + return errors.New("declaring a dead-letter topic requires explicit partitions and replication factor") + } + return nil +} + +func prepareDeadLetter(ctx context.Context, client *kgo.Client, d *DeadLetterConfig) error { + if d == nil { + return nil + } + ctx, cancel := context.WithTimeout(ctx, d.Timeout) + defer cancel() + if client.OptValue(kgo.RequiredAcks) != kgo.AllISRAcks() { + return errors.New("dead-letter publishing requires AllISRAcks") + } + if id, _ := client.OptValue(kgo.TransactionalID).(string); id != "" { + return errors.New("dead-letter consumer requires a non-transactional client") + } + admin := kadm.NewClient(client) + if d.Provision == Declare { + configs := make(map[string]*string, len(d.Configs)) + for key, value := range d.Configs { + value := value + configs[key] = &value + } + responses, err := admin.CreateTopics(ctx, d.Partitions, d.ReplicationFactor, configs, d.Topic) + if err != nil { + return err + } + response, ok := responses[d.Topic] + if !ok { + return errors.New("missing dead-letter create response") + } + if response.Err != nil && !errors.Is(response.Err, kerr.TopicAlreadyExists) { + return response.Err + } + } + topics, err := admin.ListTopics(ctx, d.Topic) + if err != nil { + return err + } + topic, ok := topics[d.Topic] + if !ok { + return fmt.Errorf("dead-letter topic %s does not exist", d.Topic) + } + if topic.Err != nil { + return topic.Err + } + if len(topic.Partitions) == 0 { + return errors.New("dead-letter topic has no partitions") + } + if d.Partitions > 0 && len(topic.Partitions) != int(d.Partitions) { + return errors.New("dead-letter partition count differs from configuration") + } + for _, partition := range topic.Partitions { + if partition.Err != nil { + return partition.Err + } + if d.ReplicationFactor > 0 && len(partition.Replicas) != int(d.ReplicationFactor) { + return errors.New("dead-letter replication factor differs from configuration") + } + } + if len(d.Configs) == 0 { + return nil + } + configs, err := admin.DescribeTopicConfigs(ctx, d.Topic) + if err != nil { + return err + } + resource, err := configs.On(d.Topic, nil) + if err != nil { + return err + } + if resource.Err != nil { + return resource.Err + } + actual := make(map[string]string, len(resource.Configs)) + for _, cfg := range resource.Configs { + if cfg.Value != nil { + actual[cfg.Key] = *cfg.Value + } + } + for key, want := range d.Configs { + if got, ok := actual[key]; !ok || got != want { + return fmt.Errorf("dead-letter topic setting %s differs from configuration", key) + } + } + return nil +} + +func deadLetterRecord(d *DeadLetterConfig, source *kgo.Record, failure processingResult) *kgo.Record { + headers := make([]kgo.RecordHeader, 0, len(source.Headers)+7) + for _, h := range source.Headers { + if !strings.HasPrefix(h.Key, "fiddle.dlq.") { + headers = append(headers, h) + } + } + metadata := map[string]string{ + "source_topic": source.Topic, + "source_partition": strconv.FormatInt(int64(source.Partition), 10), + "source_offset": strconv.FormatInt(source.Offset, 10), + "failure_kind": failure.kind.String(), + "attempts": strconv.Itoa(failure.attempts), + "failed_at": time.Now().UTC().Format(time.RFC3339Nano), + } + if detail := d.ErrorFormatter(failure.err); detail != "" { + metadata["error"] = detail + } + for key, value := range metadata { + headers = append(headers, kgo.RecordHeader{Key: "fiddle.dlq." + key, Value: []byte(value)}) + } + return &kgo.Record{Topic: d.Topic, Key: source.Key, Value: source.Value, Headers: headers} +} diff --git a/kafka/delivery_test.go b/kafka/delivery_test.go new file mode 100644 index 0000000..4b3cef8 --- /dev/null +++ b/kafka/delivery_test.go @@ -0,0 +1,96 @@ +package kafka + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/require" + "github.com/twmb/franz-go/pkg/kgo" +) + +func fetchRecords(records ...*kgo.Record) kgo.Fetches { + return kgo.Fetches{{Topics: []kgo.FetchTopic{{Topic: "orders", Partitions: []kgo.FetchPartition{{Partition: 0, Records: records}}}}}} +} + +func TestFailedRecordStopsOffsetCommitBoundary(t *testing.T) { + for _, kind := range []FailureKind{UnknownFailure, PermanentFailure, DependencyUnavailable, ConfigurationFailure} { + t.Run(kind.String(), func(t *testing.T) { + io := &recordingIO{} + c := newTestConsumer(io) + c.policy = quickPolicy(kind) + source := []*kgo.Record{{Topic: "orders", Offset: 10}, {Topic: "orders", Offset: 11}, {Topic: "orders", Offset: 12}} + boom := errors.New("failed to read cards") + var seen []int64 + err := c.processFetches(context.Background(), fetchRecords(source...), func(_ context.Context, r *kgo.Record) error { + seen = append(seen, r.Offset) + if r.Offset == 11 { + return boom + } + return nil + }) + require.ErrorIs(t, err, boom) + require.ErrorIs(t, err, ErrConsumerPaused) + require.Equal(t, source[:1], io.committed) + require.NotContains(t, seen, int64(12)) + require.Empty(t, io.published) + }) + } +} + +func TestDeadLetterFailureDoesNotCommitOriginal(t *testing.T) { + for _, publishErr := range []error{nil, errors.New("DLQ unavailable")} { + io := &recordingIO{publishErr: publishErr} + c := newTestConsumer(io) + c.policy = quickPolicy(PermanentFailure) + c.options.DeadLetter = (&DeadLetterConfig{Topic: "cards.failed"}).normalized(nil) + source := &kgo.Record{Topic: "cards", Offset: 5, Key: []byte("id"), Value: []byte("raw body"), Headers: []kgo.RecordHeader{{Key: "trace", Value: []byte("trace-id")}}} + err := c.processFetches(context.Background(), fetchRecords(source), func(context.Context, *kgo.Record) error { return errors.New("invalid card") }) + require.Len(t, io.published, 1) + require.Equal(t, "cards.failed", io.published[0].Topic) + require.Equal(t, source.Value, io.published[0].Value) + require.Equal(t, source.Key, io.published[0].Key) + require.Contains(t, io.published[0].Headers, source.Headers[0]) + if publishErr == nil { + require.NoError(t, err) + require.Equal(t, []*kgo.Record{source}, io.committed) + } else { + require.ErrorIs(t, err, ErrDLQPublish) + require.ErrorIs(t, err, publishErr) + require.Empty(t, io.committed) + } + } +} + +func TestCommitFailurePreservesProcessingCause(t *testing.T) { + commitErr, handlerErr := errors.New("commit unavailable"), errors.New("handler failed") + io := &recordingIO{commitErr: commitErr} + c := newTestConsumer(io) + c.policy = quickPolicy(DependencyUnavailable) + err := c.processFetches(context.Background(), fetchRecords(&kgo.Record{Offset: 1}, &kgo.Record{Offset: 2}), func(_ context.Context, r *kgo.Record) error { + if r.Offset == 2 { + return handlerErr + } + return nil + }) + require.ErrorIs(t, err, handlerErr) + require.ErrorIs(t, err, commitErr) +} + +func TestDeadLetterConfigValidationAndCopy(t *testing.T) { + original := &DeadLetterConfig{Configs: map[string]string{"retention.ms": "86400000"}} + d := original.normalized([]string{"orders"}) + require.Equal(t, "orders.dlq", d.Topic) + require.NoError(t, d.validate([]string{"orders"})) + d.Configs["retention.ms"] = "1000" + require.Equal(t, "86400000", original.Configs["retention.ms"]) + d.Topic = "orders" + require.Error(t, d.validate([]string{"orders"})) + d.Topic = "failed" + d.Provision = Declare + require.Error(t, d.validate(nil)) + d.Partitions = 3 + d.ReplicationFactor = 3 + require.NoError(t, d.validate(nil)) + require.Error(t, NewConsumer(nil, ConsumerOptions{RetryPolicy: &RetryPolicy{OnExhausted: DeadLetter}}).Start(context.Background(), nil)) +} diff --git a/kafka/failure.go b/kafka/failure.go new file mode 100644 index 0000000..16cf367 --- /dev/null +++ b/kafka/failure.go @@ -0,0 +1,228 @@ +package kafka + +import ( + "context" + "errors" + "fmt" + "math/rand/v2" + "time" +) + +// FailureKind describes an application processing failure, not a broker failure. +type FailureKind uint8 + +const ( + UnknownFailure FailureKind = iota + RetryableFailure + PermanentFailure + DependencyUnavailable + ConfigurationFailure +) + +func (k FailureKind) String() string { + switch k { + case RetryableFailure: + return "retryable" + case PermanentFailure: + return "permanent" + case DependencyUnavailable: + return "dependency_unavailable" + case ConfigurationFailure: + return "configuration" + default: + return "unknown" + } +} + +// ExhaustedAction applies to explicitly retryable failures only. Unknown +// failures always stop consumption; a DLQ is never a reason to discard them. +type ExhaustedAction uint8 + +const ( + StopConsumer ExhaustedAction = iota + DeadLetter +) + +// RetryPolicy is optional. A nil policy allows three retries, with jittered +// exponential backoff and a ten-second total budget, then stops consumption. +// A non-nil policy's MaxRetries is literal: zero disables retries. +// Handlers and classifier callbacks must respect context deadlines / not block. +type RetryPolicy struct { + Classify func(error) FailureKind + MaxRetries int + InitialBackoff time.Duration + MaxBackoff time.Duration + MaxElapsedTime time.Duration + OnExhausted ExhaustedAction +} + +var ErrConsumerPaused = errors.New("consumer paused; message preserved") + +// ProcessingError preserves the cause and describes why consumption stopped. +// Restart with backoff or RunWithRecovery; never restart in an immediate loop. +type ProcessingError struct { + Kind FailureKind + Attempts int + Err error +} + +func (e *ProcessingError) Error() string { + return fmt.Sprintf("%s: %s after %d attempts: %v", ErrConsumerPaused, e.Kind, e.Attempts, e.Err) +} +func (e *ProcessingError) Unwrap() error { return e.Err } +func (e *ProcessingError) Is(target error) bool { return target == ErrConsumerPaused } + +func (p *RetryPolicy) normalized() RetryPolicy { + var out RetryPolicy + if p == nil { + out.MaxRetries = 3 + } else { + out = *p + } + if out.InitialBackoff == 0 { + out.InitialBackoff = 100 * time.Millisecond + } + if out.MaxBackoff == 0 { + out.MaxBackoff = 5 * time.Second + } + if out.MaxElapsedTime == 0 { + out.MaxElapsedTime = 10 * time.Second + } + return out +} + +func (p RetryPolicy) validate(hasDLQ bool) error { + if p.MaxRetries < 0 || p.InitialBackoff < 0 || p.MaxBackoff < p.InitialBackoff || p.MaxElapsedTime <= 0 { + return errors.New("invalid retry limits or time budget") + } + if p.OnExhausted > DeadLetter { + return errors.New("invalid exhausted action") + } + if p.OnExhausted == DeadLetter && !hasDLQ { + return errors.New("dead-letter exhaustion requires DeadLetterConfig") + } + return nil +} + +type processingResult struct { + err error + kind FailureKind + attempts int + park bool +} + +func (r processingResult) paused() error { + return &ProcessingError{Kind: r.kind, Attempts: r.attempts, Err: r.err} +} + +// process retries in place. It never publishes a replacement or settles input. +func (p RetryPolicy) process(ctx context.Context, handler func(context.Context) error) processingResult { + budget, cancel := context.WithTimeout(ctx, p.MaxElapsedTime) + defer cancel() + var result processingResult + delay := min(p.InitialBackoff, p.MaxBackoff) + for { + if err := budget.Err(); err != nil { + result.err = errors.Join(result.err, err) + result.park = ctx.Err() == nil && result.kind == RetryableFailure && p.OnExhausted == DeadLetter + return result + } + result.attempts++ + result.err = handler(budget) + if err := ctx.Err(); err != nil { + result.err = err + result.park = false + return result + } + if result.err == nil { + return result + } + result.kind = UnknownFailure + if p.Classify != nil { + result.kind = p.Classify(result.err) + } + if result.kind > ConfigurationFailure { + result.kind = UnknownFailure + } + switch result.kind { + case PermanentFailure: + result.park = true + return result + case DependencyUnavailable, ConfigurationFailure: + return result + } + if result.attempts > p.MaxRetries || budget.Err() != nil { + result.park = result.kind == RetryableFailure && p.OnExhausted == DeadLetter + return result + } + if err := waitDelay(budget, time.Duration(float64(delay)*(0.5+rand.Float64()*0.5))); err != nil { + result.err = errors.Join(result.err, err) + result.park = ctx.Err() == nil && result.kind == RetryableFailure && p.OnExhausted == DeadLetter + return result + } + if delay >= p.MaxBackoff/2 { + delay = p.MaxBackoff + } else { + delay *= 2 + } + } +} + +func waitDelay(ctx context.Context, delay time.Duration) error { + if err := ctx.Err(); err != nil { + return err + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return ctx.Err() + } +} + +// RecoveryPolicy gates restarts after DependencyUnavailable. Probe must honor +// ctx. No messages are fetched while probing. Defaults: 30s interval, 5s timeout. +type RecoveryPolicy struct { + Probe func(context.Context) error + Interval time.Duration + Timeout time.Duration +} + +// RunWithRecovery runs consume, probing only after a classified dependency +// outage. consume must release its resources on return and create a fresh +// consumer/client on each invocation. Other failures return for operator action. +// ctx bounds the whole recovery loop; cancellation never starts another consumer. +func RunWithRecovery(ctx context.Context, recovery RecoveryPolicy, consume func(context.Context) error) error { + if recovery.Interval == 0 { + recovery.Interval = 30 * time.Second + } + if recovery.Timeout == 0 { + recovery.Timeout = 5 * time.Second + } + if recovery.Interval < 0 || recovery.Timeout < 0 || consume == nil { + return errors.New("invalid recovery policy") + } + for { + if err := ctx.Err(); err != nil { + return err + } + err := consume(ctx) + paused, ok := errors.AsType[*ProcessingError](err) + if !ok || paused.Kind != DependencyUnavailable || recovery.Probe == nil { + return err + } + for { + if err := waitDelay(ctx, recovery.Interval); err != nil { + return err + } + probeCtx, cancel := context.WithTimeout(ctx, recovery.Timeout) + probeErr := errors.Join(recovery.Probe(probeCtx), probeCtx.Err()) + cancel() + if probeErr == nil { + break + } + } + } +} diff --git a/kafka/failure_test.go b/kafka/failure_test.go new file mode 100644 index 0000000..efe6157 --- /dev/null +++ b/kafka/failure_test.go @@ -0,0 +1,157 @@ +package kafka + +import ( + "context" + "errors" + "testing" + "time" +) + +func quickPolicy(kind FailureKind) RetryPolicy { + return RetryPolicy{Classify: func(error) FailureKind { return kind }, MaxRetries: 2, + InitialBackoff: time.Millisecond, MaxBackoff: 2 * time.Millisecond, MaxElapsedTime: time.Second} +} + +func TestFailureClassificationControlsRetries(t *testing.T) { + boom := errors.New("application failure") + for _, tc := range []struct { + kind FailureKind + attempts int + park bool + }{ + {UnknownFailure, 3, false}, {RetryableFailure, 3, true}, + {PermanentFailure, 1, true}, {DependencyUnavailable, 1, false}, {ConfigurationFailure, 1, false}, + } { + t.Run(tc.kind.String(), func(t *testing.T) { + p := quickPolicy(tc.kind) + p.OnExhausted = DeadLetter + calls := 0 + got := p.process(context.Background(), func(context.Context) error { calls++; return boom }) + if calls != tc.attempts || got.attempts != calls || got.park != tc.park || !errors.Is(got.paused(), boom) || !errors.Is(got.paused(), ErrConsumerPaused) { + t.Fatalf("calls=%d result=%+v", calls, got) + } + }) + } +} + +func TestRetryBudgetAndCancellation(t *testing.T) { + boom := errors.New("temporary failure") + p := quickPolicy(RetryableFailure) + p.MaxRetries = 1000 + p.MaxElapsedTime = 15 * time.Millisecond + p.InitialBackoff, p.MaxBackoff = time.Second, time.Second + start := time.Now() + got := p.process(context.Background(), func(context.Context) error { return boom }) + if got.attempts != 1 || !errors.Is(got.err, boom) || !errors.Is(got.err, context.DeadlineExceeded) || time.Since(start) > time.Second { + t.Fatalf("time budget did not stop retry wait: %+v", got) + } + ctx, cancel := context.WithCancel(context.Background()) + got = p.process(ctx, func(context.Context) error { cancel(); return boom }) + if !errors.Is(got.err, context.Canceled) || got.park { + t.Fatalf("cancelled input must remain unsettled: %+v", got) + } + called := false + got = p.process(ctx, func(context.Context) error { called = true; return nil }) + if called || !errors.Is(got.err, context.Canceled) { + t.Fatal("cancelled context invoked handler") + } +} + +func TestRetrySuccessAndExplicitZero(t *testing.T) { + p := quickPolicy(RetryableFailure) + calls := 0 + got := p.process(context.Background(), func(context.Context) error { + calls++ + if calls < 3 { + return errors.New("not yet") + } + return nil + }) + if got.err != nil || calls != 3 { + t.Fatalf("result=%+v calls=%d", got, calls) + } + p.MaxRetries = 0 + got = p.process(context.Background(), func(context.Context) error { return errors.New("failure") }) + if got.attempts != 1 { + t.Fatalf("zero means no retries: %+v", got) + } + var defaults *RetryPolicy + if defaults.normalized().MaxRetries != 3 { + t.Fatal("nil policy lost default retry budget") + } +} + +func TestFailurePolicyValidation(t *testing.T) { + p := quickPolicy(RetryableFailure) + p.OnExhausted = DeadLetter + if p.validate(false) == nil || p.validate(true) != nil { + t.Fatal("parking requires configured destination") + } + p.MaxRetries = -1 + if p.validate(true) == nil { + t.Fatal("negative retry budget accepted") + } +} + +func TestRecoveryProbesDoNotConsumeDuringOutage(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + runs, probes := 0, 0 + err := RunWithRecovery(ctx, RecoveryPolicy{ + Interval: time.Millisecond, Timeout: time.Second, + Probe: func(context.Context) error { + probes++ + if probes < 4 { + return errors.New("still down") + } + return nil + }, + }, func(context.Context) error { + runs++ + if runs == 1 { + return &ProcessingError{Kind: DependencyUnavailable, Attempts: 1, Err: errors.New("service down")} + } + if probes != 4 { + t.Fatal("consumed before successful recovery probe") + } + return nil + }) + if err != nil || runs != 2 || probes != 4 { + t.Fatalf("err=%v runs=%d probes=%d", err, runs, probes) + } +} + +func TestRecoveryDoesNotRestartUnknownFailures(t *testing.T) { + probes, runs := 0, 0 + err := RunWithRecovery(context.Background(), RecoveryPolicy{Probe: func(context.Context) error { probes++; return nil }}, func(context.Context) error { + runs++ + return &ProcessingError{Kind: UnknownFailure, Attempts: 1, Err: errors.New("unknown")} + }) + if !errors.Is(err, ErrConsumerPaused) || probes != 0 || runs != 1 { + t.Fatalf("err=%v probes=%d runs=%d", err, probes, runs) + } +} + +func TestRecoveryCancellationStopsProbesAndRestarts(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + runs := 0 + err := RunWithRecovery(ctx, RecoveryPolicy{Interval: time.Millisecond, Probe: func(ctx context.Context) error { cancel(); return ctx.Err() }}, func(context.Context) error { + runs++ + return &ProcessingError{Kind: DependencyUnavailable, Err: errors.New("down")} + }) + if !errors.Is(err, context.Canceled) || runs != 1 { + t.Fatalf("err=%v runs=%d", err, runs) + } +} + +func TestElapsedBudgetUsesExplicitExhaustionPolicy(t *testing.T) { + p := quickPolicy(RetryableFailure) + p.MaxRetries = 100 + p.MaxElapsedTime = 10 * time.Millisecond + p.InitialBackoff, p.MaxBackoff = time.Second, time.Second + p.OnExhausted = DeadLetter + result := p.process(context.Background(), func(context.Context) error { return errors.New("temporary") }) + if !result.park || result.kind != RetryableFailure { + t.Fatalf("elapsed budget ignored explicit exhaustion policy: %+v", result) + } +} diff --git a/kafka/integration_test.go b/kafka/integration_test.go new file mode 100644 index 0000000..084f76e --- /dev/null +++ b/kafka/integration_test.go @@ -0,0 +1,81 @@ +package kafka + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kgo" +) + +// Optional broker test; no Docker is required. This creates/deletes a unique +// topic on the disposable cluster named by FIDDLE_KAFKA_BROKERS. +func TestIntegrationRestartRedeliversFailedRecord(t *testing.T) { + brokers := os.Getenv("FIDDLE_KAFKA_BROKERS") + if brokers == "" { + t.Skip("set FIDDLE_KAFKA_BROKERS for broker verification") + } + topic := fmt.Sprintf("fiddle-test-%d", time.Now().UnixNano()) + group := topic + "-group" + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + producer, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...), kgo.RequiredAcks(kgo.AllISRAcks())) + if err != nil { + t.Fatal(err) + } + defer producer.Close() + admin := kadm.NewClient(producer) + created, err := admin.CreateTopics(ctx, 1, 1, nil, topic) + if err != nil { + t.Fatal(err) + } + if result, ok := created[topic]; !ok || result.Err != nil { + t.Fatalf("create topic: %+v", created) + } + defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, _ = admin.DeleteTopics(cleanup, topic) + }() + for _, value := range []string{"ok", "failed", "later"} { + if err = producer.ProduceSync(ctx, &kgo.Record{Topic: topic, Value: []byte(value)}).FirstErr(); err != nil { + t.Fatal(err) + } + } + newClient := func() *kgo.Client { + client, err := kgo.NewClient(kgo.SeedBrokers(strings.Split(brokers, ",")...), kgo.ConsumerGroup(group), kgo.ConsumeTopics(topic), + kgo.DisableAutoCommit(), kgo.BlockRebalanceOnPoll(), kgo.ConsumeResetOffset(kgo.NewOffset().AtStart())) + if err != nil { + t.Fatal(err) + } + return client + } + client := newClient() + var seen []string + err = NewConsumer(client, ConsumerOptions{RetryPolicy: &RetryPolicy{Classify: func(error) FailureKind { return DependencyUnavailable }}}).Start(ctx, func(_ context.Context, r *kgo.Record) error { + seen = append(seen, string(r.Value)) + if string(r.Value) == "failed" { + return errors.New("service down") + } + return nil + }) + client.Close() + if !errors.Is(err, ErrConsumerPaused) || len(seen) != 2 { + t.Fatalf("err=%v processed=%v", err, seen) + } + client = newClient() + defer client.Close() + var redelivered string + err = NewConsumer(client, ConsumerOptions{RetryPolicy: &RetryPolicy{}}).Start(ctx, func(_ context.Context, r *kgo.Record) error { + redelivered = string(r.Value) + return errors.New("stop after observing first record") + }) + if !errors.Is(err, ErrConsumerPaused) || redelivered != "failed" { + t.Fatalf("err=%v first_redelivered=%q", err, redelivered) + } +} diff --git a/kafka/producer.go b/kafka/producer.go index e166bdc..d36ca38 100644 --- a/kafka/producer.go +++ b/kafka/producer.go @@ -176,6 +176,9 @@ func (p *producer) SendMessage(ctx context.Context, topic string, payload any) e // SendToDLQ publishes a record to originalTopic+".dlq" and waits for the broker // to acknowledge it. func (p *producer) SendToDLQ(ctx context.Context, originalTopic string, value []byte, key []byte, dlqErr error) error { + if p.client == nil || p.client.OptValue(kgo.RequiredAcks) != kgo.AllISRAcks() { + return errors.New("dead-letter publishing requires a client with AllISRAcks") + } errMsg := "unknown error" if dlqErr != nil { diff --git a/rabbitmq/README.md b/rabbitmq/README.md index 26aa9a8..9164912 100644 --- a/rabbitmq/README.md +++ b/rabbitmq/README.md @@ -1,509 +1,168 @@ -# rabbitmq - -Go SDK for RabbitMQ with auto-reconnection, channel pooling, OTel tracing, and dead-letter support. - -## Topology - -``` -┌─────────────────────────────────────────────────────┐ -│ rabbitmq package │ -│ │ -│ ┌─────────────────────────────────────────────────┐ │ -│ │ Connection Layer │ │ -│ │ ┌──────────┐ ┌───────────┐ ┌────────────────┐ │ │ -│ │ │ Client │ │channelPool│ │ TopologyCache │ │ │ -│ │ │dual AMQP │ │N pub chan │ │ queues,exchs, │ │ │ -│ │ │conns + │ │get/return │ │ bindings saved │ │ │ -│ │ │state mach│ │drain/close│ │ for reconnect │ │ │ -│ │ └────┬─────┘ └─────┬─────┘ └───────┬────────┘ │ │ -│ └───────┼─────────────┼───────────────┼───────────┘ │ -│ │ │ │ │ -│ ┌───────┴─────────────┴───────────────┴───────────┐ │ -│ │ Messaging Layer │ │ -│ │ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │ -│ │ │ Producer │ │ Consumer │ │ BatchConsumer │ │ │ -│ │ │ publish │ │ manual/ │ │ accumulate → │ │ │ -│ │ │ batch, │ │ auto ack │ │ flush on size/ │ │ │ -│ │ │ confirms │ │ retry/DLX│ │ timeout, batch │ │ │ -│ │ │ OTel inj │ │ OTel ext │ │ ack/nack │ │ │ -│ │ └────┬─────┘ └────┬────┘ └────────┬─────────┘ │ │ -│ └───────┼──────────────┼──────────────┼───────────┘ │ -│ │ │ │ │ -│ ┌───────┴──────────────┴──────────────┴───────────┐ │ -│ │ TopologyManager (implements TopologyDeclarer) │ │ -│ │ QueueDeclare → ExchangeDeclare → BindQueue │ │ -│ │ SetupDeadLetterExchange() │ │ -│ │ Re-declares all cached topology on reconnect │ │ -│ └──────────────────────┬──────────────────────────┘ │ -│ │ │ -│ ┌──────────────────────┴──────────────────────────┐ │ -│ │ Config: URL, conn, producer, consumer, retry, │ │ -│ │ reconnect settings, DLX flags │ │ -│ └─────────────────────────────────────────────────┘ │ -└─────────────────────────────────────────────────────┘ - - │ Dial / Channel - ▼ -┌───────────────────────┐ -│ amqp091-go (AMQP) │ -└───────────┬───────────┘ - │ AMQP 0-9-1 - ▼ -┌───────────────────────┐ -│ RabbitMQ Broker │ -└───────────────────────┘ -``` - -### Dead-Letter Exchange - -``` -main queue ──x-dead-letter-exchange──→ DLX (topic exchange) - │ │ - Reject(false) routing key: orders - (RetryEnabled) │ - orders.retry queue - (TTL: 30s, dead-letters back to main) - -after MaxRetries the consumer publishes a copy straight to the -orders.parking-lot queue and acks the original (no DLX involved) -``` - -### channelPool - -RMQ conns have ~finite channel count. New channel per publish → exhaust. Pool recycles N fixed channels. - -### Publisher Confirm - -RMQ sends ACK/NACK back after broker handles msg. Without confirm: `Publish` returns success as soon as TCP buffer accepts bytes. Msg could be lost before broker routes it (exchange missing, queue full, disk write fail). Set `PublisherConfirms: true` in config. -## Connection State Machine - -```mermaid -stateDiagram-v2 - [*] --> Disconnected : NewClient - Disconnected --> Connecting : connect() - Connecting --> Connected : both conns + pool ready - Connected --> Connecting : connection lost - Connecting --> Connecting : retry (backoff) - Connected --> Closing : Close() - Connecting --> Closing : Close() - Disconnected --> Closing : Close() - Closing --> [*] -``` - -## Reconnect Flow - -```mermaid -sequenceDiagram - participant App - participant Client - participant Pool - participant Cache - participant Broker as RabbitMQ - - Broker--)Client: connection close detected - Client->>Pool: drain() - Client->>Client: CAS Connected → Connecting - loop backoff 1s → 2s → ... → 60s - Client->>Broker: dial publisher conn - Client->>Broker: dial consumer conn - alt success - Client->>Pool: fill(pubConn) - Client->>Cache: snapshot + reset - Client->>Cache: re-declare queues - Client->>Cache: re-declare exchanges - Client->>Cache: re-declare bindings - Client->>Client: state = Connected - else failure - Client->>Client: backoff *= 2 - end - end -``` - -On every reconnect the cached topology is re-declared **before** the client reports healthy, so consumers waiting on `IsHealthy` find their queues. A declaration the broker rejects (for example `PRECONDITION_FAILED` because the queue exists with different arguments) is logged and skipped, and the other entries are still restored; it is tried again on the next reconnect. A lost connection fails the attempt, which is retried with backoff. - -## Dead-Letter Exchange Topology - -```mermaid -graph LR - subgraph Main - MainQ["orders
main queue"] - end - - subgraph DLX["orders.dlx
topic exchange"] - end - - subgraph Retry["Retry"] - RetryQ["orders.retry
TTL: 30s
DLX → orders
"] - end - - subgraph DLQ["Dead Letter"] - ParkingQ["orders.parking-lot
failed messages"] - end - - MainQ -- "x-dead-letter-exchange" --> DLX - MainQ -- "Reject(false)
(RetryEnabled)" --> DLX - RetryQ -- "TTL expires" --> MainQ - DLX -- "routing key: orders" --> RetryQ - MainQ -. "after MaxRetries:
copy published, original acked" .-> ParkingQ - - style MainQ fill:#e8f5e9,stroke:#2e7d32 - style DLX fill:#fff3e0,stroke:#ef6c00 - style RetryQ fill:#e3f2fd,stroke:#1976d2 - style ParkingQ fill:#fce4ec,stroke:#c62828 -``` - -## Message Lifecycle - -```mermaid -sequenceDiagram - participant P as Producer - participant B as Broker - participant Q as Queue - participant C as Consumer - participant DLX as DLX - participant D as ParkingLot - - P->>B: PublishMessage("orders", payload) - B->>Q: route - Q->>C: deliver - C->>C: handler(ctx, delivery) - alt success - C->>Q: Ack - else handler error, retries < MaxRetries, RetryEnabled - C->>Q: Reject(false) - Q->>DLX: route via x-dead-letter-exchange - Note over DLX: retry queue, back to Q after the retry queue TTL
x-death count incremented - else handler error, retries < MaxRetries, not RetryEnabled - C->>Q: republish copy, x-retry-count + 1 - C->>Q: Ack original - else handler error, retries >= MaxRetries (or ErrPoisonMessage) - alt DeadLetterEnabled - C->>D: publish copy to orders.parking-lot - C->>Q: Ack original - else - C->>Q: Reject(false) - end - end -``` - -## Batch Consumer Flow - -```mermaid -sequenceDiagram - participant Q as Queue - participant BC as BatchConsumer - participant H as BatchHandler - - BC->>Q: Consume (QoS prefetch, autoAck=false) - loop accumulating - Q-->>BC: delivery - opt WithBatchValidator set - BC->>BC: validate(delivery) - Note over BC: invalid: settled on its own
(parking lot / reject), not batched - end - BC->>BC: append to batch[] - alt batchSize reached - BC->>BC: flush() - else flushTimeout elapsed - BC->>BC: flush() - end - end - BC->>H: handler(ctx, deliveries) - alt success - H-->>BC: nil - BC->>Q: multiple Ack on the last delivery - else failure - H-->>BC: error - BC->>Q: retry policy applied per delivery - end - Q-->>BC: ctx cancelled - BC->>BC: flush() remaining - BC->>Q: close channel -``` - -## Public API - -### Interfaces - -| Interface | Purpose | Constructor | -|-----------|---------|-------------| -| `Publisher` | Send messages | `NewProducer(client *Client) Publisher` | -| `Subscriber` | Consume messages | `NewConsumer(client *Client, logger *slog.Logger) Subscriber` | -| `TopologyDeclarer` | Declare topology | `NewTopologyManager(client *Client) TopologyDeclarer` | - -### Concrete types - -| Type | Constructor | Notes | -|------|-------------|-------| -| `*Client` | `NewClient(config *Config, logger *slog.Logger) (*Client, error)` | Two AMQP conns (pub + con), channel pool, topology cache | -| `*BatchConsumer` | `NewBatchConsumer(client *Client, logger *slog.Logger, batchSize int, flushTimeout time.Duration, opts ...BatchOption) *BatchConsumer` | Owns its own channel; not part of `Subscriber` interface | -| `*Config` | `NewDefaultConfig() *Config` | Pre-populated defaults; caller must set `URL`. `NewClient` fills the other unset fields (`ApplyDefaults`) and checks the result (`Validate`) on a copy | - -### Handlers - -| Type | Signature | Notes | -|------|-----------|-------| -| `MessageHandler` | `func(ctx, delivery amqp.Delivery) error` | Raw payload in `delivery.Body`; any content type | -| `JSONHandler[T]` | `JSONHandler(func(ctx, msg T, delivery) error) MessageHandler` | Decodes the body into `T`; an undecodable body is a poison message | -| `BatchHandler` | `func(ctx, deliveries []amqp.Delivery) error` | Raw payloads | -| `JSONBatchHandler[T]` | `JSONBatchHandler(func(ctx, msgs []T, deliveries) error) BatchHandler` | `msgs[i]` belongs to `deliveries[i]` | -| `ValidJSON` | `func(amqp.Delivery) error` | For `WithBatchValidator`: keeps non-JSON bodies out of batches | - -### Errors - -| Sentinel | Meaning | -|----------|---------| -| `ErrNotConnected` | `rabbitmq: client not connected` | -| `ErrURLRequired` | `rabbitmq: URL is required` | -| `ErrPoisonMessage` | Wrap it in a handler error to skip the retries: the message is parked (`DeadLetterEnabled`) or rejected at once. `JSONHandler` does so for undecodable bodies | - -### Health & State - -| Method | Returns | -|--------|---------| -| `client.IsHealthy() bool` | `true` when `StateConnected` | -| `client.GetState() ConnectionState` | `StateDisconnected` / `StateConnecting` / `StateConnected` / `StateClosing` | - ---- - -## Usage - -### Basic +# RabbitMQ + +This module provides publishing, topology management, single-message and batch +consumers. Consumers use application classification, bounded in-place retries, +and confirmed transfers to preserve failed deliveries. + +## Failure policy + +Set `ConsumeOptions.RetryPolicy` once per subscription. Without it, legacy +`Config.MaxRetries` and positive `RetryBackoff` provide count/delay defaults; +`NewClient` fills defaults of three retries and a one-second initial backoff. +The total handler/retry budget defaults to ten seconds. An explicit policy uses +`MaxRetries: 0` as no retries. Handlers must honor the supplied context. + +| Classification | Behavior | +| --- | --- | +| `UnknownFailure` (default) | Bounded retries, then stop and preserve; never automatically park | +| `RetryableFailure` | Bounded retries, then stop; optionally park with `OnExhausted: DeadLetter` | +| `PermanentFailure` | Skip retries; park if configured, otherwise stop and preserve | +| `DependencyUnavailable` | Stop immediately; recovery probes can gate restart | +| `ConfigurationFailure` | Stop immediately for operator intervention | + +The caller supplies an optional `Classify func(error) FailureKind` using typed +errors or `errors.Is`. The SDK recognizes errors wrapping `ErrPoisonMessage` as +permanent. `JSONHandler` produces this error for malformed payloads; raw handlers +can accept any format. Cancellation leaves unfinished messages unacknowledged. +`ProcessingError` exposes the failure kind, attempt count and original wrapped +cause, and matches `ErrConsumerPaused`. Budgets apply to each consumer invocation; +supervisors must not restart unknown/configuration failures in tight loops. + +Retries call the handler again on the same delivery. They do not republish it, +reject it into a retry queue, or repeatedly nack/requeue it. Any unhandled failure +returns from the consume loop and closes its channel so the broker can redeliver +unfinished messages. Manual acknowledgements are required. `AutoReconnect` +recovers transport disconnections; it does not restart failed processing. + +## Configure the dead-letter destination + +A nil `ConsumeOptions.DeadLetter` disables parking. To create a configured queue +and optional direct exchange/binding before consuming: ```go -logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) - -client, err := rabbitmq.NewClient(&rabbitmq.Config{ - URL: "amqp://guest:guest@localhost:5672/", - ConnectionName: "my-service", - PublisherConfirms: true, - QueueType: rabbitmq.QueueTypeQuorum, - RetryEnabled: true, - MaxRetries: 3, - DeadLetterEnabled: true, -}, logger) -if err != nil { - log.Fatal(err) +options := rabbitmq.ConsumeOptions{ + QueueName: "cards", + RetryPolicy: &rabbitmq.RetryPolicy{ + Classify: classifyApplicationError, + MaxRetries: 3, + OnExhausted: rabbitmq.DeadLetter, + }, + DeadLetter: &rabbitmq.DeadLetterConfig{ + Provision: rabbitmq.Declare, + Queue: rabbitmq.QueueConfig{ + Name: "cards.failed", + Durable: true, + Args: map[string]any{ + "x-max-length-bytes": int64(1 << 30), + "x-overflow": "reject-publish", + // Optional retention: "x-message-ttl": int64(604800000), + }, + }, + QueueType: rabbitmq.QueueTypeQuorum, + Exchange: &rabbitmq.ExchangeConfig{ + Name: "failed.events", Kind: "direct", Durable: true, + }, + RoutingKey: "cards.failed", + Timeout: 10 * time.Second, + }, } -defer client.Close() ``` -### Declare topology +`UseExisting` first checks that configured objects exist. Both modes perform +idempotent declarations to verify argument equivalence and ensure the binding; +this requires declaration/binding permissions even for existing topology. +Existing incompatible definitions fail before subscription starts. Configured +queues must be durable, non-exclusive and not auto-delete. An empty configured +queue defaults to durable `.parking-lot`; its type defaults to quorum. +An omitted exchange uses the default exchange and the destination queue name as +routing key. `OnExhausted: DeadLetter` requires a destination at startup and only +applies to explicitly retryable failures. + +Retention and overflow are operational choices. Unspecified queue arguments use +broker defaults. Capacity limits require an explicit `x-overflow` of +`reject-publish` or `drop-head`; the latter deletes older parked messages. TTL +expires parked messages. Parking queues cannot configure an automatic DLX loop. + +## Transfer guarantees and resource limits + +Internal dead-letter writes always use publisher confirms, persistent delivery +and `mandatory=true`, regardless of normal publisher settings. A broker return, +nack, closed connection, or timeout prevents acknowledgement of the original. +Broker acknowledgements cannot mask preceding unroutable returns. Consumption +stops on transfer failure so it cannot create a requeue storm. + +Each internal transfer uses an isolated connection/channel, with one publication +in flight. This makes return/confirm correlation unambiguous and allows a timeout +to close its socket even during a blocked publish. `ChannelPoolSize` bounds the +number of transfer connections per client, and `TransferTimeout` bounds each +operation (default ten seconds). This trades connection setup overhead on failure +paths for bounded I/O and isolation from asynchronous public publishing. + +Original body and message properties are retained. Source TTL is recorded in +metadata and cleared on the parked copy; the DLQ's retention governs that copy. +Broker delivery-count headers are recorded and removed from the parked copy. +Reserved `fiddle.dlq.*` headers include the source queue/exchange/routing key, +message ID, classification, attempt count and failure time. Error text is omitted +unless `ErrorFormatter` is provided; return only sanitized details. + +An exchange-based destination guarantees routing to at least one bound queue; +use the default exchange when the guarantee must refer to the exact named queue. +Delivery is at least once: a crash between transfer and original acknowledgement +can produce duplicates. Broker retention, overflow, and delivery limits still +apply. Redrive is explicit and should be idempotent. + +Batch consumers use the same policy. A handler retry applies to the whole batch; +`WithBatchValidator(ValidJSON)` can keep malformed JSON out of batches. Every +message is settled individually so a later acknowledgement cannot include a +failed earlier validator or transfer. Shutdown preserves pending input for +redelivery rather than running new handler work with a detached context. + +## Recovery and observing the cause ```go -tm := rabbitmq.NewTopologyManager(client) - -// Simple queue -tm.DeclareQueue(rabbitmq.QueueConfig{Name: "orders", Durable: true}) - -// Exchange + binding -tm.DeclareExchange(rabbitmq.ExchangeConfig{Name: "events", Kind: "topic", Durable: true}) -tm.BindQueue(rabbitmq.BindingConfig{ - QueueName: "orders", - Exchange: "events", - RoutingKey: "order.*", -}) - -// Full DLX setup (creates orders.dlx exchange, orders.retry queue, orders.parking-lot queue) -tm.SetupDeadLetterExchange("orders", "orders.dlx", 30000) - -// Queue with DLX pre-wired -tm.SetupQueueWithDLX("orders", "orders.dlx") -``` - -### Publish - -```go -producer := rabbitmq.NewProducer(client) - -// Simple publish to default exchange (routing key = queue name) -producer.SendMessage(ctx, "orders", orderPayload) - -// Publish with custom headers -producer.SendMessageWithHeaders(ctx, "orders", payload, map[string]interface{}{ - "x-custom-header": "value", +err := rabbitmq.RunWithRecovery(ctx, rabbitmq.RecoveryPolicy{ + Probe: checkCardServiceHealth, + Interval: 30 * time.Second, + Timeout: 5 * time.Second, +}, func(ctx context.Context) error { + client, err := rabbitmq.NewClient(cfg, logger) + if err != nil { return err } + defer client.Close() + err = rabbitmq.NewConsumer(client, logger).StartConsumer(ctx, options, handleCard) + // Record err here to observe the original cause while recovery probes run. + return err }) - -// Publish to named exchange -producer.SendToTopic(ctx, "events", "order.created", eventPayload) -producer.SendToTopicWithHeaders(ctx, "events", "order.created", payload, headers) - -// Full control -producer.PublishMessage(ctx, rabbitmq.PublishOptions{ - Exchange: "events", - RoutingKey: "order.updated", - DeliveryMode: 2, // persistent - MessageId: "msg-123", - Headers: map[string]interface{}{"region": "eu"}, -}, payload) - -// Batch publish (fails fast on first error) -producer.PublishBatch(ctx, rabbitmq.PublishOptions{ - Exchange: "", - RoutingKey: "orders", -}, []interface{}{payload1, payload2, payload3}) ``` -### Consume - -```go -consumer := rabbitmq.NewConsumer(client, logger) - -// Typed JSON: the body is decoded into Order. A body that does not decode is a -// poison message and is parked without retries. -handler := rabbitmq.JSONHandler(func(ctx context.Context, order Order, delivery amqp.Delivery) error { - // Process order - // Return nil → Ack - // Return error → retry policy (see below) - return nil -}) - -// Raw bytes: any content type, nothing is decoded for you. -raw := func(ctx context.Context, delivery amqp.Delivery) error { - return process(delivery.ContentType, delivery.Body) -} - -// Minimal (sensible defaults: manual ack, no auto-reconnect) -consumer.ConsumeWithDefaults(ctx, "orders", handler) - -// Full control -consumer.StartConsumer(ctx, rabbitmq.ConsumeOptions{ - QueueName: "orders", - Consumer: "worker-1", - AutoReconnect: true, // restart on delivery channel close -}, handler) +Only `DependencyUnavailable` triggers probes. The callback releases its consumer +before probing and creates a fresh one after a successful, timely health check. +No messages are consumed during the outage. Unknown/configuration, setup, and +transfer errors return for intervention. The outer context bounds recovery. +Probes must honor context cancellation and check the application dependency. + +Normal publishing remains available through `NewProducer`, with public publisher +confirms and persistence controlled by `Config`. `NewTopologyManager` declares +queues, exchanges and bindings and caches topology for transport reconnection. + +## Migration and tests + +- Exhausted failures with parking disabled are preserved; they are no longer + rejected and potentially discarded. +- `Config.RetryEnabled: true` is rejected. Replace broker retry loops with a + subscription `RetryPolicy`; generic topology helpers remain available. +- `Config.DeadLetterEnabled` selects the conventional existing parking queue for + compatibility. Prefer explicit per-subscription configuration. It does not + automatically make unknown errors safe to dead-letter. +- `AutoAck` is rejected by reliable consumers. + +Run `make check` in this module with Go 1.27.2 and the configured lint tools. +Unit tests cover policy budgets, outage recovery gating, settlement ordering, +batch preservation, and unroutable/ack races. An optional real broker test deletes +a parking queue after startup verification and checks original redelivery: + +```sh +FIDDLE_RABBITMQ_URL=amqp://guest:guest@localhost:5672/ go test -run TestIntegration -count=1 -timeout 60s ``` -A handler error is settled by the retry policy: - -| Situation | What happens | -|-----------|--------------| -| `RetryEnabled`, attempts < `MaxRetries` | `Reject(false)`; the queue's DLX routes the message through the TTL retry queue (its TTL is the one given to `SetupDeadLetterExchange`) | -| not `RetryEnabled`, attempts < `MaxRetries` | The consumer waits `RetryBackoff` (doubling with each retry, capped at 30s), then republishes a copy with `x-retry-count` + 1 and acks the original. Works on classic and quorum queues. The wait is in the consume loop, so it also slows the consumer while a dependency keeps failing; a batch waits once for all its messages. The republished copy keeps the message properties, `Expiration` included (it gets its full TTL again), but not `UserId`, which the broker rejects when it differs from the connection's user | -| attempts >= `MaxRetries`, or error wraps `ErrPoisonMessage` | `DeadLetterEnabled`: copy published to `.parking-lot`, original acked. Otherwise `Reject(false)` | - -The attempt count is the largest of the `x-death` count, `x-retry-count` and the quorum queue's `x-delivery-count`. - -### Batch consume - -```go -bc := rabbitmq.NewBatchConsumer(client, logger, 100, 5*time.Second, - rabbitmq.WithBatchValidator(rabbitmq.ValidJSON), // optional: park non-JSON bodies on their own -) - -batchHandler := rabbitmq.JSONBatchHandler(func(ctx context.Context, orders []Order, deliveries []amqp.Delivery) error { - // Process batch - // Return nil → one multiple-Ack for the whole batch - // Return error → retry policy applied to every delivery - return nil -}) - -bc.StartBatchConsumer(ctx, rabbitmq.ConsumeOptions{ - QueueName: "orders", - Consumer: "batch-worker", -}, batchHandler) -``` - ---- - -## Configuration Reference - -### Config (top-level) - -| Field | Type | Default | Description | -|-------|------|---------|-------------| -| `URL` | `string` | **required** | AMQP connection string | -| `ConnectionName` | `string` | `"go-service"` | Identifies client in broker UI | -| `PublisherConfirms` | `bool` | `false` | Enable per-message publisher confirms | -| `ChannelPoolSize` | `int` | `10` | Number of pre-allocated publisher channels | -| `Mandatory` | `bool` | `false` | Broker returns unroutable messages via `OnReturn` | -| `PersistentDelivery` | `bool` | `false` | Default `DeliveryMode = 2` (overridable per-message) | -| `PrefetchCount` | `int` | `10` | Consumer QoS prefetch count | -| `AutoAck` | `bool` | `false` | Should always be `false` in production | -| `QueueType` | `QueueType` | `"quorum"` | `QueueTypeQuorum` or `QueueTypeClassic` | -| `RetryEnabled` | `bool` | `false` | Retry through the queue's DLX and TTL retry queue. When `false`, retries are republished with an `x-retry-count` header; see [Consume](#consume) | -| `RetryBackoff` | `time.Duration` | `1s` | Base delay between counted retries when `RetryEnabled` is `false`; doubles per retry, capped at 30s. Zero uses the default, negative retries at once | -| `MaxRetries` | `int` | `3` | Retries after the first failure (the count is the largest of `x-death`, `x-retry-count`, `x-delivery-count`). Zero means "unset" and uses the default, so write a negative value for no retries: failures then go straight to the parking lot (or are rejected) | -| `DeadLetterEnabled` | `bool` | `false` | Enable DLX routing for failed messages | -| `ReconnectInitialInterval` | `time.Duration` | `1s` | Exponential backoff start | -| `ReconnectMaxInterval` | `time.Duration` | `60s` | Exponential backoff cap | -| `Heartbeat` | `time.Duration` | `0` | `0` = server-negotiated | -| `ChannelMax` | `int` | `0` | `0` = server-negotiated | -| `FrameSize` | `int` | `0` | `0` = server-negotiated | -| `OnReturn` | `func(amqp.Return)` | `nil` | Callback for unroutable mandatory messages | - -### QueueConfig - -| Field | Type | Description | -|-------|------|-------------| -| `Name` | `string` | Queue name | -| `Durable` | `bool` | Survive broker restart | -| `AutoDelete` | `bool` | Delete when last consumer disconnects | -| `Exclusive` | `bool` | Only accessible by declaring connection | -| `NoWait` | `bool` | Don't wait for broker confirmation | -| `Args` | `map[string]interface{}` | Custom arguments (e.g. `x-queue-type`) | - -### ExchangeConfig - -| Field | Type | Description | -|-------|------|-------------| -| `Name` | `string` | Exchange name | -| `Kind` | `string` | `direct`, `fanout`, `topic`, `headers` | -| `Durable` | `bool` | Survive broker restart | -| `AutoDelete` | `bool` | Delete when no queues bound | -| `Internal` | `bool` | Internal exchange (no publisher access) | -| `NoWait` | `bool` | Don't wait for broker confirmation | -| `Args` | `map[string]interface{}` | Custom arguments | - -### BindingConfig - -| Field | Type | Description | -|-------|------|-------------| -| `QueueName` | `string` | Queue to bind | -| `Exchange` | `string` | Exchange to bind to | -| `RoutingKey` | `string` | Routing key pattern | -| `NoWait` | `bool` | Don't wait for broker confirmation | -| `Args` | `map[string]interface{}` | Custom arguments | - -### PublishOptions - -| Field | Type | Description | -|-------|------|-------------| -| `Exchange` | `string` | Exchange name (empty = default exchange) | -| `RoutingKey` | `string` | Routing key (or queue name for default exchange) | -| `Mandatory` | `bool` | Override Config.Mandatory | -| `Immediate` | `bool` | AMQP immediate flag | -| `MessageId` | `string` | App-level message identifier | -| `CorrelationId` | `string` | Request/reply correlation | -| `ReplyTo` | `string` | Reply queue address | -| `Expiration` | `string` | Per-message TTL string | -| `Priority` | `uint8` | Message priority (0-9) | -| `Type` | `string` | Message type name | -| `AppId` | `string` | Application identifier | -| `UserId` | `string` | User identifier | -| `ContentType` | `string` | MIME type (default: `"application/json"`) | -| `ContentEncoding` | `string` | Content encoding | -| `Timestamp` | `time.Time` | Message timestamp | -| `DeliveryMode` | `uint8` | `0` = use Config, `1` = transient, `2` = persistent | -| `Headers` | `map[string]interface{}` | Custom headers (OTel context auto-injected) | - -### ConsumeOptions - -| Field | Type | Description | -|-------|------|-------------| -| `QueueName` | `string` | Queue to consume from | -| `Consumer` | `string` | Consumer tag (name in broker UI) | -| `AutoAck` | `bool` | Override Config.AutoAck | -| `Exclusive` | `bool` | Exclusive consumer | -| `NoLocal` | `bool` | Don't receive own messages | -| `NoWait` | `bool` | Don't wait for broker confirmation | -| `Args` | `map[string]interface{}` | Custom arguments | -| `AutoReconnect` | `bool` | Restart consume loop after delivery channel close | - ---- - -## Testing - -```bash -cd rabbitmq && make test # go test -count=1 -timeout 120s ./... -``` +Use a disposable broker/vhost with queue declaration/deletion permissions. The +test is skipped when the variable is unset; Docker is not required by the suite. diff --git a/rabbitmq/adr.md b/rabbitmq/adr.md new file mode 100644 index 0000000..3aceeae --- /dev/null +++ b/rabbitmq/adr.md @@ -0,0 +1,36 @@ +# Processing failures and reliable transfers + +Status: implemented; executable verification pending the declared Go toolchain. + +The application classifies business failures through an optional policy. Retry +processing in place with bounded attempts/time and jittered exponential backoff. +Return on unknown/configuration failures, and stop immediately on a dependency +outage. An optional recovery runner probes the dependency with no consumer alive. +This avoids broker retry-copy loops and repeated calls to a failed dependency. + +Park only permanent failures or explicitly configured retry exhaustion. Validate +per-subscription durable DLQ topology before consuming. Check publisher returns +as well as confirms before acknowledging the original. Settle batches per delivery +so a later multiple-ack cannot hide an earlier failure. Leave failed input unacked +and close the consumer channel instead of immediately requeueing into a hot loop. + +Internal transfers use isolated, bounded-lifetime connections/channels. The +amqp091-go publish context does not interrupt blocked socket writes; cancellation +closes the dedicated socket. A semaphore bounds concurrent transfer connections. +One in-flight publication per channel eliminates return/confirm ambiguity, and +there are no unresolved notifications carried over to another transfer. This +adds connection setup cost on failure paths but leaves normal pooled publishing +behavior unchanged. A future pool must retain these cancellation and correlation +guarantees before replacing this implementation. + +Durability, retention and capacity remain broker configuration choices; the SDK +requires durable destinations and explicit overflow semantics for bounded queues. +Using an exchange guarantees delivery to some matching queue, while the default +exchange identifies the exact named queue. AMQP cannot inspect queue argument +equivalence with passive declarations alone, so UseExisting also performs active +idempotent declarations and needs the corresponding permissions. + +Delivery is at least once; applications must tolerate duplicates. Preserve body, +properties and failure metadata, reset source TTL/delivery count on parked copies, +and never automatically redrive a DLQ. Keep the same public policy contract as +Kafka without coupling the independent modules through a new shared dependency. diff --git a/rabbitmq/client.go b/rabbitmq/client.go index f5fd298..4e79b9d 100644 --- a/rabbitmq/client.go +++ b/rabbitmq/client.go @@ -63,6 +63,7 @@ type Client struct { consumerConn *amqp.Connection publisherPool *channelPool + transferSlots chan struct{} state atomic.Int32 closeChan chan struct{} @@ -113,6 +114,7 @@ func NewClient(config *Config, logger *slog.Logger) (*Client, error) { bindings: make([]BindingConfig, 0), }, } + client.transferSlots = make(chan struct{}, config.ChannelPoolSize) client.publisherPool = newChannelPool(config.ChannelPoolSize, client.newPublisherChannel) client.state.Store(int32(StateConnecting)) diff --git a/rabbitmq/config.go b/rabbitmq/config.go index 2407900..d0acfbc 100644 --- a/rabbitmq/config.go +++ b/rabbitmq/config.go @@ -45,6 +45,8 @@ type Config struct { TLSConfig *tls.Config // Producer settings + // TransferTimeout bounds internal transfer connections and all their socket I/O. + TransferTimeout time.Duration PublisherConfirms bool ChannelPoolSize int Mandatory bool @@ -61,26 +63,12 @@ type Config struct { // auto-delete, ...) are set per queue in QueueConfig. QueueType QueueType - // Retry/DLX settings. - // - // RetryEnabled: reject a failed delivery without requeue, so the queue's - // dead-letter exchange routes it to the TTL retry queue (see - // TopologyManager.SetupDeadLetterExchange). Without a DLX it is dropped. - // - // Without RetryEnabled, the client waits RetryBackoff (doubling per retry), - // then republishes the message with an incremented "x-retry-count" header - // and acks the original. This bounds retries on any queue type. The wait - // blocks the consume loop, which slows the consumer while a dependency - // keeps failing. If the ack is lost the message is delivered twice. - // - // RetryBackoff: zero uses DefaultRetryBackoff, negative retries at once. - // Ignored when RetryEnabled is true. - // - // MaxRetries: retries after the first failure. Zero uses DefaultMaxRetries, - // negative means no retries. - // - // DeadLetterEnabled: after MaxRetries, publish the message to - // ".parking-lot" and ack it; otherwise reject it. + // Legacy retry settings. MaxRetries/RetryBackoff supply defaults when a + // subscription does not set ConsumeOptions.RetryPolicy. Zero uses defaults; + // a negative MaxRetries disables retries. RetryEnabled is no longer accepted: + // processing retries are in place rather than broker-side republish loops. + // DeadLetterEnabled enables the conventional existing .parking-lot + // destination; prefer per-subscription DeadLetterConfig for explicit topology. RetryEnabled bool RetryBackoff time.Duration MaxRetries int @@ -104,6 +92,7 @@ type Config struct { func NewDefaultConfig() *Config { return &Config{ ConnectionName: "go-service", + TransferTimeout: 10 * time.Second, PublisherConfirms: false, ChannelPoolSize: DefaultChannelPoolSize, Mandatory: false, @@ -124,11 +113,15 @@ func NewDefaultConfig() *Config { // ConnectionName, ChannelPoolSize, PrefetchCount, QueueType, RetryBackoff, // MaxRetries, ReconnectInitialInterval and ReconnectMaxInterval. Zero means // "unset", so MaxRetries: 0 becomes DefaultMaxRetries; a negative RetryBackoff -// or MaxRetries is kept and means "none". Other negative values are left for +// MaxRetries is kept and disables retries; non-positive RetryBackoff now uses +// the policy default. Other negative values are left for // Validate to reject. Booleans and URL are never touched. func (c *Config) ApplyDefaults() { def := NewDefaultConfig() + if c.TransferTimeout == 0 { + c.TransferTimeout = 10 * time.Second + } c.ConnectionName = cmp.Or(c.ConnectionName, def.ConnectionName) c.ChannelPoolSize = cmp.Or(c.ChannelPoolSize, def.ChannelPoolSize) c.PrefetchCount = cmp.Or(c.PrefetchCount, def.PrefetchCount) @@ -142,6 +135,12 @@ func (c *Config) ApplyDefaults() { // Validate reports the first invalid field. It does not modify the config; call // ApplyDefaults first to fill unset fields (NewClient does both). func (c *Config) Validate() error { + if c.RetryEnabled { + return errors.New("RetryEnabled broker retry loops are unsupported; configure ConsumeOptions.RetryPolicy") + } + if c.TransferTimeout < 0 { + return errors.New("negative TransferTimeout") + } if c.URL == "" { return ErrURLRequired } diff --git a/rabbitmq/consumer.go b/rabbitmq/consumer.go index 8054c4f..d714f0f 100644 --- a/rabbitmq/consumer.go +++ b/rabbitmq/consumer.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "log/slog" - "maps" "time" amqp "github.com/rabbitmq/amqp091-go" @@ -19,7 +18,7 @@ import ( // malformed payload. When a MessageHandler returns an error wrapping it the // consumer skips the retries and settles the message as if MaxRetries was // already reached: it is moved to ".parking-lot" when DeadLetterEnabled, -// and rejected otherwise. +// and otherwise preserved while consumption stops. var ErrPoisonMessage = errors.New("rabbitmq: poison message") // MessageHandler is called for each consumed message. @@ -27,9 +26,10 @@ var ErrPoisonMessage = errors.New("rabbitmq: poison message") // The payload is delivery.Body, exactly as published: the consumer neither // decodes it nor assumes a content type. Use JSONHandler for typed JSON. // -// Returning nil acks the message. Returning an error applies the retry policy -// of Config (RetryEnabled, MaxRetries, DeadLetterEnabled); an error wrapping -// ErrPoisonMessage skips the retries. +// Returning nil acknowledges the message. RetryPolicy classifies failures; +// unknown failures stop consumption after bounded in-place retries. An error +// wrapping ErrPoisonMessage is permanent and skips retries. Without a usable +// DLQ the original is preserved and consumption stops. type MessageHandler func(ctx context.Context, delivery amqp.Delivery) error // JSONHandler adapts a typed handler to a MessageHandler. The body is decoded @@ -50,13 +50,18 @@ func JSONHandler[T any](fn func(ctx context.Context, msg T, delivery amqp.Delive // Consumer handles message consumption with QoS and OTel tracing. type Consumer struct { - client *Client - logger *slog.Logger - tracer trace.Tracer + client *Client + logger *slog.Logger + tracer trace.Tracer + policy RetryPolicy + deadLetter *DeadLetterConfig } // NewConsumer creates a new Subscriber backed by client. func NewConsumer(client *Client, logger *slog.Logger) Subscriber { + if logger == nil { + logger = slog.Default() + } return &Consumer{ client: client, logger: logger, @@ -66,6 +71,8 @@ func NewConsumer(client *Client, logger *slog.Logger) Subscriber { // ConsumeOptions contains options for consuming messages. type ConsumeOptions struct { + RetryPolicy *RetryPolicy + DeadLetter *DeadLetterConfig QueueName string Consumer string // Consumer tag AutoAck bool @@ -82,6 +89,24 @@ var errDeliveryChannelClosed = errors.New("delivery channel closed") // StartConsumer starts consuming messages from a queue. // If opts.AutoReconnect is true, it will automatically restart on delivery channel closure. func (c *Consumer) StartConsumer(ctx context.Context, opts ConsumeOptions, handler MessageHandler) error { + if c.client == nil || handler == nil { + return errors.New("consumer requires a client and handler") + } + if opts.QueueName == "" { + return errors.New("source queue is required") + } + if opts.AutoAck || c.client.config.AutoAck { + return errors.New("reliable consumption requires manual acknowledgements") + } + local := *c + local.policy, local.deadLetter = subscriptionPolicy(c.client.config, opts) + if err := errors.Join(local.policy.validate(local.deadLetter != nil), local.deadLetter.validate(opts.QueueName)); err != nil { + return err + } + if err := local.client.prepareDeadLetter(ctx, local.deadLetter); err != nil { + return fmt.Errorf("prepare dead-letter queue: %w", err) + } + c = &local if opts.AutoReconnect { return c.startConsumerWithReconnect(ctx, opts, handler) } @@ -95,6 +120,7 @@ func (c *Consumer) startConsumeLoop(ctx context.Context, opts ConsumeOptions, ha return fmt.Errorf("failed to create consumer channel: %w", err) } + defer func() { _ = ch.Close() }() // PrefetchCount was validated by NewClient and is positive. prefetchCount := c.client.config.PrefetchCount if err := ch.Qos(prefetchCount, 0, false); err != nil { @@ -136,7 +162,7 @@ func (c *Consumer) startConsumeLoop(ctx context.Context, opts ConsumeOptions, ha case reason, ok := <-cancelChan: _ = ch.Close() if !ok { - return errors.New("consumer cancelled by broker") + return errDeliveryChannelClosed } c.logger.Warn("consumer cancelled by broker", "queue", opts.QueueName, @@ -152,10 +178,8 @@ func (c *Consumer) startConsumeLoop(ctx context.Context, opts ConsumeOptions, ha } if err := c.processDelivery(ctx, delivery, handler, autoAck, opts.QueueName); err != nil { - c.logger.Error("failed to process delivery", - "error", err, - "delivery_tag", delivery.DeliveryTag, - ) + _ = ch.Close() + return err } } } @@ -173,14 +197,17 @@ func (c *Consumer) startConsumerWithReconnect(ctx context.Context, opts ConsumeO if err == nil || ctx.Err() != nil { return err } + if !errors.Is(err, errDeliveryChannelClosed) && !errors.Is(err, ErrNotConnected) { + return err + } c.logger.Warn("consumer disconnected, waiting for reconnection", "queue", opts.QueueName, "error", err, ) - if !c.waitForReconnect(ctx) { - return ctx.Err() + if err := c.waitForReconnect(ctx); err != nil { + return err } c.logger.Info("client reconnected, restarting consumer", "queue", opts.QueueName) @@ -188,17 +215,19 @@ func (c *Consumer) startConsumerWithReconnect(ctx context.Context, opts ConsumeO } // waitForReconnect polls until the client is healthy or the context is cancelled. -func (c *Consumer) waitForReconnect(ctx context.Context) bool { +func (c *Consumer) waitForReconnect(ctx context.Context) error { ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() for { select { case <-ctx.Done(): - return false + return ctx.Err() + case <-c.client.closeChan: + return ErrClientClosed case <-ticker.C: if c.client.IsHealthy() { - return true + return nil } } } @@ -216,220 +245,75 @@ func traceCarrier(headers amqp.Table) propagation.MapCarrier { return carrier } -// processDelivery processes a single delivery with tracing and ack management. -func (c *Consumer) processDelivery(ctx context.Context, delivery amqp.Delivery, handler MessageHandler, autoAck bool, queue string) error { - ctx = otel.GetTextMapPropagator().Extract(ctx, traceCarrier(delivery.Headers)) - - ctx, span := c.tracer.Start(ctx, "rabbitmq.consume") - defer span.End() - - if err := handler(ctx, delivery); err != nil { - span.RecordError(err) - - if !autoAck { - c.settleFailure(ctx, delivery, queue, err) +// subscriptionPolicy copies per-subscription settings. Legacy fields only +// supply retry counts/delays; broker-side retry routing is no longer used. +func subscriptionPolicy(cfg *Config, opts ConsumeOptions) (RetryPolicy, *DeadLetterConfig) { + policy := opts.RetryPolicy.normalized() + if opts.RetryPolicy == nil { + policy.MaxRetries = max(0, cfg.MaxRetries) + if cfg.RetryBackoff > 0 { + policy.InitialBackoff = cfg.RetryBackoff + policy.MaxBackoff = max(policy.MaxBackoff, cfg.RetryBackoff) } - return fmt.Errorf("handler error: %w", err) - } - - if autoAck { - return nil - } - if err := delivery.Ack(false); err != nil { - c.logger.Error("failed to acknowledge message", "error", err) - return fmt.Errorf("failed to ack: %w", err) - } - return nil -} - -// settleFailure settles a delivery whose handler returned err. -func (c *Consumer) settleFailure(ctx context.Context, d amqp.Delivery, queue string, err error) { - cfg := c.client.config - if errors.Is(err, ErrPoisonMessage) { - settleExhausted(ctx, cfg, c.logger, c.client.republish, d, queue, "poison message") - return - } - if !c.waitBeforeRetry(ctx, queue, d) { - return - } - handleFailedDelivery(ctx, cfg, c.logger, c.client.republish, d, queue) -} - -// waitBeforeRetry waits out the retry backoff for d and reports whether to go -// on settling it. When ctx ends first the delivery is left unacked: closing the -// consumer's channel makes the broker redeliver it. -func (c *Consumer) waitBeforeRetry(ctx context.Context, queue string, ds ...amqp.Delivery) bool { - if err := waitBeforeRetry(ctx, c.client.config, queue, ds...); err != nil { - c.logger.Warn("retry wait interrupted, leaving message unacked", "queue", queue, "error", err) - return false - } - return true -} - -// parkingLotSuffix names the queue that receives messages which exhausted -// their retries (see TopologyManager.SetupDeadLetterExchange). -const parkingLotSuffix = ".parking-lot" - -// retryCountHeader carries the number of failed attempts when RetryEnabled is -// false and the client republishes the message itself. -const retryCountHeader = "x-retry-count" - -// republishFunc publishes a copy of d to queue through the default exchange. -type republishFunc func(ctx context.Context, queue string, d amqp.Delivery) error - -// maxRetryDelay caps the backoff between counted retries. -const maxRetryDelay = 30 * time.Second - -// retryDelay is the wait before the retry that follows retryCount failures: -// base, doubling with every failure, capped at maxRetryDelay. A non-positive -// base means no delay. -func retryDelay(base time.Duration, retryCount int) time.Duration { - if base <= 0 { - return 0 } - d := base - for range retryCount { - if d >= maxRetryDelay { - break + classify := policy.Classify + policy.Classify = func(err error) FailureKind { + if errors.Is(err, ErrPoisonMessage) { + return PermanentFailure } - d *= 2 - } - return min(d, maxRetryDelay) -} - -// waitBeforeRetry sleeps for the longest backoff any of ds needs before its -// counted retry. It returns at once when RetryEnabled (the retry queue's TTL is -// the delay), when the backoff is disabled, or when none of ds will be retried, -// and returns ctx's error if ctx ends first. -func waitBeforeRetry(ctx context.Context, cfg *Config, queue string, ds ...amqp.Delivery) error { - if cfg.RetryEnabled { - return nil - } - var delay time.Duration - for _, d := range ds { - if n := getRetryCount(d, queue); n < cfg.MaxRetries { - delay = max(delay, retryDelay(cfg.RetryBackoff, n)) + if classify != nil { + return classify(err) } + return UnknownFailure } - if delay <= 0 { - return nil - } - - timer := time.NewTimer(delay) - defer timer.Stop() - select { - case <-ctx.Done(): - return ctx.Err() - case <-timer.C: - return nil + dlq := opts.DeadLetter + if dlq == nil && cfg.DeadLetterEnabled { + dlq = &DeadLetterConfig{} } + return policy, dlq.normalized(opts.QueueName) } -// handleFailedDelivery settles a delivery whose handler failed: -// -// - under MaxRetries with RetryEnabled: Reject without requeue (the queue's -// DLX routes it through the TTL retry queue); -// - under MaxRetries without RetryEnabled: republish a copy to the queue with -// an incremented "x-retry-count" header and Ack the original (Nack with -// requeue if that publish fails), so the attempts are counted on any queue -// type; -// - at MaxRetries: settleExhausted. -// -// At MaxRetries a reject would not reach the parking lot: the DLX routes by the -// main queue's name, which leads back to the retry queue. -func handleFailedDelivery(ctx context.Context, cfg *Config, logger *slog.Logger, republish republishFunc, d amqp.Delivery, queue string) { - retryCount := getRetryCount(d, queue) - - if retryCount >= cfg.MaxRetries { - settleExhausted(ctx, cfg, logger, republish, d, queue, "max retries exceeded") - return - } - - if cfg.RetryEnabled { - if err := d.Reject(false); err != nil { - logger.Error("failed to settle message for retry", "error", err) - } - logger.Debug("message scheduled for retry", - "queue", queue, - "retry_count", retryCount, - "via_dlx", true, - ) - return +// processDelivery retries in place; an outage never republishes the input. +func (c *Consumer) processDelivery(ctx context.Context, delivery amqp.Delivery, handler MessageHandler, autoAck bool, queue string) error { + if autoAck { + return errors.New("reliable consumption requires manual acknowledgements") } - - next := d - next.Headers = withRetryCount(d.Headers, retryCount+1) - if err := republish(ctx, queue, next); err != nil { - logger.Error("failed to republish message for retry, requeueing", - "queue", queue, - "retry_count", retryCount, - "error", err, - ) - if nackErr := d.Nack(false, true); nackErr != nil { - logger.Error("failed to nack message", "error", nackErr) - } - return + ctx = otel.GetTextMapPropagator().Extract(ctx, traceCarrier(delivery.Headers)) + ctx, span := c.tracer.Start(ctx, "rabbitmq.consume") + defer span.End() + failure := c.policy.process(ctx, func(attemptCtx context.Context) error { return handler(attemptCtx, delivery) }) + if err := ctx.Err(); err != nil { + return err } - if err := d.Ack(false); err != nil { - logger.Error("failed to ack message republished for retry", "error", err) + if failure.err != nil { + span.RecordError(failure.err) } - logger.Debug("message scheduled for retry", - "queue", queue, - "retry_count", retryCount, - "via_dlx", false, - ) + return settleProcessed(delivery, failure, func() error { + if c.deadLetter == nil { + return failure.paused() + } + return c.client.park(ctx, c.deadLetter, delivery, queue, failure) + }) } -// settleExhausted settles a delivery that will not be retried again: it is -// published to ".parking-lot" and acked when DeadLetterEnabled (Nack -// with requeue if that publish fails), and rejected otherwise. -func settleExhausted(ctx context.Context, cfg *Config, logger *slog.Logger, republish republishFunc, d amqp.Delivery, queue, reason string) { - retryCount := getRetryCount(d, queue) - - if !cfg.DeadLetterEnabled { - if err := d.Reject(false); err != nil { - logger.Error("failed to reject message", "error", err) +// settleProcessed acknowledges failures only after the replacement is confirmed +// and routed. Its caller closes the channel on error, preserving unacked input. +func settleProcessed(d amqp.Delivery, failure processingResult, publish func() error) error { + if failure.err != nil { + if !failure.park { + return failure.paused() } - logger.Warn("message rejected ("+reason+")", - "queue", queue, - "retry_count", retryCount, - "max_retries", cfg.MaxRetries, - ) - return - } - - parkingLot := queue + parkingLotSuffix - if err := republish(ctx, parkingLot, d); err != nil { - logger.Error("failed to move message to parking lot, requeueing", - "queue", queue, - "parking_lot", parkingLot, - "error", err, - ) - if nackErr := d.Nack(false, true); nackErr != nil { - logger.Error("failed to nack message", "error", nackErr) + if err := publish(); err != nil { + return err } - return } if err := d.Ack(false); err != nil { - logger.Error("failed to ack message moved to parking lot", "error", err) + return fmt.Errorf("acknowledge delivery: %w", err) } - logger.Warn("message moved to parking lot ("+reason+")", - "queue", queue, - "parking_lot", parkingLot, - "retry_count", retryCount, - "max_retries", cfg.MaxRetries, - ) + return nil } -// withRetryCount returns a copy of headers with the retry counter set to n. -// The broker-managed x-delivery-count is dropped: n already includes it. -func withRetryCount(headers amqp.Table, n int) amqp.Table { - out := amqp.Table{} - maps.Copy(out, headers) - delete(out, "x-delivery-count") - out[retryCountHeader] = int64(n) - return out -} +const parkingLotSuffix = ".parking-lot" // publishingFrom rebuilds d as a Publishing: body, headers (including x-death // history) and the properties that describe the message, Expiration included @@ -454,70 +338,6 @@ func publishingFrom(d amqp.Delivery) amqp.Publishing { } } -// republish publishes d to queue via the default exchange, waiting for the -// broker confirm when publisher confirms are enabled. A message with a -// per-message TTL gets its full TTL again, since the broker counts from enqueue. -func (c *Client) republish(ctx context.Context, queue string, d amqp.Delivery) error { - ch, err := c.GetPublisherChannel(ctx) - if err != nil { - return err - } - defer c.ReturnPublisherChannel(ch) - - dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, "", queue, false, false, publishingFrom(d)) - if err != nil { - return err - } - return waitConfirm(ctx, dc) -} - -// getRetryCount returns how many times d has failed on queue: the largest of -// the x-death count for queue, x-retry-count and x-delivery-count. Taking the -// largest never under-counts a message that went through more than one retry -// path. -func getRetryCount(d amqp.Delivery, queue string) int { - count := xDeathCount(d.Headers, queue) - for _, header := range []string{retryCountHeader, "x-delivery-count"} { - if n, ok := toInt(d.Headers[header]); ok { - count = max(count, n) - } - } - return count -} - -// xDeathCount returns the "count" of the x-death entry the broker recorded for -// queue, or 0 when the message was never dead-lettered from it. -func xDeathCount(headers amqp.Table, queue string) int { - entries, _ := headers["x-death"].([]any) - count := 0 - for _, entry := range entries { - table, ok := entry.(amqp.Table) - if !ok { - continue - } - if q, _ := table["queue"].(string); q != queue { - continue - } - if n, ok := toInt(table["count"]); ok { - count = max(count, n) - } - } - return count -} - -func toInt(v any) (int, bool) { - switch n := v.(type) { - case int64: - return int(n), true - case int32: - return int(n), true - case int: - return n, true - default: - return 0, false - } -} - // ConsumeWithDefaults consumes queueName with manual acks and no auto-reconnect. func (c *Consumer) ConsumeWithDefaults(ctx context.Context, queueName string, handler MessageHandler) error { return c.StartConsumer(ctx, ConsumeOptions{ @@ -533,7 +353,7 @@ func (c *Consumer) ConsumeWithDefaults(ctx context.Context, queueName string, ha // BatchHandler is called with a batch of deliveries; each payload is the // delivery's Body, undecoded. Returning nil acks the whole batch. Returning an -// error applies the retry policy of Config to every delivery of the batch. +// error applies the subscription RetryPolicy to the whole batch. type BatchHandler func(ctx context.Context, deliveries []amqp.Delivery) error // JSONBatchHandler adapts a typed handler to a BatchHandler. Every body is @@ -569,15 +389,15 @@ type BatchOption func(*BatchConsumer) // WithBatchValidator sets a check run on every delivery before it joins a // batch. A delivery that fails is settled on its own as a poison message -// (parking lot when DeadLetterEnabled, rejected otherwise) and never reaches +// (parked with DeadLetterConfig, otherwise preserved) and never reaches // the handler, so one bad message cannot fail the batch it would sit in. // Without a validator every delivery joins a batch. func WithBatchValidator(validate func(amqp.Delivery) error) BatchOption { return func(bc *BatchConsumer) { bc.validate = validate } } -// BatchConsumer consumes in batches. It owns its channel and acks a whole batch -// at once. +// BatchConsumer owns its channel and settles each delivery independently, so +// a failed validator or transfer cannot be acknowledged by a later batch. type BatchConsumer struct { client *Client logger *slog.Logger @@ -585,10 +405,18 @@ type BatchConsumer struct { batchSize int flushTimeout time.Duration validate func(amqp.Delivery) error + policy RetryPolicy + deadLetter *DeadLetterConfig } // NewBatchConsumer creates a batch consumer. func NewBatchConsumer(client *Client, logger *slog.Logger, batchSize int, flushTimeout time.Duration, opts ...BatchOption) *BatchConsumer { + if logger == nil { + logger = slog.Default() + } + if flushTimeout <= 0 { + flushTimeout = time.Second + } bc := &BatchConsumer{ client: client, logger: logger, @@ -606,11 +434,27 @@ func NewBatchConsumer(client *Client, logger *slog.Logger, batchSize int, flushT // flushing a partial batch after the flush timeout. It returns when ctx ends or // the delivery channel closes. func (bc *BatchConsumer) StartBatchConsumer(ctx context.Context, opts ConsumeOptions, handler BatchHandler) error { + if bc.client == nil || handler == nil || opts.QueueName == "" { + return errors.New("batch consumer requires client, queue and handler") + } + if opts.AutoAck || bc.client.config.AutoAck { + return errors.New("reliable consumption requires manual acknowledgements") + } + local := *bc + local.policy, local.deadLetter = subscriptionPolicy(bc.client.config, opts) + if err := errors.Join(local.policy.validate(local.deadLetter != nil), local.deadLetter.validate(opts.QueueName)); err != nil { + return err + } + if err := local.client.prepareDeadLetter(ctx, local.deadLetter); err != nil { + return fmt.Errorf("prepare dead-letter queue: %w", err) + } + bc = &local ch, deliveries, err := bc.consume(opts) if err != nil { return err } + defer func() { _ = ch.Close() }() b := &batcher{bc: bc, queue: opts.QueueName, handler: handler} flushTimer := time.NewTimer(bc.flushTimeout) defer flushTimer.Stop() @@ -618,27 +462,29 @@ func (bc *BatchConsumer) StartBatchConsumer(ctx context.Context, opts ConsumeOpt for { select { case <-ctx.Done(): - // Flush the remaining batch before exiting; ctx is already - // cancelled, so give the handler and acks a bounded detached context. - shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), bc.flushTimeout) - b.flushAndLog(shutdownCtx, "failed to flush batch on shutdown") - cancel() _ = ch.Close() return ctx.Err() case <-flushTimer.C: b.flushAndLog(ctx, "failed to flush batch on timeout") + if b.err != nil { + _ = ch.Close() + return b.err + } flushTimer.Reset(bc.flushTimeout) case delivery, ok := <-deliveries: if !ok { - b.flushAndLog(ctx, "failed to flush batch on channel close") _ = ch.Close() return errDeliveryChannelClosed } if b.add(ctx, delivery) { flushTimer.Reset(bc.flushTimeout) } + if b.err != nil { + _ = ch.Close() + return b.err + } } } } @@ -691,6 +537,7 @@ type batcher struct { queue string handler BatchHandler pending []amqp.Delivery + err error } // add appends delivery to the batch unless it is invalid, flushing when the @@ -727,7 +574,13 @@ func (b *batcher) accept(ctx context.Context, delivery amqp.Delivery) bool { span.RecordError(err) bc.logger.Warn("invalid message, not batched", "queue", b.queue, "error", err) - settleExhausted(ctx, bc.client.config, bc.logger, bc.client.republish, delivery, b.queue, "invalid message") + failure := processingResult{err: err, kind: PermanentFailure, attempts: 1, park: true} + b.err = settleProcessed(delivery, failure, func() error { + if bc.deadLetter == nil { + return failure.paused() + } + return bc.client.park(ctx, bc.deadLetter, delivery, b.queue, failure) + }) return false } @@ -738,31 +591,29 @@ func (b *batcher) flush(ctx context.Context) error { return nil } batch := b.pending - b.pending = nil - - if err := b.handler(ctx, batch); err != nil { - // One backoff for the whole batch, then the retry policy per message. - if werr := waitBeforeRetry(ctx, b.bc.client.config, b.queue, batch...); werr != nil { - b.bc.logger.Warn("retry wait interrupted, leaving batch unacked", "queue", b.queue, "error", werr) - return fmt.Errorf("batch handler error: %w", err) - } - for _, d := range batch { - handleFailedDelivery(ctx, b.bc.client.config, b.bc.logger, b.bc.client.republish, d, b.queue) - } - return fmt.Errorf("batch handler error: %w", err) + failure := b.bc.policy.process(ctx, func(attemptCtx context.Context) error { return b.handler(attemptCtx, batch) }) + if err := ctx.Err(); err != nil { + return err } - - // This consumer owns the channel and settles deliveries in order, so a - // single multiple-ack on the last tag acks the whole batch. - if err := batch[len(batch)-1].Ack(true); err != nil { - b.bc.logger.Error("failed to ack batch", "error", err) + for _, delivery := range batch { + err := settleProcessed(delivery, failure, func() error { + if b.bc.deadLetter == nil { + return failure.paused() + } + return b.bc.client.park(ctx, b.bc.deadLetter, delivery, b.queue, failure) + }) + if err != nil { + return err + } } + b.pending = nil return nil } // flushAndLog flushes the batch and logs a failure under msg. func (b *batcher) flushAndLog(ctx context.Context, msg string) { if err := b.flush(ctx); err != nil { + b.err = err b.bc.logger.Error(msg, "error", err) } } diff --git a/rabbitmq/consumer_test.go b/rabbitmq/consumer_test.go index 9d540c8..50f0cd7 100644 --- a/rabbitmq/consumer_test.go +++ b/rabbitmq/consumer_test.go @@ -13,67 +13,6 @@ import ( amqp "github.com/rabbitmq/amqp091-go" ) -func TestGetRetryCount(t *testing.T) { - cases := []struct { - name string - headers amqp.Table - want int - }{ - {"no headers", nil, 0}, - { - // One entry per queue+reason; the retry count lives in "count". - name: "x-death count for this queue", - headers: amqp.Table{"x-death": []any{ - amqp.Table{"queue": "orders.retry", "reason": "expired", "count": int64(4)}, - amqp.Table{"queue": "orders", "reason": "rejected", "count": int64(3)}, - }}, - want: 3, - }, - { - name: "x-death for other queue only", - headers: amqp.Table{"x-death": []any{ - amqp.Table{"queue": "other", "reason": "rejected", "count": int64(7)}, - }}, - want: 0, - }, - { - name: "quorum x-delivery-count fallback", - headers: amqp.Table{"x-delivery-count": int64(2)}, - want: 2, - }, - { - name: "client-side x-retry-count", - headers: amqp.Table{"x-retry-count": int64(2)}, - want: 2, - }, - { - name: "largest of the counters wins", - headers: amqp.Table{ - "x-retry-count": int64(1), - "x-delivery-count": int64(4), - "x-death": []any{amqp.Table{"queue": "orders", "count": int64(2)}}, - }, - want: 4, - }, - { - name: "malformed entries ignored", - headers: amqp.Table{"x-death": []any{ - "garbage", - amqp.Table{"queue": "orders", "count": "nope"}, - }}, - want: 0, - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := getRetryCount(amqp.Delivery{Headers: tc.headers}, "orders") - if got != tc.want { - t.Fatalf("getRetryCount = %d, want %d", got, tc.want) - } - }) - } -} - func TestJitter(t *testing.T) { d := time.Second for range 1000 { @@ -176,15 +115,16 @@ func TestNewClient_DoesNotModifyConfig(t *testing.T) { // ---- failure settlement ----------------------------------------------------- type ackCall struct { - op string // ack | nack | reject - requeue bool + op string // ack | nack | reject + requeue bool + multiple bool } // fakeAcker records how a delivery was settled. type fakeAcker struct{ calls []ackCall } -func (f *fakeAcker) Ack(uint64, bool) error { - f.calls = append(f.calls, ackCall{op: "ack"}) +func (f *fakeAcker) Ack(_ uint64, multiple bool) error { + f.calls = append(f.calls, ackCall{op: "ack", multiple: multiple}) return nil } func (f *fakeAcker) Nack(_ uint64, _, requeue bool) error { @@ -196,176 +136,12 @@ func (f *fakeAcker) Reject(_ uint64, requeue bool) error { return nil } -type republished struct { - queue string - d amqp.Delivery -} - -// fakeRepublisher records republished copies; err makes every publish fail. -type fakeRepublisher struct { - sent []republished - err error -} - -func (f *fakeRepublisher) publish(_ context.Context, queue string, d amqp.Delivery) error { - if f.err != nil { - return f.err - } - f.sent = append(f.sent, republished{queue: queue, d: d}) - return nil -} - func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func newDelivery(acker *fakeAcker, headers amqp.Table) amqp.Delivery { return amqp.Delivery{Acknowledger: acker, Body: []byte(`{"id":1}`), Headers: headers} } -func expectCalls(t *testing.T, got []ackCall, want ...ackCall) { - t.Helper() - if len(got) != len(want) { - t.Fatalf("settlement calls = %+v, want %+v", got, want) - } - for i := range want { - if got[i] != want[i] { - t.Fatalf("settlement calls = %+v, want %+v", got, want) - } - } -} - -func TestHandleFailedDelivery(t *testing.T) { - ctx := context.Background() - - t.Run("RetryEnabled rejects into the DLX retry queue", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{} - cfg := &Config{RetryEnabled: true, MaxRetries: 3} - handleFailedDelivery(ctx, cfg, discardLogger(), pub.publish, newDelivery(acker, nil), "orders") - - expectCalls(t, acker.calls, ackCall{op: "reject"}) - if len(pub.sent) != 0 { - t.Fatalf("nothing may be republished, got %d", len(pub.sent)) - } - }) - - t.Run("without RetryEnabled the attempt is counted on a republished copy", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{} - cfg := &Config{MaxRetries: 3} - handleFailedDelivery(ctx, cfg, discardLogger(), pub.publish, newDelivery(acker, nil), "orders") - - expectCalls(t, acker.calls, ackCall{op: "ack"}) - if len(pub.sent) != 1 || pub.sent[0].queue != "orders" { - t.Fatalf("expected one copy republished to orders, got %+v", pub.sent) - } - if got := pub.sent[0].d.Headers["x-retry-count"]; got != int64(1) { - t.Fatalf("x-retry-count = %v, want 1", got) - } - if string(pub.sent[0].d.Body) != `{"id":1}` { - t.Fatalf("body must be copied unchanged, got %q", pub.sent[0].d.Body) - } - }) - - t.Run("retry copy keeps the caller's headers intact and drops x-delivery-count", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{} - orig := amqp.Table{"x-delivery-count": int64(1), "tenant": "a"} - handleFailedDelivery(ctx, &Config{MaxRetries: 3}, discardLogger(), pub.publish, newDelivery(acker, orig), "orders") - - copyHeaders := pub.sent[0].d.Headers - if copyHeaders["tenant"] != "a" || copyHeaders["x-retry-count"] != int64(2) { - t.Fatalf("unexpected copy headers %v", copyHeaders) - } - if _, ok := copyHeaders["x-delivery-count"]; ok { - t.Fatalf("x-delivery-count is broker-managed and must not be republished: %v", copyHeaders) - } - if _, ok := orig["x-retry-count"]; ok || len(orig) != 2 { - t.Fatalf("the delivery's own headers were mutated: %v", orig) - } - }) - - t.Run("failed retry publish requeues instead of losing the message", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{err: errors.New("broker down")} - handleFailedDelivery(ctx, &Config{MaxRetries: 3}, discardLogger(), pub.publish, newDelivery(acker, nil), "orders") - - expectCalls(t, acker.calls, ackCall{op: "nack", requeue: true}) - }) - - t.Run("max retries moves to the parking lot", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{} - cfg := &Config{MaxRetries: 3, DeadLetterEnabled: true} - d := newDelivery(acker, amqp.Table{"x-retry-count": int64(3)}) - handleFailedDelivery(ctx, cfg, discardLogger(), pub.publish, d, "orders") - - expectCalls(t, acker.calls, ackCall{op: "ack"}) - if len(pub.sent) != 1 || pub.sent[0].queue != "orders.parking-lot" { - t.Fatalf("expected a copy in orders.parking-lot, got %+v", pub.sent) - } - if pub.sent[0].d.Headers["x-retry-count"] != int64(3) { - t.Fatalf("parked copy must keep its history unchanged: %v", pub.sent[0].d.Headers) - } - }) - - t.Run("max retries without DeadLetterEnabled rejects", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{} - d := newDelivery(acker, amqp.Table{"x-retry-count": int64(3)}) - handleFailedDelivery(ctx, &Config{MaxRetries: 3}, discardLogger(), pub.publish, d, "orders") - - expectCalls(t, acker.calls, ackCall{op: "reject"}) - if len(pub.sent) != 0 { - t.Fatalf("nothing may be republished, got %d", len(pub.sent)) - } - }) - - t.Run("failed parking lot publish requeues", func(t *testing.T) { - acker, pub := &fakeAcker{}, &fakeRepublisher{err: errors.New("broker down")} - cfg := &Config{MaxRetries: 3, DeadLetterEnabled: true} - d := newDelivery(acker, amqp.Table{"x-retry-count": int64(3)}) - handleFailedDelivery(ctx, cfg, discardLogger(), pub.publish, d, "orders") - - expectCalls(t, acker.calls, ackCall{op: "nack", requeue: true}) - }) -} - -// A handler that always fails must reach the parking lot after MaxRetries -// retries, even on a queue with no broker-side counter and no DLX. -func TestHandleFailedDelivery_BoundsUnboundedRequeueLoop(t *testing.T) { - cfg := &Config{MaxRetries: 2, DeadLetterEnabled: true} - pub := &fakeRepublisher{} - headers := amqp.Table(nil) - - attempts, parked := 0, false - for attempts < 100 && !parked { - attempts++ - acker := &fakeAcker{} - handleFailedDelivery(context.Background(), cfg, discardLogger(), pub.publish, newDelivery(acker, headers), "orders") - - last := pub.sent[len(pub.sent)-1] - parked = last.queue == "orders.parking-lot" - headers = last.d.Headers // the broker would deliver the copy next - } - - if !parked || attempts != 3 { - t.Fatalf("parked=%v after %d attempts, want parked after 3 (1 initial + MaxRetries)", parked, attempts) - } -} - -func TestConsumer_SettleFailure_PoisonSkipsRetries(t *testing.T) { - // No DLX and no broker connection: a normal failure tries to republish (and - // requeues when that fails), a poison message is settled straight away. - c := &Consumer{client: &Client{config: &Config{MaxRetries: 3}}, logger: discardLogger()} - ctx := context.Background() - - normal := &fakeAcker{} - c.settleFailure(ctx, newDelivery(normal, nil), "orders", errors.New("db down")) - expectCalls(t, normal.calls, ackCall{op: "nack", requeue: true}) - - poison := &fakeAcker{} - c.settleFailure(ctx, newDelivery(poison, nil), "orders", ErrPoisonMessage) - expectCalls(t, poison.calls, ackCall{op: "reject"}) - - wrapped := &fakeAcker{} - c.settleFailure(ctx, newDelivery(wrapped, nil), "orders", errors.Join(errors.New("ctx"), ErrPoisonMessage)) - expectCalls(t, wrapped.calls, ackCall{op: "reject"}) -} - // ---- handlers ---------------------------------------------------------------- type order struct { @@ -461,124 +237,6 @@ func TestWithBatchValidator(t *testing.T) { } } -// ---- retry backoff ------------------------------------------------------------ - -func TestRetryDelay(t *testing.T) { - cases := []struct { - base time.Duration - count int - want time.Duration - }{ - {time.Second, 0, time.Second}, - {time.Second, 1, 2 * time.Second}, - {time.Second, 2, 4 * time.Second}, - {time.Second, 4, 16 * time.Second}, - {time.Second, 5, maxRetryDelay}, // 32s capped - {time.Second, 500, maxRetryDelay}, // no overflow for huge counts - {time.Minute, 0, maxRetryDelay}, // base above the cap - {0, 3, 0}, - {-time.Second, 3, 0}, - } - for _, tc := range cases { - if got := retryDelay(tc.base, tc.count); got != tc.want { - t.Errorf("retryDelay(%v, %d) = %v, want %v", tc.base, tc.count, got, tc.want) - } - } -} - -func TestWaitBeforeRetry(t *testing.T) { - ctx := context.Background() - fresh := amqp.Delivery{} - spent := amqp.Delivery{Headers: amqp.Table{"x-retry-count": int64(3)}} - - elapsed := func(cfg *Config, ds ...amqp.Delivery) (time.Duration, error) { - start := time.Now() - err := waitBeforeRetry(ctx, cfg, "orders", ds...) - return time.Since(start), err - } - - t.Run("waits the backoff for a counted retry", func(t *testing.T) { - d, err := elapsed(&Config{MaxRetries: 3, RetryBackoff: 40 * time.Millisecond}, fresh) - if err != nil || d < 40*time.Millisecond { - t.Fatalf("waited %v (err %v), want at least 40ms", d, err) - } - }) - - t.Run("no wait when RetryEnabled, the retry queue TTL is the delay", func(t *testing.T) { - d, err := elapsed(&Config{MaxRetries: 3, RetryEnabled: true, RetryBackoff: time.Hour}, fresh) - if err != nil || d > 100*time.Millisecond { - t.Fatalf("waited %v (err %v), want none", d, err) - } - }) - - t.Run("no wait when disabled or when nothing will be retried", func(t *testing.T) { - for _, cfg := range []*Config{ - {MaxRetries: 3, RetryBackoff: -1}, - {MaxRetries: 3, RetryBackoff: time.Hour}, // used with spent below - } { - ds := []amqp.Delivery{fresh} - if cfg.RetryBackoff > 0 { - ds = []amqp.Delivery{spent} - } - d, err := elapsed(cfg, ds...) - if err != nil || d > 100*time.Millisecond { - t.Fatalf("cfg %+v: waited %v (err %v), want none", cfg, d, err) - } - } - }) - - t.Run("a batch waits once, for its longest need", func(t *testing.T) { - twice := amqp.Delivery{Headers: amqp.Table{"x-retry-count": int64(1)}} // needs 2*base - d, err := elapsed(&Config{MaxRetries: 3, RetryBackoff: 30 * time.Millisecond}, fresh, twice, fresh, spent) - if err != nil || d < 60*time.Millisecond || d > 500*time.Millisecond { - t.Fatalf("waited %v (err %v), want about 60ms", d, err) - } - }) - - t.Run("returns when the context ends", func(t *testing.T) { - cctx, cancel := context.WithCancel(ctx) - time.AfterFunc(20*time.Millisecond, cancel) - start := time.Now() - err := waitBeforeRetry(cctx, &Config{MaxRetries: 3, RetryBackoff: time.Hour}, "orders", fresh) - if !errors.Is(err, context.Canceled) || time.Since(start) > time.Second { - t.Fatalf("err = %v after %v, want context.Canceled promptly", err, time.Since(start)) - } - }) -} - -func TestSettleFailure_InterruptedWaitLeavesMessageUnacked(t *testing.T) { - c := &Consumer{ - client: &Client{config: &Config{MaxRetries: 3, RetryBackoff: time.Hour}}, - logger: discardLogger(), - } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - acker := &fakeAcker{} - c.settleFailure(ctx, newDelivery(acker, nil), "orders", errors.New("db down")) - expectCalls(t, acker.calls) // untouched: closing the channel redelivers it -} - -// ---- MaxRetries semantics -------------------------------------------------------- - -func TestNegativeMaxRetriesMeansNoRetries(t *testing.T) { - cfg := &Config{URL: "amqp://localhost", MaxRetries: -1} - cfg.ApplyDefaults() - if cfg.MaxRetries != -1 { - t.Fatalf("ApplyDefaults must keep an explicit negative MaxRetries, got %d", cfg.MaxRetries) - } - if err := cfg.Validate(); err != nil { - t.Fatalf("negative MaxRetries must validate: %v", err) - } - - acker, pub := &fakeAcker{}, &fakeRepublisher{} - handleFailedDelivery(context.Background(), cfg, discardLogger(), pub.publish, newDelivery(acker, nil), "orders") - expectCalls(t, acker.calls, ackCall{op: "reject"}) // first failure is already final - if len(pub.sent) != 0 { - t.Fatalf("nothing may be republished, got %d", len(pub.sent)) - } -} - func TestApplyDefaults_ExplicitZeroMaxRetriesIsTheDefault(t *testing.T) { cfg := &Config{MaxRetries: 0, RetryBackoff: -1} cfg.ApplyDefaults() @@ -640,40 +298,3 @@ func TestIsBrokerRejection(t *testing.T) { t.Error("transport errors are not rejections") } } - -// ---- mixed retry headers ---------------------------------------------------------------- - -// RetryEnabled may be toggled between deploys, leaving a message with several -// counters. The largest wins, so a message is never retried more than -// MaxRetries times in total, and the republished copy continues from it. -func TestRetryCount_MixedHeadersNeverUndercount(t *testing.T) { - mixed := amqp.Table{ - "x-death": []any{amqp.Table{"queue": "orders", "count": int64(1)}}, - "x-retry-count": int64(2), - "x-delivery-count": int64(1), - } - if got := getRetryCount(amqp.Delivery{Headers: mixed}, "orders"); got != 2 { - t.Fatalf("getRetryCount = %d, want 2 (the largest)", got) - } - - acker, pub := &fakeAcker{}, &fakeRepublisher{} - handleFailedDelivery(context.Background(), &Config{MaxRetries: 4}, discardLogger(), pub.publish, newDelivery(acker, mixed), "orders") - next := pub.sent[0].d.Headers - if next["x-retry-count"] != int64(3) { - t.Fatalf("copy continues from the largest counter: x-retry-count = %v, want 3", next["x-retry-count"]) - } - if _, ok := next["x-delivery-count"]; ok { - t.Fatal("x-delivery-count is broker-managed and must not be republished") - } - if _, ok := next["x-death"]; !ok { - t.Fatal("x-death history must be kept") - } - - // At the limit it parks, whichever counter got it there. - at := amqp.Table{"x-delivery-count": int64(4), "x-retry-count": int64(1)} - acker, pub = &fakeAcker{}, &fakeRepublisher{} - handleFailedDelivery(context.Background(), &Config{MaxRetries: 4, DeadLetterEnabled: true}, discardLogger(), pub.publish, newDelivery(acker, at), "orders") - if len(pub.sent) != 1 || pub.sent[0].queue != "orders.parking-lot" { - t.Fatalf("expected parking, got %+v", pub.sent) - } -} diff --git a/rabbitmq/dead_letter.go b/rabbitmq/dead_letter.go new file mode 100644 index 0000000..75d848b --- /dev/null +++ b/rabbitmq/dead_letter.go @@ -0,0 +1,192 @@ +package rabbitmq + +import ( + "context" + "errors" + "fmt" + "maps" + "strings" + "time" + + amqp "github.com/rabbitmq/amqp091-go" +) + +type ProvisionMode uint8 + +const ( + UseExisting ProvisionMode = iota + Declare +) + +// DeadLetterConfig describes a per-subscription parking destination. A nil +// config disables parking. An empty Queue uses .parking-lot, durable. +// Queue.Args accepts x-message-ttl, x-max-length-bytes and x-overflow; capacity +// limits must explicitly use reject-publish or drop-head (which deletes data). +// QueueType defaults to quorum. Exchange, when set, must be durable and direct; +// its binding uses RoutingKey (defaults to Queue.Name). +type DeadLetterConfig struct { + Queue QueueConfig + QueueType QueueType + Exchange *ExchangeConfig + RoutingKey string + Provision ProvisionMode + Timeout time.Duration + // ErrorFormatter is opt-in; by default no error message leaves the service. + ErrorFormatter func(error) string +} + +func (d *DeadLetterConfig) normalized(source string) *DeadLetterConfig { + if d == nil { + return nil + } + out := *d + if out.Queue.Name == "" { + out.Queue.Name = source + parkingLotSuffix + out.Queue.Durable = true + } + out.Queue.Args = maps.Clone(d.Queue.Args) + if out.Exchange != nil { + e := *out.Exchange + e.Args = maps.Clone(e.Args) + out.Exchange = &e + } + if out.QueueType == "" { + out.QueueType = QueueTypeQuorum + } + if out.RoutingKey == "" { + out.RoutingKey = out.Queue.Name + } + if out.Timeout == 0 { + out.Timeout = 10 * time.Second + } + return &out +} + +func (d *DeadLetterConfig) validate(source string) error { + if d == nil { + return nil + } + if strings.TrimSpace(d.Queue.Name) == "" || d.Queue.Name == source || !d.Queue.Durable || d.Queue.AutoDelete || d.Queue.Exclusive || d.Queue.NoWait { + return errors.New("dead-letter queue must be named, durable, distinct from source, and neither exclusive nor auto-delete/no-wait") + } + if d.QueueType != QueueTypeQuorum && d.QueueType != QueueTypeClassic { + return errors.New("invalid dead-letter queue type") + } + if d.Provision > Declare || d.Timeout <= 0 { + return errors.New("invalid dead-letter provisioning or timeout") + } + if d.Exchange != nil && (d.Exchange.Name == "" || d.Exchange.Kind != "direct" || !d.Exchange.Durable || d.Exchange.AutoDelete || d.Exchange.Internal || d.Exchange.NoWait) { + return errors.New("dead-letter exchange must be named, durable and direct") + } + if d.Exchange == nil && d.RoutingKey != d.Queue.Name { + return errors.New("default-exchange routing key must equal dead-letter queue name") + } + args := d.Queue.Args + if _, length := args["x-max-length"]; length { + if err := validateOverflow(args); err != nil { + return err + } + } + if _, bytes := args["x-max-length-bytes"]; bytes { + if err := validateOverflow(args); err != nil { + return err + } + } + if kind, ok := args["x-queue-type"]; ok && kind != string(d.QueueType) { + return errors.New("conflicting dead-letter queue type") + } + if _, loop := args["x-dead-letter-exchange"]; loop { + return errors.New("parking queues must not automatically dead-letter messages again") + } + return nil +} + +func validateOverflow(args map[string]any) error { + if v := args["x-overflow"]; v != "reject-publish" && v != "drop-head" { + return errors.New("bounded dead-letter queues require an explicit x-overflow policy") + } + return nil +} + +func (c *Client) prepareDeadLetter(ctx context.Context, d *DeadLetterConfig) error { + if d == nil { + return nil + } + ctx, cancel := context.WithTimeout(ctx, d.Timeout) + defer cancel() + return c.withTransferChannel(ctx, func(ch *amqp.Channel) error { + args := maps.Clone(d.Queue.Args) + if args == nil { + args = map[string]any{} + } + args["x-queue-type"] = string(d.QueueType) + q := d.Queue + if d.Provision == UseExisting { + if _, err := ch.QueueDeclarePassive(q.Name, q.Durable, false, false, false, args); err != nil { + return err + } + } + // The active idempotent declaration checks equivalence; a passive + // declaration alone only checks existence in AMQP 0-9-1. + if _, err := ch.QueueDeclare(q.Name, q.Durable, false, false, false, args); err != nil { + return err + } + if d.Exchange == nil { + return nil + } + e := d.Exchange + if d.Provision == UseExisting { + if err := ch.ExchangeDeclarePassive(e.Name, e.Kind, e.Durable, false, false, false, e.Args); err != nil { + return err + } + } + if err := declareExchangeOn(ch, *e); err != nil { + return err + } + return ch.QueueBind(q.Name, d.RoutingKey, e.Name, false, nil) + }) +} + +func (c *Client) park(ctx context.Context, cfg *DeadLetterConfig, d amqp.Delivery, source string, failure processingResult) error { + ctx, cancel := context.WithTimeout(ctx, cfg.Timeout) + defer cancel() + message := publishingFrom(d) + message.Headers = maps.Clone(message.Headers) + if message.Headers == nil { + message.Headers = amqp.Table{} + } + for key := range message.Headers { + if strings.HasPrefix(key, "fiddle.dlq.") { + delete(message.Headers, key) + } + } + message.Headers["fiddle.dlq.source_queue"] = source + message.Headers["fiddle.dlq.source_exchange"] = d.Exchange + message.Headers["fiddle.dlq.source_routing_key"] = d.RoutingKey + if count, ok := message.Headers["x-delivery-count"]; ok { + message.Headers["fiddle.dlq.source_delivery_count"] = count + delete(message.Headers, "x-delivery-count") + } + message.Headers["fiddle.dlq.message_id"] = d.MessageId + message.Headers["fiddle.dlq.failure_kind"] = failure.kind.String() + message.Headers["fiddle.dlq.attempts"] = int64(failure.attempts) + message.Headers["fiddle.dlq.failed_at"] = time.Now().UTC().Format(time.RFC3339Nano) + if cfg.ErrorFormatter != nil { + if detail := cfg.ErrorFormatter(failure.err); detail != "" { + message.Headers["fiddle.dlq.error"] = detail + } + } + // Source TTL must not expire a parked message before it can be inspected. + if d.Expiration != "" { + message.Headers["fiddle.dlq.source_expiration"] = d.Expiration + } + message.Expiration = "" + exchange := "" + if cfg.Exchange != nil { + exchange = cfg.Exchange.Name + } + if err := c.transfer(ctx, exchange, cfg.RoutingKey, message); err != nil { + return fmt.Errorf("dead-letter transfer to %s: %w", cfg.Queue.Name, errors.Join(failure.paused(), err)) + } + return nil +} diff --git a/rabbitmq/delivery_test.go b/rabbitmq/delivery_test.go new file mode 100644 index 0000000..6be7443 --- /dev/null +++ b/rabbitmq/delivery_test.go @@ -0,0 +1,172 @@ +package rabbitmq + +import ( + "context" + "errors" + "testing" + "time" + + amqp "github.com/rabbitmq/amqp091-go" +) + +func TestSettlementPreservesOriginalOnFailure(t *testing.T) { + boom := errors.New("failed to read cards") + for _, tc := range []struct { + name string + failure processingResult + transferErr error + publishes, acks int + }{ + {"success", processingResult{}, nil, 0, 1}, + {"unknown", processingResult{err: boom, kind: UnknownFailure, attempts: 3}, nil, 0, 0}, + {"outage", processingResult{err: boom, kind: DependencyUnavailable, attempts: 1}, nil, 0, 0}, + {"parked", processingResult{err: boom, kind: PermanentFailure, attempts: 1, park: true}, nil, 1, 1}, + {"unroutable", processingResult{err: boom, kind: PermanentFailure, attempts: 1, park: true}, ErrUnroutable, 1, 0}, + {"unconfirmed", processingResult{err: boom, kind: PermanentFailure, attempts: 1, park: true}, ErrTransferUnconfirmed, 1, 0}, + {"timeout", processingResult{err: boom, kind: PermanentFailure, attempts: 1, park: true}, context.DeadlineExceeded, 1, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + acker := &fakeAcker{} + publishes := 0 + err := settleProcessed(newDelivery(acker, nil), tc.failure, func() error { + if len(acker.calls) != 0 { + t.Fatal("acknowledged before transfer") + } + publishes++ + return tc.transferErr + }) + if publishes != tc.publishes || len(acker.calls) != tc.acks { + t.Fatalf("publishes=%d calls=%v err=%v", publishes, acker.calls, err) + } + for _, call := range acker.calls { + if call.op != "ack" || call.multiple { + t.Fatalf("unsafe settlement: %+v", call) + } + } + if tc.acks == 0 && err == nil { + t.Fatal("unsettled failure must stop consumption") + } + }) + } +} + +func TestTransferReturnWinsOverAcknowledgement(t *testing.T) { + // Both channels are ready: select may choose ack first. Repeat to exercise + // both branches; an ack never masks RabbitMQ's preceding basic.return. + for range 200 { + returned := make(chan amqp.Return, 1) + confirmed := make(chan amqp.Confirmation, 1) + returned <- amqp.Return{ReplyCode: 312, ReplyText: "NO_ROUTE"} + confirmed <- amqp.Confirmation{DeliveryTag: 1, Ack: true} + if err := awaitTransfer(context.Background(), returned, confirmed); !errors.Is(err, ErrUnroutable) { + t.Fatalf("unroutable publication accepted: %v", err) + } + } +} + +func TestTransferConfirmationFailures(t *testing.T) { + for _, tc := range []struct { + name string + confirmation amqp.Confirmation + wantErr bool + }{ + {"ack", amqp.Confirmation{DeliveryTag: 1, Ack: true}, false}, + {"nack", amqp.Confirmation{DeliveryTag: 1, Ack: false}, true}, + {"unexpected-tag", amqp.Confirmation{DeliveryTag: 2, Ack: true}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + confirmed := make(chan amqp.Confirmation, 1) + confirmed <- tc.confirmation + err := awaitTransfer(context.Background(), make(chan amqp.Return, 1), confirmed) + if (err != nil) != tc.wantErr { + t.Fatalf("err=%v", err) + } + }) + } + closed := make(chan amqp.Confirmation) + close(closed) + if !errors.Is(awaitTransfer(context.Background(), make(chan amqp.Return), closed), ErrTransferUnconfirmed) { + t.Fatal("closed confirmation stream accepted") + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if !errors.Is(awaitTransfer(ctx, make(chan amqp.Return), make(chan amqp.Confirmation)), context.Canceled) { + t.Fatal("cancelled transfer did not stop") + } +} + +func TestDeadLetterQueueConfiguration(t *testing.T) { + d := (&DeadLetterConfig{}).normalized("cards") + if d.Queue.Name != "cards.parking-lot" || !d.Queue.Durable || d.validate("cards") != nil { + t.Fatalf("invalid defaults: %+v", d) + } + d.Queue.Name = "cards" + if d.validate("cards") == nil { + t.Fatal("source and dead-letter queue must differ") + } + d = (&DeadLetterConfig{Queue: QueueConfig{Name: "cards.failed", Durable: true, Args: map[string]any{"x-max-length-bytes": int64(1024)}}}).normalized("cards") + if d.validate("cards") == nil { + t.Fatal("implicit overflow policy accepted") + } + d.Queue.Args["x-overflow"] = "reject-publish" + if d.validate("cards") != nil { + t.Fatal("explicit safe overflow rejected") + } + d.Provision = ProvisionMode(99) + if d.validate("cards") == nil { + t.Fatal("invalid provisioning mode accepted") + } +} + +func TestBatchFailureNeverAcknowledgesLaterMessages(t *testing.T) { + first, second := &fakeAcker{}, &fakeAcker{} + bc := NewBatchConsumer(nil, nil, 2, time.Second) + bc.policy = quickPolicy(DependencyUnavailable) + b := &batcher{bc: bc, queue: "cards", pending: []amqp.Delivery{newDelivery(first, nil), newDelivery(second, nil)}, handler: func(context.Context, []amqp.Delivery) error { return errors.New("service down") }} + if !errors.Is(b.flush(context.Background()), ErrConsumerPaused) { + t.Fatal("batch failure did not stop consumption") + } + if len(first.calls)+len(second.calls) != 0 { + t.Fatal("failed batch acknowledged input") + } + bc.policy = quickPolicy(UnknownFailure) + b.handler = func(context.Context, []amqp.Delivery) error { return nil } + if err := b.flush(context.Background()); err != nil { + t.Fatal(err) + } + for _, a := range []*fakeAcker{first, second} { + if len(a.calls) != 1 || a.calls[0].multiple { + t.Fatalf("unsafe batch ack: %+v", a.calls) + } + } +} + +func TestValidatorFailureWithoutDLQStopsBatch(t *testing.T) { + bc := NewBatchConsumer(nil, nil, 10, time.Second, WithBatchValidator(ValidJSON)) + b := &batcher{bc: bc, queue: "cards"} + a := &fakeAcker{} + d := newDelivery(a, nil) + d.Body = []byte("broken json") + b.add(context.Background(), d) + if !errors.Is(b.err, ErrConsumerPaused) || len(a.calls) != 0 { + t.Fatalf("invalid input lost: err=%v calls=%v", b.err, a.calls) + } +} + +func TestLegacyBrokerRetryLoopRejected(t *testing.T) { + cfg := NewDefaultConfig() + cfg.URL = "amqp://localhost" + cfg.RetryEnabled = true + if cfg.Validate() == nil { + t.Fatal("broker retry loop accepted") + } +} + +func TestReconnectWaitStopsWhenClientCloses(t *testing.T) { + closed := make(chan struct{}) + close(closed) + c := &Consumer{client: &Client{closeChan: closed}} + if err := c.waitForReconnect(context.Background()); !errors.Is(err, ErrClientClosed) { + t.Fatalf("closed client did not stop reconnect wait: %v", err) + } +} diff --git a/rabbitmq/failure.go b/rabbitmq/failure.go new file mode 100644 index 0000000..a2b15e8 --- /dev/null +++ b/rabbitmq/failure.go @@ -0,0 +1,228 @@ +package rabbitmq + +import ( + "context" + "errors" + "fmt" + "math/rand/v2" + "time" +) + +// FailureKind describes an application processing failure, not a broker failure. +type FailureKind uint8 + +const ( + UnknownFailure FailureKind = iota + RetryableFailure + PermanentFailure + DependencyUnavailable + ConfigurationFailure +) + +func (k FailureKind) String() string { + switch k { + case RetryableFailure: + return "retryable" + case PermanentFailure: + return "permanent" + case DependencyUnavailable: + return "dependency_unavailable" + case ConfigurationFailure: + return "configuration" + default: + return "unknown" + } +} + +// ExhaustedAction applies to explicitly retryable failures only. Unknown +// failures always stop consumption; a DLQ is never a reason to discard them. +type ExhaustedAction uint8 + +const ( + StopConsumer ExhaustedAction = iota + DeadLetter +) + +// RetryPolicy is optional. A nil policy allows three retries, with jittered +// exponential backoff and a ten-second total budget, then stops consumption. +// A non-nil policy's MaxRetries is literal: zero disables retries. +// Handlers and classifier callbacks must respect context deadlines / not block. +type RetryPolicy struct { + Classify func(error) FailureKind + MaxRetries int + InitialBackoff time.Duration + MaxBackoff time.Duration + MaxElapsedTime time.Duration + OnExhausted ExhaustedAction +} + +var ErrConsumerPaused = errors.New("consumer paused; message preserved") + +// ProcessingError preserves the cause and describes why consumption stopped. +// Restart with backoff or RunWithRecovery; never restart in an immediate loop. +type ProcessingError struct { + Kind FailureKind + Attempts int + Err error +} + +func (e *ProcessingError) Error() string { + return fmt.Sprintf("%s: %s after %d attempts: %v", ErrConsumerPaused, e.Kind, e.Attempts, e.Err) +} +func (e *ProcessingError) Unwrap() error { return e.Err } +func (e *ProcessingError) Is(target error) bool { return target == ErrConsumerPaused } + +func (p *RetryPolicy) normalized() RetryPolicy { + var out RetryPolicy + if p == nil { + out.MaxRetries = 3 + } else { + out = *p + } + if out.InitialBackoff == 0 { + out.InitialBackoff = 100 * time.Millisecond + } + if out.MaxBackoff == 0 { + out.MaxBackoff = 5 * time.Second + } + if out.MaxElapsedTime == 0 { + out.MaxElapsedTime = 10 * time.Second + } + return out +} + +func (p RetryPolicy) validate(hasDLQ bool) error { + if p.MaxRetries < 0 || p.InitialBackoff < 0 || p.MaxBackoff < p.InitialBackoff || p.MaxElapsedTime <= 0 { + return errors.New("invalid retry limits or time budget") + } + if p.OnExhausted > DeadLetter { + return errors.New("invalid exhausted action") + } + if p.OnExhausted == DeadLetter && !hasDLQ { + return errors.New("dead-letter exhaustion requires DeadLetterConfig") + } + return nil +} + +type processingResult struct { + err error + kind FailureKind + attempts int + park bool +} + +func (r processingResult) paused() error { + return &ProcessingError{Kind: r.kind, Attempts: r.attempts, Err: r.err} +} + +// process retries in place. It never publishes a replacement or settles input. +func (p RetryPolicy) process(ctx context.Context, handler func(context.Context) error) processingResult { + budget, cancel := context.WithTimeout(ctx, p.MaxElapsedTime) + defer cancel() + var result processingResult + delay := min(p.InitialBackoff, p.MaxBackoff) + for { + if err := budget.Err(); err != nil { + result.err = errors.Join(result.err, err) + result.park = ctx.Err() == nil && result.kind == RetryableFailure && p.OnExhausted == DeadLetter + return result + } + result.attempts++ + result.err = handler(budget) + if err := ctx.Err(); err != nil { + result.err = err + result.park = false + return result + } + if result.err == nil { + return result + } + result.kind = UnknownFailure + if p.Classify != nil { + result.kind = p.Classify(result.err) + } + if result.kind > ConfigurationFailure { + result.kind = UnknownFailure + } + switch result.kind { + case PermanentFailure: + result.park = true + return result + case DependencyUnavailable, ConfigurationFailure: + return result + } + if result.attempts > p.MaxRetries || budget.Err() != nil { + result.park = result.kind == RetryableFailure && p.OnExhausted == DeadLetter + return result + } + if err := waitDelay(budget, time.Duration(float64(delay)*(0.5+rand.Float64()*0.5))); err != nil { + result.err = errors.Join(result.err, err) + result.park = ctx.Err() == nil && result.kind == RetryableFailure && p.OnExhausted == DeadLetter + return result + } + if delay >= p.MaxBackoff/2 { + delay = p.MaxBackoff + } else { + delay *= 2 + } + } +} + +func waitDelay(ctx context.Context, delay time.Duration) error { + if err := ctx.Err(); err != nil { + return err + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return ctx.Err() + } +} + +// RecoveryPolicy gates restarts after DependencyUnavailable. Probe must honor +// ctx. No messages are fetched while probing. Defaults: 30s interval, 5s timeout. +type RecoveryPolicy struct { + Probe func(context.Context) error + Interval time.Duration + Timeout time.Duration +} + +// RunWithRecovery runs consume, probing only after a classified dependency +// outage. consume must release its resources on return and create a fresh +// consumer/client on each invocation. Other failures return for operator action. +// ctx bounds the whole recovery loop; cancellation never starts another consumer. +func RunWithRecovery(ctx context.Context, recovery RecoveryPolicy, consume func(context.Context) error) error { + if recovery.Interval == 0 { + recovery.Interval = 30 * time.Second + } + if recovery.Timeout == 0 { + recovery.Timeout = 5 * time.Second + } + if recovery.Interval < 0 || recovery.Timeout < 0 || consume == nil { + return errors.New("invalid recovery policy") + } + for { + if err := ctx.Err(); err != nil { + return err + } + err := consume(ctx) + paused, ok := errors.AsType[*ProcessingError](err) + if !ok || paused.Kind != DependencyUnavailable || recovery.Probe == nil { + return err + } + for { + if err := waitDelay(ctx, recovery.Interval); err != nil { + return err + } + probeCtx, cancel := context.WithTimeout(ctx, recovery.Timeout) + probeErr := errors.Join(recovery.Probe(probeCtx), probeCtx.Err()) + cancel() + if probeErr == nil { + break + } + } + } +} diff --git a/rabbitmq/failure_test.go b/rabbitmq/failure_test.go new file mode 100644 index 0000000..2cbf2d5 --- /dev/null +++ b/rabbitmq/failure_test.go @@ -0,0 +1,157 @@ +package rabbitmq + +import ( + "context" + "errors" + "testing" + "time" +) + +func quickPolicy(kind FailureKind) RetryPolicy { + return RetryPolicy{Classify: func(error) FailureKind { return kind }, MaxRetries: 2, + InitialBackoff: time.Millisecond, MaxBackoff: 2 * time.Millisecond, MaxElapsedTime: time.Second} +} + +func TestFailureClassificationControlsRetries(t *testing.T) { + boom := errors.New("application failure") + for _, tc := range []struct { + kind FailureKind + attempts int + park bool + }{ + {UnknownFailure, 3, false}, {RetryableFailure, 3, true}, + {PermanentFailure, 1, true}, {DependencyUnavailable, 1, false}, {ConfigurationFailure, 1, false}, + } { + t.Run(tc.kind.String(), func(t *testing.T) { + p := quickPolicy(tc.kind) + p.OnExhausted = DeadLetter + calls := 0 + got := p.process(context.Background(), func(context.Context) error { calls++; return boom }) + if calls != tc.attempts || got.attempts != calls || got.park != tc.park || !errors.Is(got.paused(), boom) || !errors.Is(got.paused(), ErrConsumerPaused) { + t.Fatalf("calls=%d result=%+v", calls, got) + } + }) + } +} + +func TestRetryBudgetAndCancellation(t *testing.T) { + boom := errors.New("temporary failure") + p := quickPolicy(RetryableFailure) + p.MaxRetries = 1000 + p.MaxElapsedTime = 15 * time.Millisecond + p.InitialBackoff, p.MaxBackoff = time.Second, time.Second + start := time.Now() + got := p.process(context.Background(), func(context.Context) error { return boom }) + if got.attempts != 1 || !errors.Is(got.err, boom) || !errors.Is(got.err, context.DeadlineExceeded) || time.Since(start) > time.Second { + t.Fatalf("time budget did not stop retry wait: %+v", got) + } + ctx, cancel := context.WithCancel(context.Background()) + got = p.process(ctx, func(context.Context) error { cancel(); return boom }) + if !errors.Is(got.err, context.Canceled) || got.park { + t.Fatalf("cancelled input must remain unsettled: %+v", got) + } + called := false + got = p.process(ctx, func(context.Context) error { called = true; return nil }) + if called || !errors.Is(got.err, context.Canceled) { + t.Fatal("cancelled context invoked handler") + } +} + +func TestRetrySuccessAndExplicitZero(t *testing.T) { + p := quickPolicy(RetryableFailure) + calls := 0 + got := p.process(context.Background(), func(context.Context) error { + calls++ + if calls < 3 { + return errors.New("not yet") + } + return nil + }) + if got.err != nil || calls != 3 { + t.Fatalf("result=%+v calls=%d", got, calls) + } + p.MaxRetries = 0 + got = p.process(context.Background(), func(context.Context) error { return errors.New("failure") }) + if got.attempts != 1 { + t.Fatalf("zero means no retries: %+v", got) + } + var defaults *RetryPolicy + if defaults.normalized().MaxRetries != 3 { + t.Fatal("nil policy lost default retry budget") + } +} + +func TestFailurePolicyValidation(t *testing.T) { + p := quickPolicy(RetryableFailure) + p.OnExhausted = DeadLetter + if p.validate(false) == nil || p.validate(true) != nil { + t.Fatal("parking requires configured destination") + } + p.MaxRetries = -1 + if p.validate(true) == nil { + t.Fatal("negative retry budget accepted") + } +} + +func TestRecoveryProbesDoNotConsumeDuringOutage(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + runs, probes := 0, 0 + err := RunWithRecovery(ctx, RecoveryPolicy{ + Interval: time.Millisecond, Timeout: time.Second, + Probe: func(context.Context) error { + probes++ + if probes < 4 { + return errors.New("still down") + } + return nil + }, + }, func(context.Context) error { + runs++ + if runs == 1 { + return &ProcessingError{Kind: DependencyUnavailable, Attempts: 1, Err: errors.New("service down")} + } + if probes != 4 { + t.Fatal("consumed before successful recovery probe") + } + return nil + }) + if err != nil || runs != 2 || probes != 4 { + t.Fatalf("err=%v runs=%d probes=%d", err, runs, probes) + } +} + +func TestRecoveryDoesNotRestartUnknownFailures(t *testing.T) { + probes, runs := 0, 0 + err := RunWithRecovery(context.Background(), RecoveryPolicy{Probe: func(context.Context) error { probes++; return nil }}, func(context.Context) error { + runs++ + return &ProcessingError{Kind: UnknownFailure, Attempts: 1, Err: errors.New("unknown")} + }) + if !errors.Is(err, ErrConsumerPaused) || probes != 0 || runs != 1 { + t.Fatalf("err=%v probes=%d runs=%d", err, probes, runs) + } +} + +func TestRecoveryCancellationStopsProbesAndRestarts(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + runs := 0 + err := RunWithRecovery(ctx, RecoveryPolicy{Interval: time.Millisecond, Probe: func(ctx context.Context) error { cancel(); return ctx.Err() }}, func(context.Context) error { + runs++ + return &ProcessingError{Kind: DependencyUnavailable, Err: errors.New("down")} + }) + if !errors.Is(err, context.Canceled) || runs != 1 { + t.Fatalf("err=%v runs=%d", err, runs) + } +} + +func TestElapsedBudgetUsesExplicitExhaustionPolicy(t *testing.T) { + p := quickPolicy(RetryableFailure) + p.MaxRetries = 100 + p.MaxElapsedTime = 10 * time.Millisecond + p.InitialBackoff, p.MaxBackoff = time.Second, time.Second + p.OnExhausted = DeadLetter + result := p.process(context.Background(), func(context.Context) error { return errors.New("temporary") }) + if !result.park || result.kind != RetryableFailure { + t.Fatalf("elapsed budget ignored explicit exhaustion policy: %+v", result) + } +} diff --git a/rabbitmq/integration_test.go b/rabbitmq/integration_test.go new file mode 100644 index 0000000..10bd5d6 --- /dev/null +++ b/rabbitmq/integration_test.go @@ -0,0 +1,82 @@ +package rabbitmq + +import ( + "context" + "errors" + "fmt" + "os" + "testing" + "time" + + amqp "github.com/rabbitmq/amqp091-go" +) + +// Optional broker test; no Docker is required. Point FIDDLE_RABBITMQ_URL at a +// disposable broker/vhost whose user may declare and delete test queues. +func TestIntegrationMissingParkingQueuePreservesOriginal(t *testing.T) { + url := os.Getenv("FIDDLE_RABBITMQ_URL") + if url == "" { + t.Skip("set FIDDLE_RABBITMQ_URL for broker verification") + } + cfg := NewDefaultConfig() + cfg.URL = url + cfg.TransferTimeout = 3 * time.Second + // Internal transfers must be reliable even with public confirms disabled. + cfg.PublisherConfirms = false + client, err := NewClient(cfg, discardLogger()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = client.Close() }() + admin, err := client.CreateConsumerChannel() + if err != nil { + t.Fatal(err) + } + defer func() { _ = admin.Close() }() + source := fmt.Sprintf("fiddle-test-%d", time.Now().UnixNano()) + failed := source + ".failed" + if _, err = admin.QueueDeclare(source, false, false, false, false, nil); err != nil { + t.Fatal(err) + } + defer func() { + _, _ = admin.QueueDelete(source, false, false, false) + _, _ = admin.QueueDelete(failed, false, false, false) + }() + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if err = admin.Confirm(false); err != nil { + t.Fatal(err) + } + body := []byte(`{"card":"test"}`) + dc, err := admin.PublishWithDeferredConfirmWithContext(ctx, "", source, true, false, amqp.Publishing{Body: body, DeliveryMode: amqp.Persistent}) + if err != nil { + t.Fatal(err) + } + if err = waitConfirm(ctx, dc); err != nil { + t.Fatal(err) + } + calls := 0 + err = NewConsumer(client, discardLogger()).StartConsumer(ctx, ConsumeOptions{ + QueueName: source, + DeadLetter: &DeadLetterConfig{Queue: QueueConfig{Name: failed, Durable: true}, QueueType: QueueTypeClassic, Provision: Declare}, + }, func(context.Context, amqp.Delivery) error { + calls++ + if _, deleteErr := admin.QueueDelete(failed, false, false, false); deleteErr != nil { + return deleteErr + } + return ErrPoisonMessage + }) + if !errors.Is(err, ErrUnroutable) || calls != 1 { + t.Fatalf("err=%v handler_calls=%d", err, calls) + } + delivery, ok, err := admin.Get(source, false) + if err != nil || !ok { + t.Fatalf("original was lost: present=%v err=%v", ok, err) + } + if string(delivery.Body) != string(body) { + t.Fatalf("original payload changed: %q", delivery.Body) + } + if err = delivery.Ack(false); err != nil { + t.Fatal(err) + } +} diff --git a/rabbitmq/transfer.go b/rabbitmq/transfer.go new file mode 100644 index 0000000..98a029d --- /dev/null +++ b/rabbitmq/transfer.go @@ -0,0 +1,124 @@ +package rabbitmq + +import ( + "context" + "errors" + "fmt" + "net" + "time" + + amqp "github.com/rabbitmq/amqp091-go" +) + +var ( + ErrUnroutable = errors.New("rabbitmq: transfer was returned as unroutable") + ErrTransferUnconfirmed = errors.New("rabbitmq: transfer was not confirmed") +) + +// withTransferChannel isolates internal transfers from asynchronous public +// publishes. One connection/channel per operation also allows cancellation to +// close its socket: amqp091-go's publish context does not interrupt socket I/O. +// The semaphore bounds connections, waiters are bounded by the caller deadline. +func (c *Client) withTransferChannel(ctx context.Context, fn func(*amqp.Channel) error) error { + limit := c.config.TransferTimeout + if limit <= 0 { + limit = 10 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, limit) + defer cancel() + if c.closing() { + return ErrClientClosed + } + select { + case c.transferSlots <- struct{}{}: + defer func() { <-c.transferSlots }() + case <-c.closeChan: + return ErrClientClosed + case <-ctx.Done(): + return ctx.Err() + } + var socket net.Conn + var stopIO func() bool + defer func() { + if stopIO != nil { + stopIO() + } + if socket != nil { + _ = socket.Close() + } + }() + config := amqp.Config{ + TLSClientConfig: c.config.TLSConfig, + Heartbeat: c.config.Heartbeat, + Properties: amqp.Table{"connection_name": c.config.ConnectionName + "-transfer"}, + Dial: func(network, address string) (net.Conn, error) { + conn, err := (&net.Dialer{}).DialContext(ctx, network, address) + if err != nil { + return nil, err + } + socket = conn + if deadline, ok := ctx.Deadline(); ok { + if err := conn.SetDeadline(deadline); err != nil { + _ = conn.Close() + return nil, err + } + } + stopIO = context.AfterFunc(ctx, func() { _ = conn.Close() }) + return conn, nil + }, + } + conn, err := amqp.DialConfig(c.config.URL, config) + if err != nil { + return err + } + ch, err := conn.Channel() + if err != nil { + return err + } + return fn(ch) +} + +func (c *Client) transfer(ctx context.Context, exchange, key string, message amqp.Publishing) error { + return c.withTransferChannel(ctx, func(ch *amqp.Channel) error { + returned := ch.NotifyReturn(make(chan amqp.Return, 1)) + confirmed := ch.NotifyPublish(make(chan amqp.Confirmation, 1)) + if err := ch.Confirm(false); err != nil { + return err + } + message.DeliveryMode = amqp.Persistent + if err := ch.PublishWithContext(ctx, exchange, key, true, false, message); err != nil { + return err + } + return awaitTransfer(ctx, returned, confirmed) + }) +} + +func awaitTransfer(ctx context.Context, returned <-chan amqp.Return, confirmed <-chan amqp.Confirmation) error { + if err := ctx.Err(); err != nil { + return err + } + select { + case <-ctx.Done(): + return ctx.Err() + case r, ok := <-returned: + if !ok { + return ErrTransferUnconfirmed + } + return fmt.Errorf("%w: %d %s", ErrUnroutable, r.ReplyCode, r.ReplyText) + case confirmation, ok := <-confirmed: + if !ok || !confirmation.Ack || confirmation.DeliveryTag != 1 { + return ErrTransferUnconfirmed + } + // RabbitMQ sends basic.return before basic.ack, and amqp091-go enqueues + // them in wire order. Check the buffered return even if select chose ack. + select { + case r, ok := <-returned: + if !ok { + return ErrTransferUnconfirmed + } + return fmt.Errorf("%w: %d %s", ErrUnroutable, r.ReplyCode, r.ReplyText) + default: + return nil + } + } +}