forked from mtusi2026/mtusi2026lab6
131 lines
3.1 KiB
Go
131 lines
3.1 KiB
Go
package broker
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
amqp "github.com/rabbitmq/amqp091-go"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/trace"
|
|
|
|
"high-loud-apps-labs/internal/telemetry"
|
|
)
|
|
|
|
type Publisher interface {
|
|
Publish(ctx context.Context, routingKey string, body []byte) error
|
|
Close() error
|
|
}
|
|
|
|
type RabbitPublisher struct {
|
|
url string
|
|
mu sync.Mutex
|
|
conn *amqp.Connection
|
|
ch *amqp.Channel
|
|
}
|
|
|
|
func NewRabbitPublisher(url string) (*RabbitPublisher, error) {
|
|
p := &RabbitPublisher{url: url}
|
|
if err := p.connect(); err != nil {
|
|
return nil, err
|
|
}
|
|
return p, nil
|
|
}
|
|
|
|
func (p *RabbitPublisher) connect() error {
|
|
var err error
|
|
p.conn, err = amqp.Dial(p.url)
|
|
if err != nil {
|
|
return fmt.Errorf("подключение к rabbitmq: %w", err)
|
|
}
|
|
|
|
p.ch, err = p.conn.Channel()
|
|
if err != nil {
|
|
return fmt.Errorf("открытие канала rabbitmq: %w", err)
|
|
}
|
|
|
|
if err := p.ch.Confirm(false); err != nil {
|
|
return fmt.Errorf("включение режима confirm: %w", err)
|
|
}
|
|
|
|
err = p.ch.ExchangeDeclare("attachments", "direct", true, false, false, false, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("объявление exchange: %w", err)
|
|
}
|
|
|
|
_, err = p.ch.QueueDeclare("attachments.process", true, false, false, false, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("объявление очереди: %w", err)
|
|
}
|
|
|
|
err = p.ch.QueueBind("attachments.process", "process", "attachments", false, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("привязка очереди: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body []byte) (publishErr error) {
|
|
ctx, span := telemetry.Tracer("broker").Start(ctx, "attachments publish",
|
|
trace.WithSpanKind(trace.SpanKindProducer), trace.WithAttributes(
|
|
attribute.String("messaging.system", "rabbitmq"),
|
|
attribute.String("messaging.destination.name", "attachments"),
|
|
))
|
|
defer func() {
|
|
if publishErr != nil {
|
|
span.SetStatus(codes.Error, "публикация не подтверждена")
|
|
}
|
|
span.End()
|
|
}()
|
|
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
|
|
if p.conn == nil || p.conn.IsClosed() {
|
|
if err := p.connect(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
headers := amqp.Table{}
|
|
for key, value := range telemetry.TraceHeaders(ctx) {
|
|
headers[key] = value
|
|
}
|
|
confirmation, err := p.ch.PublishWithDeferredConfirmWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{
|
|
Headers: headers,
|
|
ContentType: "application/json",
|
|
DeliveryMode: amqp.Persistent,
|
|
Body: body,
|
|
Timestamp: time.Now().UTC(),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
acked, err := confirmation.WaitContext(waitCtx)
|
|
if err != nil {
|
|
return fmt.Errorf("ожидание подтверждения RabbitMQ: %w", err)
|
|
}
|
|
if !acked {
|
|
return fmt.Errorf("сообщение отклонено брокером")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *RabbitPublisher) Close() error {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
if p.ch != nil {
|
|
_ = p.ch.Close()
|
|
}
|
|
if p.conn != nil {
|
|
return p.conn.Close()
|
|
}
|
|
return nil
|
|
}
|