forked from mtusi2026/mtusi2026lab6
feat(rabbitmq): lab6 propagate trace context from publisher to worker
This commit is contained in:
+38
-11
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user