forked from mtusi2026/mtusi2026lab7
84 lines
2.4 KiB
Go
84 lines
2.4 KiB
Go
package repositories
|
|
|
|
import (
|
|
"context"
|
|
|
|
"errors"
|
|
"messenger/src/backend/telemetry"
|
|
"net"
|
|
"time"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
)
|
|
|
|
const jobQueue = "attachments.v1"
|
|
|
|
type JobBroker struct {
|
|
connection *amqp.Connection
|
|
channel *amqp.Channel
|
|
returned chan amqp.Return
|
|
}
|
|
|
|
func NewJobBroker(ctx context.Context, address string) (*JobBroker, error) {
|
|
connection, err := amqp.DialConfig(address, amqp.Config{
|
|
Heartbeat: 10 * time.Second,
|
|
Dial: func(network, address string) (net.Conn, error) {
|
|
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, network, address)
|
|
},
|
|
})
|
|
if err != nil {
|
|
return nil, errors.New("RabbitMQ connection unavailable")
|
|
}
|
|
channel, err := connection.Channel()
|
|
if err != nil {
|
|
connection.Close()
|
|
return nil, errors.New("RabbitMQ channel unavailable")
|
|
}
|
|
b := &JobBroker{connection: connection, channel: channel, returned: make(chan amqp.Return, 1)}
|
|
// Queue metadata and message bodies both survive a broker restart.
|
|
_, err = channel.QueueDeclare(jobQueue, true, false, false, false, nil)
|
|
if err == nil {
|
|
err = channel.Confirm(false)
|
|
}
|
|
if err == nil {
|
|
err = channel.Qos(1, 0, false)
|
|
}
|
|
if err != nil {
|
|
b.Close()
|
|
return nil, errors.New("RabbitMQ queue initialization failed")
|
|
}
|
|
channel.NotifyReturn(b.returned)
|
|
return b, nil
|
|
}
|
|
|
|
func (b *JobBroker) Close() { b.channel.Close(); b.connection.Close() }
|
|
|
|
func (b *JobBroker) Publish(ctx context.Context, body []byte) error {
|
|
// mandatory catches an unroutable message; confirms alone do not prove routing.
|
|
headers := amqp.Table{}
|
|
for key, value := range telemetry.TraceHeaders(ctx) {
|
|
headers[key] = value
|
|
}
|
|
confirmation, err := b.channel.PublishWithDeferredConfirmWithContext(ctx, "", jobQueue, true, false, amqp.Publishing{
|
|
DeliveryMode: amqp.Persistent, ContentType: "application/json", Body: body, Headers: headers,
|
|
})
|
|
if err != nil {
|
|
return errors.New("RabbitMQ publication failed")
|
|
}
|
|
confirmed, err := confirmation.WaitContext(ctx)
|
|
if err != nil || !confirmed {
|
|
return errors.New("RabbitMQ publication not confirmed")
|
|
}
|
|
// basic.return precedes basic.ack on the channel; NotifyReturn is buffered.
|
|
select {
|
|
case <-b.returned:
|
|
return errors.New("RabbitMQ message was not routed")
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
func (b *JobBroker) Consume() (<-chan amqp.Delivery, error) {
|
|
return b.channel.Consume(jobQueue, "", false, false, false, false, nil)
|
|
}
|