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"
|
"time"
|
||||||
|
|
||||||
amqp "github.com/rabbitmq/amqp091-go"
|
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/config"
|
||||||
"high-loud-apps-labs/internal/domain"
|
"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)
|
quit := make(chan os.Signal, 1)
|
||||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer signal.Stop(quit)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -129,18 +133,41 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin
|
|||||||
if !ok {
|
if !ok {
|
||||||
return context.Canceled // Канал закрыт (соединение разорвано)
|
return context.Canceled // Канал закрыт (соединение разорвано)
|
||||||
}
|
}
|
||||||
var msg domain.JobMessage
|
if err := consume(ctx, d, pipeline); err != nil {
|
||||||
if err := json.Unmarshal(d.Body, &msg); err != nil {
|
return err
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,6 +7,11 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
amqp "github.com/rabbitmq/amqp091-go"
|
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 {
|
type Publisher interface {
|
||||||
@@ -15,11 +20,10 @@ type Publisher interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type RabbitPublisher struct {
|
type RabbitPublisher struct {
|
||||||
url string
|
url string
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
conn *amqp.Connection
|
conn *amqp.Connection
|
||||||
ch *amqp.Channel
|
ch *amqp.Channel
|
||||||
confirms chan amqp.Confirmation
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRabbitPublisher(url string) (*RabbitPublisher, error) {
|
func NewRabbitPublisher(url string) (*RabbitPublisher, error) {
|
||||||
@@ -45,7 +49,6 @@ func (p *RabbitPublisher) connect() error {
|
|||||||
if err := p.ch.Confirm(false); err != nil {
|
if err := p.ch.Confirm(false); err != nil {
|
||||||
return fmt.Errorf("включение режима confirm: %w", err)
|
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)
|
err = p.ch.ExchangeDeclare("attachments", "direct", true, false, false, false, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -65,7 +68,19 @@ func (p *RabbitPublisher) connect() error {
|
|||||||
return nil
|
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()
|
p.mu.Lock()
|
||||||
defer p.mu.Unlock()
|
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",
|
ContentType: "application/json",
|
||||||
DeliveryMode: amqp.Persistent,
|
DeliveryMode: amqp.Persistent,
|
||||||
Body: body,
|
Body: body,
|
||||||
@@ -84,17 +104,16 @@ func (p *RabbitPublisher) Publish(ctx context.Context, routingKey string, body [
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
select {
|
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
case confirm := <-p.confirms:
|
defer cancel()
|
||||||
if !confirm.Ack {
|
acked, err := confirmation.WaitContext(waitCtx)
|
||||||
return fmt.Errorf("сообщение отклонено брокером")
|
if err != nil {
|
||||||
}
|
return fmt.Errorf("ожидание подтверждения RabbitMQ: %w", err)
|
||||||
return nil
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
return fmt.Errorf("таймаут ожидания подтверждения от rabbitmq")
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
}
|
||||||
|
if !acked {
|
||||||
|
return fmt.Errorf("сообщение отклонено брокером")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *RabbitPublisher) Close() error {
|
func (p *RabbitPublisher) Close() error {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"high-loud-apps-labs/internal/broker"
|
"high-loud-apps-labs/internal/broker"
|
||||||
"high-loud-apps-labs/internal/domain"
|
"high-loud-apps-labs/internal/domain"
|
||||||
|
"high-loud-apps-labs/internal/telemetry"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Publisher struct {
|
type Publisher struct {
|
||||||
@@ -54,7 +55,7 @@ func (p *Publisher) tick(ctx context.Context) {
|
|||||||
|
|
||||||
var successIDs []string
|
var successIDs []string
|
||||||
for _, e := range entries {
|
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 {
|
if err != nil {
|
||||||
log.Printf("outbox: ошибка публикации %s: %v", e.ID, err)
|
log.Printf("outbox: ошибка публикации %s: %v", e.ID, err)
|
||||||
break // Прерываем пачку
|
break // Прерываем пачку
|
||||||
|
|||||||
Reference in New Issue
Block a user