Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
321 lines
7.3 KiB
Go
321 lines
7.3 KiB
Go
// Package broker owns the RabbitMQ topology, confirmed publishing and the
|
|
// consumer loop. Business state never lives here: PostgreSQL is the source of
|
|
// truth for jobs and the outbox.
|
|
package broker
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
)
|
|
|
|
type Config struct {
|
|
URL string
|
|
Exchange string
|
|
DLX string
|
|
Queue string
|
|
DLQ string
|
|
ConnectTimeout time.Duration
|
|
ConfirmTimeout time.Duration
|
|
Heartbeat time.Duration
|
|
Prefetch int
|
|
}
|
|
|
|
type Client struct {
|
|
cfg Config
|
|
|
|
conn *amqp.Connection
|
|
publisher *amqp.Channel
|
|
|
|
mu sync.Mutex
|
|
returns chan amqp.Return
|
|
closed chan *amqp.Error
|
|
}
|
|
|
|
// Dial connects, declares the durable topology idempotently and opens a
|
|
// confirm-mode publisher channel.
|
|
func Dial(cfg Config) (*Client, error) {
|
|
if cfg.URL == "" {
|
|
return nil, errors.New("broker url is empty")
|
|
}
|
|
|
|
conn, err := amqp.DialConfig(cfg.URL, amqp.Config{
|
|
Heartbeat: cfg.Heartbeat,
|
|
Dial: amqp.DefaultDial(cfg.ConnectTimeout),
|
|
Properties: amqp.Table{
|
|
"connection_name": "messenger-relay",
|
|
},
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("dial broker: %w", err)
|
|
}
|
|
|
|
channel, err := conn.Channel()
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
|
|
return nil, fmt.Errorf("open topology channel: %w", err)
|
|
}
|
|
|
|
if err := declareTopology(channel, cfg); err != nil {
|
|
_ = channel.Close()
|
|
_ = conn.Close()
|
|
|
|
return nil, err
|
|
}
|
|
|
|
if err := channel.Close(); err != nil {
|
|
_ = conn.Close()
|
|
|
|
return nil, fmt.Errorf("close topology channel: %w", err)
|
|
}
|
|
|
|
publisher, err := conn.Channel()
|
|
if err != nil {
|
|
_ = conn.Close()
|
|
|
|
return nil, fmt.Errorf("open publisher channel: %w", err)
|
|
}
|
|
|
|
client := &Client{
|
|
cfg: cfg,
|
|
conn: conn,
|
|
publisher: publisher,
|
|
returns: make(chan amqp.Return, 16),
|
|
closed: conn.NotifyClose(make(chan *amqp.Error, 1)),
|
|
}
|
|
|
|
if err := publisher.Confirm(false); err != nil {
|
|
_ = client.Close()
|
|
|
|
return nil, fmt.Errorf("enable publisher confirms: %w", err)
|
|
}
|
|
|
|
publisher.NotifyReturn(client.returns)
|
|
|
|
return client, nil
|
|
}
|
|
|
|
func declareTopology(channel *amqp.Channel, cfg Config) error {
|
|
if err := channel.ExchangeDeclare(cfg.Exchange, "direct", true, false, false, false, nil); err != nil {
|
|
return fmt.Errorf("declare exchange: %w", err)
|
|
}
|
|
|
|
if err := channel.ExchangeDeclare(cfg.DLX, "direct", true, false, false, false, nil); err != nil {
|
|
return fmt.Errorf("declare dlx: %w", err)
|
|
}
|
|
|
|
queue, err := channel.QueueDeclare(cfg.Queue, true, false, false, false, amqp.Table{
|
|
"x-queue-type": "quorum",
|
|
"x-delivery-limit": int32(100),
|
|
"x-delayed-retry-type": "all",
|
|
"x-delayed-retry-min": int32(5000),
|
|
"x-delayed-retry-max": int32(60000),
|
|
"x-dead-letter-exchange": cfg.DLX,
|
|
"x-dead-letter-routing-key": cfg.DLQ,
|
|
"x-dead-letter-strategy": "at-least-once",
|
|
"x-overflow": "reject-publish",
|
|
"x-max-length": int32(100000),
|
|
"x-consumer-timeout": int32(300000),
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("declare job queue: %w", err)
|
|
}
|
|
|
|
if queue.Name != cfg.Queue {
|
|
return fmt.Errorf("broker returned queue %q, want %q", queue.Name, cfg.Queue)
|
|
}
|
|
|
|
if err := channel.QueueBind(cfg.Queue, cfg.Queue, cfg.Exchange, false, nil); err != nil {
|
|
return fmt.Errorf("bind job queue: %w", err)
|
|
}
|
|
|
|
if _, err := channel.QueueDeclare(cfg.DLQ, true, false, false, false, amqp.Table{
|
|
"x-queue-type": "quorum",
|
|
"x-max-length": int32(100000),
|
|
"x-overflow": "reject-publish",
|
|
"x-message-ttl": int32(7 * 24 * 60 * 60 * 1000),
|
|
}); err != nil {
|
|
return fmt.Errorf("declare dlq: %w", err)
|
|
}
|
|
|
|
if err := channel.QueueBind(cfg.DLQ, cfg.DLQ, cfg.DLX, false, nil); err != nil {
|
|
return fmt.Errorf("bind dlq: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) Connected() bool {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
return c.conn != nil && !c.conn.IsClosed()
|
|
}
|
|
|
|
// PublishConfirmed returns only after the broker acknowledged the persistent
|
|
// message. A duplicate publication after a crash is normal and harmless.
|
|
func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error {
|
|
payload, err := message.MarshalPayload()
|
|
if err != nil {
|
|
return fmt.Errorf("marshal job message: %w", err)
|
|
}
|
|
|
|
confirmation, err := c.publisher.PublishWithDeferredConfirmWithContext(
|
|
ctx,
|
|
c.cfg.Exchange,
|
|
routingKey,
|
|
true,
|
|
false,
|
|
amqp.Publishing{
|
|
ContentType: "application/json",
|
|
DeliveryMode: amqp.Persistent,
|
|
MessageId: message.JobID.String(),
|
|
Type: message.Type,
|
|
Timestamp: message.CreatedAt,
|
|
Body: payload,
|
|
},
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("publish job: %w", err)
|
|
}
|
|
|
|
confirmCtx := ctx
|
|
if c.cfg.ConfirmTimeout > 0 {
|
|
var cancel context.CancelFunc
|
|
confirmCtx, cancel = context.WithTimeout(ctx, c.cfg.ConfirmTimeout)
|
|
defer cancel()
|
|
}
|
|
|
|
confirmed, err := confirmation.WaitContext(confirmCtx)
|
|
if err != nil {
|
|
return fmt.Errorf("await publisher confirm: %w", err)
|
|
}
|
|
|
|
if !confirmed {
|
|
return errors.New("broker nacked the job message")
|
|
}
|
|
|
|
// mandatory=true: an unroutable message is returned even though the
|
|
// confirm may still be positive. The topology is declared before publish,
|
|
// so this is a safety net rather than a normal path.
|
|
select {
|
|
case returned := <-c.returns:
|
|
if returned.MessageId == message.JobID.String() {
|
|
return fmt.Errorf("broker returned unroutable message: %s", returned.ReplyText)
|
|
}
|
|
default:
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type Outcome int
|
|
|
|
const (
|
|
Ack Outcome = iota
|
|
Requeue
|
|
Drop
|
|
)
|
|
|
|
type Handler func(ctx context.Context, delivery amqp.Delivery) Outcome
|
|
|
|
// Consume blocks until the context is cancelled or the consumer channel fails.
|
|
// Each call uses its own channel so worker slots do not share prefetch state.
|
|
func (c *Client) Consume(ctx context.Context, handler Handler) error {
|
|
channel, err := c.conn.Channel()
|
|
if err != nil {
|
|
return fmt.Errorf("open consumer channel: %w", err)
|
|
}
|
|
defer channel.Close()
|
|
|
|
if err := channel.Qos(c.cfg.Prefetch, 0, false); err != nil {
|
|
return fmt.Errorf("set qos: %w", err)
|
|
}
|
|
|
|
consumerTag := fmt.Sprintf("messenger-%d", time.Now().UnixNano())
|
|
|
|
deliveries, err := channel.Consume(
|
|
c.cfg.Queue,
|
|
consumerTag,
|
|
false,
|
|
false,
|
|
false,
|
|
false,
|
|
nil,
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("consume: %w", err)
|
|
}
|
|
|
|
done := make(chan struct{})
|
|
defer close(done)
|
|
|
|
go func() {
|
|
select {
|
|
case <-ctx.Done():
|
|
_ = channel.Cancel(consumerTag, false)
|
|
case <-done:
|
|
}
|
|
}()
|
|
|
|
for delivery := range deliveries {
|
|
outcome := safeHandle(ctx, handler, delivery)
|
|
|
|
switch outcome {
|
|
case Ack:
|
|
_ = delivery.Ack(false)
|
|
case Requeue:
|
|
_ = delivery.Nack(false, true)
|
|
case Drop:
|
|
_ = delivery.Nack(false, false)
|
|
}
|
|
|
|
if ctx.Err() != nil {
|
|
// Let unacked deliveries return to the broker on channel close.
|
|
return nil
|
|
}
|
|
}
|
|
|
|
if ctx.Err() != nil {
|
|
return nil
|
|
}
|
|
|
|
return errors.New("consumer channel closed")
|
|
}
|
|
|
|
func safeHandle(ctx context.Context, handler Handler, delivery amqp.Delivery) (outcome Outcome) {
|
|
defer func() {
|
|
if recover() != nil {
|
|
outcome = Requeue
|
|
}
|
|
}()
|
|
|
|
return handler(ctx, delivery)
|
|
}
|
|
|
|
func (c *Client) Close() error {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
if c.publisher != nil {
|
|
_ = c.publisher.Close()
|
|
c.publisher = nil
|
|
}
|
|
|
|
if c.conn != nil {
|
|
err := c.conn.Close()
|
|
c.conn = nil
|
|
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|