Files
mtusi2026lab5/internal/broker/rabbit.go
T

116 lines
3.0 KiB
Go

// Package broker owns the AMQP connection for one publisher or consumer.
package broker
import (
"context"
"errors"
"net"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const queue = "attachment.jobs"
type link struct {
conn *amqp.Connection
channel *amqp.Channel
}
func open(ctx context.Context, url string) (*link, error) {
conn, err := amqp.DialConfig(url, amqp.Config{Heartbeat: 5 * time.Second, Dial: func(network, addr string) (net.Conn, error) {
d := net.Dialer{Timeout: 3 * time.Second}
c, err := d.DialContext(ctx, network, addr)
if err == nil {
err = c.SetDeadline(time.Now().Add(5 * time.Second))
}
return c, err
}})
// Parse errors can contain the complete connection URL.
if err != nil {
return nil, errors.New("RabbitMQ connection unavailable")
}
l := &link{conn: conn}
l.channel, err = conn.Channel()
if err == nil {
// PostgreSQL limits processing attempts. A broker redelivery can occur
// before PostgreSQL is reachable and must leave the job recoverable.
_, err = l.channel.QueueDeclare(queue, true, false, false, false, amqp.Table{
"x-queue-type": "quorum", "x-delivery-limit": int32(-1),
})
}
if err != nil {
l.Close()
return nil, err
}
return l, nil
}
func (l *link) Close() { _ = l.conn.CloseDeadline(time.Now().Add(time.Second)) }
type Publisher struct {
*link
returned <-chan amqp.Return
}
func NewPublisher(ctx context.Context, url string) (*Publisher, error) {
l, err := open(ctx, url)
if err != nil {
return nil, err
}
if err = l.channel.Confirm(false); err != nil {
l.Close()
return nil, err
}
return &Publisher{l, l.channel.NotifyReturn(make(chan amqp.Return, 1))}, nil
}
// Publish has one in-flight confirm on its channel. An ambiguous result means
// the caller discards this publisher and leaves the outbox row pending.
func (p *Publisher) Publish(ctx context.Context, body []byte) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
stop := context.AfterFunc(ctx, p.Close)
defer stop()
confirmation, err := p.channel.PublishWithDeferredConfirmWithContext(ctx, "", queue, true, false, amqp.Publishing{ContentType: "application/json", DeliveryMode: amqp.Persistent, Body: body})
if err != nil {
return err
}
ok, err := confirmation.WaitContext(ctx)
if err != nil {
return err
}
if !ok {
return errors.New("broker did not confirm publication")
}
// RabbitMQ sends basic.return before the associated publisher confirm.
select {
case <-p.returned:
return errors.New("broker returned publication")
default:
return nil
}
}
type Consumer struct {
*link
Deliveries <-chan amqp.Delivery
}
func NewConsumer(ctx context.Context, url string) (*Consumer, error) {
l, err := open(ctx, url)
if err != nil {
return nil, err
}
if err = l.channel.Qos(1, 0, false); err != nil {
l.Close()
return nil, err
}
d, err := l.channel.ConsumeWithContext(ctx, queue, "", false, false, false, false, nil)
if err != nil {
l.Close()
return nil, err
}
return &Consumer{l, d}, nil
}