diff --git a/backend/cmd/worker/main.go b/backend/cmd/worker/main.go index 69f6373..1986dc0 100644 --- a/backend/cmd/worker/main.go +++ b/backend/cmd/worker/main.go @@ -11,6 +11,9 @@ import ( "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/config" "high-loud-apps-labs/internal/domain" @@ -119,6 +122,7 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(quit) for { select { @@ -129,18 +133,41 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin if !ok { return context.Canceled // Канал закрыт (соединение разорвано) } - var msg domain.JobMessage - if err := json.Unmarshal(d.Body, &msg); err != nil { - slog.Error("Worker получил битое сообщение", "error", err) - _ = d.Nack(false, false) - continue - } - if err := pipeline.Process(ctx, msg.AttachmentID, msg.PipelineVersion); err != nil { - slog.Error("Ошибка обработки задачи", "attachment_id", msg.AttachmentID, "error", err) - _ = d.Nack(false, true) - } else { - _ = d.Ack(false) + if err := consume(ctx, d, pipeline); err != nil { + return err } } } } + +func consume(ctx context.Context, d amqp.Delivery, pipeline *worker.Pipeline) (ackErr error) { + headers := make(map[string]string, 2) + for _, key := range []string{"traceparent", "tracestate"} { + if value, ok := d.Headers[key].(string); ok { + headers[key] = value + } + } + ctx, span := telemetry.Tracer("worker").Start(telemetry.ExtractTrace(ctx, headers), + "attachments.process process", trace.WithSpanKind(trace.SpanKindConsumer), + trace.WithAttributes(attribute.String("messaging.system", "rabbitmq"), + attribute.String("messaging.destination.name", "attachments.process"))) + defer func() { + if ackErr != nil { + span.SetStatus(codes.Error, "ошибка подтверждения доставки") + } + span.End() + }() + + var msg domain.JobMessage + if err := json.Unmarshal(d.Body, &msg); err != nil { + span.SetStatus(codes.Error, "повреждённое сообщение") + slog.ErrorContext(ctx, "Неверный JSON задания", "event", "job.invalid") + return d.Nack(false, false) + } + if err := pipeline.Process(ctx, msg.AttachmentID, msg.PipelineVersion); err != nil { + span.SetStatus(codes.Error, "ошибка обработки") + slog.ErrorContext(ctx, "Повторная доставка задания", "event", "job.requeue") + return d.Nack(false, true) + } + return d.Ack(false) +} diff --git a/backend/internal/broker/rabbitmq.go b/backend/internal/broker/rabbitmq.go index dd79752..9d4cc06 100644 --- a/backend/internal/broker/rabbitmq.go +++ b/backend/internal/broker/rabbitmq.go @@ -7,6 +7,11 @@ import ( "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 { @@ -15,11 +20,10 @@ type Publisher interface { } type RabbitPublisher struct { - url string - mu sync.Mutex - conn *amqp.Connection - ch *amqp.Channel - confirms chan amqp.Confirmation + url string + mu sync.Mutex + conn *amqp.Connection + ch *amqp.Channel } func NewRabbitPublisher(url string) (*RabbitPublisher, error) { @@ -45,7 +49,6 @@ func (p *RabbitPublisher) connect() error { if err := p.ch.Confirm(false); err != nil { return fmt.Errorf("включение режима confirm: %w", err) } - p.confirms = p.ch.NotifyPublish(make(chan amqp.Confirmation, 1)) err = p.ch.ExchangeDeclare("attachments", "direct", true, false, false, false, nil) if err != nil { @@ -65,7 +68,19 @@ func (p *RabbitPublisher) connect() error { return nil } -func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body []byte) error { +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() @@ -75,7 +90,12 @@ func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body [ } } - err := p.ch.PublishWithContext(ctx, "attachments", routingKey, false, false, amqp.Publishing{ + 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, @@ -84,17 +104,16 @@ func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body [ return err } - select { - case confirm := <-p.confirms: - if !confirm.Ack { - return fmt.Errorf("сообщение отклонено брокером") - } - return nil - case <-time.After(5 * time.Second): - return fmt.Errorf("таймаут ожидания подтверждения от rabbitmq") - case <-ctx.Done(): - return ctx.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 { diff --git a/backend/internal/outbox/publisher.go b/backend/internal/outbox/publisher.go index 2eb5ef2..7d9357a 100644 --- a/backend/internal/outbox/publisher.go +++ b/backend/internal/outbox/publisher.go @@ -7,6 +7,7 @@ import ( "high-loud-apps-labs/internal/broker" "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/telemetry" ) type Publisher struct { @@ -54,7 +55,7 @@ func (p *Publisher) tick(ctx context.Context) { var successIDs []string for _, e := range entries { - err := p.broker.Publish(ctx, "process", e.Payload) + err := p.broker.Publish(telemetry.ExtractTrace(ctx, e.Headers), "process", e.Payload) if err != nil { log.Printf("outbox: ошибка публикации %s: %v", e.ID, err) break // Прерываем пачку