| | 1 | | using MassTransit; |
| | 2 | | using Contracts; |
| | 3 | | using OpenTelemetry; |
| | 4 | | using OpenTelemetry.Context.Propagation; |
| | 5 | | using System.Diagnostics; |
| | 6 | | using System.Text; |
| | 7 | |
|
| | 8 | | public class OrderConsumer : IConsumer<Order> |
| | 9 | | { |
| | 10 | | private readonly PaymentDbContext _dbContext; |
| 1 | 11 | | private static readonly ActivitySource ActivitySource = new("PaymentService"); |
| | 12 | |
|
| 1 | 13 | | public OrderConsumer(PaymentDbContext dbContext) |
| | 14 | | { |
| 1 | 15 | | _dbContext = dbContext; |
| 1 | 16 | | } |
| | 17 | |
|
| | 18 | | public async Task Consume(ConsumeContext<Order> context) |
| | 19 | | { |
| | 20 | | // Extrai o contexto de rastreamento dos headers MassTransit |
| 1 | 21 | | var parentContext = Propagators.DefaultTextMapPropagator.Extract( |
| 1 | 22 | | default, |
| 1 | 23 | | context.Headers, |
| 1 | 24 | | (headers, key) => |
| 1 | 25 | | { |
| 0 | 26 | | if (headers.TryGetHeader(key, out var value)) |
| 1 | 27 | | { |
| 0 | 28 | | return value switch |
| 0 | 29 | | { |
| 0 | 30 | | string s => new[] { s }, |
| 0 | 31 | | byte[] b => new[] { Encoding.UTF8.GetString(b) }, |
| 0 | 32 | | _ => Array.Empty<string>() |
| 0 | 33 | | }; |
| 1 | 34 | | } |
| 0 | 35 | | return Array.Empty<string>(); |
| 1 | 36 | | }); |
| | 37 | |
|
| 1 | 38 | | Baggage.Current = parentContext.Baggage; |
| 1 | 39 | | Activity.Current = null; // 🔥 limpa contexto anterior |
| | 40 | |
|
| 1 | 41 | | using var activity = ActivitySource.StartActivity( |
| 1 | 42 | | "Consume Order", |
| 1 | 43 | | ActivityKind.Consumer, |
| 1 | 44 | | parentContext.ActivityContext); |
| | 45 | |
|
| 1 | 46 | | activity?.SetTag("message.id", context.MessageId); |
| 1 | 47 | | activity?.SetTag("order.id", context.Message.Id); |
| 1 | 48 | | activity?.SetTag("order.productName", context.Message.ProductName); |
| 1 | 49 | | activity?.SetTag("messaging.system", "rabbitmq"); |
| 1 | 50 | | activity?.SetTag("messaging.destination", "payment-service-queue"); |
| | 51 | |
|
| 1 | 52 | | var payment = new Payment |
| 1 | 53 | | { |
| 1 | 54 | | Id = Guid.NewGuid(), |
| 1 | 55 | | OrderId = context.Message.Id |
| 1 | 56 | | }; |
| | 57 | |
|
| 1 | 58 | | _dbContext.Payments.Add(payment); |
| 1 | 59 | | await _dbContext.SaveChangesAsync(); |
| | 60 | |
|
| 1 | 61 | | Console.WriteLine($"💰 Pagamento registrado para pedido: {context.Message.ProductName}"); |
| 1 | 62 | | } |
| | 63 | | } |