| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace AsyncResponse.Transports.RabbitMQ; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Extracts the AsyncResponse correlation id from an inbound response message: first from the |
| | | 8 | | /// broker's own CorrelationId, then the configured header, then from the JSON body via the |
| | | 9 | | /// configured paths (walked by the shared <see cref="CorrelationIdJsonPaths"/>). |
| | | 10 | | /// </summary> |
| | | 11 | | internal static class RabbitMqCorrelationIdExtractor |
| | | 12 | | { |
| | | 13 | | /// <summary>Extracts the correlation id from the supplied message.</summary> |
| | | 14 | | public static string? Extract( |
| | | 15 | | RabbitMqDelivery delivery, |
| | | 16 | | string messageJson, |
| | | 17 | | RabbitMqAsyncResponseOptions options) |
| | | 18 | | { |
| | 42 | 19 | | if (!string.IsNullOrWhiteSpace(delivery.BasicProperties.CorrelationId)) |
| | 2 | 20 | | return delivery.BasicProperties.CorrelationId; |
| | | 21 | | |
| | 40 | 22 | | if (!string.IsNullOrWhiteSpace(options.CorrelationIdHeader) |
| | 40 | 23 | | && delivery.BasicProperties.Headers is not null |
| | 40 | 24 | | && delivery.BasicProperties.Headers.TryGetValue(options.CorrelationIdHeader, out var header) |
| | 40 | 25 | | && TryConvertHeader(header) is { } headerValue |
| | 40 | 26 | | && !string.IsNullOrWhiteSpace(headerValue)) |
| | | 27 | | { |
| | 14 | 28 | | return headerValue; |
| | | 29 | | } |
| | | 30 | | |
| | 26 | 31 | | return CorrelationIdJsonPaths.Extract(messageJson, options.CorrelationIdJsonPaths); |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | private static string? TryConvertHeader(object? header) |
| | 16 | 35 | | => header switch |
| | 16 | 36 | | { |
| | 2 | 37 | | null => null, |
| | 2 | 38 | | string s => s, |
| | 2 | 39 | | byte[] bytes => Encoding.UTF8.GetString(bytes), |
| | 2 | 40 | | ReadOnlyMemory<byte> memory => Encoding.UTF8.GetString(memory.Span), |
| | 16 | 41 | | // AMQP headers legally carry numeric/timestamp values, and the id must render the same |
| | 16 | 42 | | // on every consumer: a locale-formatted "1,5" here never matches the "1.5" the waiter |
| | 16 | 43 | | // registered under, so the wait runs to timeout on hosts with another CurrentCulture. |
| | 8 | 44 | | IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), |
| | 0 | 45 | | _ => header.ToString() |
| | 16 | 46 | | }; |
| | | 47 | | } |