feat(rabbitmq): lab6 propagate trace context from publisher to worker

This commit is contained in:
Голиков Maximillian Антон
2026-11-16 17:04:32 +03:00
parent 2716119a20
commit 26ee39e814
3 changed files with 77 additions and 30 deletions
+38 -11
View File
@@ -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)
}