266 lines
6.6 KiB
Go
266 lines
6.6 KiB
Go
// Package broker provides confirmed publishing and consumption over certificate-
|
|
// authenticated AMQP. The operator owns topology; PostgreSQL owns business state.
|
|
package broker
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/url"
|
|
"sync"
|
|
"time"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/platform/tlsconfig"
|
|
)
|
|
|
|
type Config struct {
|
|
URL string
|
|
Role string
|
|
Producer bool
|
|
Exchange string
|
|
Queue string
|
|
ConnectTimeout time.Duration
|
|
ConfirmTimeout time.Duration
|
|
Heartbeat time.Duration
|
|
Prefetch int
|
|
}
|
|
|
|
type Client struct {
|
|
cfg Config
|
|
|
|
conn *amqp.Connection
|
|
publisher *amqp.Channel
|
|
|
|
returns chan amqp.Return
|
|
closeOnce sync.Once
|
|
closeErr error
|
|
}
|
|
|
|
// Dial connects using EXTERNAL only. Relay gets a confirm-mode publisher;
|
|
// worker opens consumer channels only when Consume is called.
|
|
func Dial(cfg Config) (*Client, error) {
|
|
endpoint, err := url.Parse(cfg.URL)
|
|
if err != nil || endpoint.Scheme != "amqps" || endpoint.Hostname() == "" || endpoint.User != nil {
|
|
return nil, errors.New("broker: url must be amqps without credentials")
|
|
}
|
|
if endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
|
return nil, errors.New("broker: url query and fragment are not permitted")
|
|
}
|
|
switch cfg.Role {
|
|
case "relay":
|
|
if !cfg.Producer || cfg.Exchange == "" {
|
|
return nil, errors.New("broker: relay requires producer mode and an exchange")
|
|
}
|
|
case "worker":
|
|
if cfg.Producer || cfg.Queue == "" {
|
|
return nil, errors.New("broker: worker requires consumer mode and a queue")
|
|
}
|
|
default:
|
|
return nil, errors.New("broker: role must be relay or worker")
|
|
}
|
|
if cfg.ConnectTimeout <= 0 || cfg.ConnectTimeout > 5*time.Second {
|
|
return nil, errors.New("broker: connect timeout must be positive and at most 5s")
|
|
}
|
|
clientTLS, err := tlsconfig.NewClientFromEnv(endpoint.Hostname())
|
|
if err != nil {
|
|
return nil, fmt.Errorf("configure broker tls: %w", err)
|
|
}
|
|
conn, err := amqp.DialConfig(cfg.URL, amqp.Config{
|
|
Heartbeat: cfg.Heartbeat,
|
|
Dial: amqp.DefaultDial(cfg.ConnectTimeout),
|
|
TLSClientConfig: clientTLS,
|
|
SASL: []amqp.Authentication{&amqp.ExternalAuth{}},
|
|
Properties: amqp.Table{
|
|
"connection_name": "messenger-" + cfg.Role,
|
|
},
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("dial broker: %w", err)
|
|
}
|
|
client := &Client{cfg: cfg, conn: conn}
|
|
if !cfg.Producer {
|
|
return client, nil
|
|
}
|
|
publisher, err := conn.Channel()
|
|
if err != nil {
|
|
return nil, errors.Join(
|
|
fmt.Errorf("open publisher channel: %w", err),
|
|
client.Close(),
|
|
)
|
|
}
|
|
client.publisher = publisher
|
|
client.returns = make(chan amqp.Return, 16)
|
|
if err := publisher.Confirm(false); err != nil {
|
|
return nil, errors.Join(
|
|
fmt.Errorf("enable publisher confirms: %w", err),
|
|
client.Close(),
|
|
)
|
|
}
|
|
publisher.NotifyReturn(client.returns)
|
|
return client, nil
|
|
}
|
|
|
|
func (c *Client) Connected() bool {
|
|
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 {
|
|
if c.cfg.Role != "relay" || !c.cfg.Producer || c.publisher == nil {
|
|
return errors.New("broker: publication is restricted to relay")
|
|
}
|
|
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 if confirmed.
|
|
// The operator must provision bindings before relay startup.
|
|
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 {
|
|
if c.cfg.Role != "worker" || c.cfg.Producer {
|
|
return errors.New("broker: consumption is restricted to worker")
|
|
}
|
|
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.closeOnce.Do(func() {
|
|
// Closing the connection first interrupts consumers and publication.
|
|
// Keep pointers immutable while those operations unwind concurrently.
|
|
if c.conn != nil && !c.conn.IsClosed() {
|
|
c.closeErr = c.conn.CloseDeadline(time.Now().Add(time.Second))
|
|
}
|
|
})
|
|
return c.closeErr
|
|
}
|