Files
mtusi2026lab5/internal/rabbitmq/client.go
T

107 lines
2.3 KiB
Go

package rabbitmq
import (
"context"
"errors"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
const QueueName = "attachments.process.v1"
var (
ErrConnect = errors.New("connect to rabbitmq")
ErrNotRouted = errors.New("rabbitmq message not routed")
ErrNack = errors.New("rabbitmq publish rejected")
ErrPrefetch = errors.New("rabbitmq prefetch must be positive")
)
type Client struct {
conn *amqp.Connection
channel *amqp.Channel
returns <-chan amqp.Return
}
func New(url string) (*Client, error) {
conn, err := amqp.DialConfig(url, amqp.Config{
Dial: amqp.DefaultDial(5 * time.Second),
})
if err != nil {
return nil, ErrConnect
}
channel, err := conn.Channel()
if err != nil {
_ = conn.CloseDeadline(time.Now().Add(time.Second))
return nil, err
}
if _, err := channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil {
_ = conn.CloseDeadline(time.Now().Add(time.Second))
return nil, err
}
if err := channel.Confirm(false); err != nil {
_ = conn.CloseDeadline(time.Now().Add(time.Second))
return nil, err
}
return &Client{
conn: conn,
channel: channel,
returns: channel.NotifyReturn(make(chan amqp.Return, 1)),
}, nil
}
// Publish must not be called concurrently on the same client.
func (c *Client) Publish(ctx context.Context, messageID string, body []byte) error {
if err := ctx.Err(); err != nil {
return err
}
stop := context.AfterFunc(ctx, func() {
_ = c.conn.CloseDeadline(time.Now())
})
defer stop()
confirmation, err := c.channel.PublishWithDeferredConfirm("", QueueName, true, false, amqp.Publishing{
ContentType: "application/json",
DeliveryMode: amqp.Persistent,
MessageId: messageID,
Body: body,
})
if err != nil {
return err
}
ack, err := confirmation.WaitContext(ctx)
if err != nil {
return err
}
if !ack {
return ErrNack
}
select {
case _, ok := <-c.returns:
if !ok {
return amqp.ErrClosed
}
return ErrNotRouted
default:
return nil
}
}
func (c *Client) Consume(ctx context.Context, prefetch int) (<-chan amqp.Delivery, error) {
if prefetch < 1 {
return nil, ErrPrefetch
}
if err := c.channel.Qos(prefetch, 0, false); err != nil {
return nil, err
}
return c.channel.ConsumeWithContext(ctx, QueueName, "", false, false, false, false, nil)
}
func (c *Client) Close() error {
return c.conn.CloseDeadline(time.Now().Add(time.Second))
}