| | | 1 | | using Microsoft.Extensions.Options; |
| | | 2 | | using StackExchange.Redis; |
| | | 3 | | using System.Diagnostics; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.Transports.Redis; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Publishes <see cref="WorkerJobEnvelope"/> messages to a Redis stream. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <remarks> |
| | | 12 | | /// Redis Streams provide durable queueing and consumer-group acknowledgement. Publishing uses XADD |
| | | 13 | | /// with optional approximate trimming, and transient Redis failures are retried with bounded |
| | | 14 | | /// exponential backoff before the exception is returned to the caller. |
| | | 15 | | /// </remarks> |
| | | 16 | | public sealed class RedisWorkerTransport : IWorkerTransport |
| | | 17 | | { |
| | | 18 | | private readonly RedisAsyncResponseTransportOptions _options; |
| | | 19 | | private readonly IRedisStreamDatabase _database; |
| | | 20 | | private readonly RedisTransportKeySchema _keys; |
| | | 21 | | private readonly TimeSpan _publishDedupTtl; |
| | | 22 | | |
| | | 23 | | /// <summary>Runs the RedisWorkerTransport operation.</summary> |
| | | 24 | | public RedisWorkerTransport( |
| | | 25 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | | 26 | | IConnectionMultiplexer multiplexer) |
| | 195 | 27 | | : this( |
| | 195 | 28 | | options, |
| | 195 | 29 | | new RedisStreamDatabaseAdapter( |
| | 195 | 30 | | multiplexer.GetDatabase(), |
| | 195 | 31 | | RedisTransportOptionsValidatorWithValue(options).OperationTimeout)) |
| | | 32 | | { |
| | 195 | 33 | | } |
| | | 34 | | |
| | 213 | 35 | | internal RedisWorkerTransport( |
| | 213 | 36 | | IOptions<RedisAsyncResponseTransportOptions> options, |
| | 213 | 37 | | IRedisStreamDatabase database) |
| | | 38 | | { |
| | 213 | 39 | | _options = options.Value; |
| | 213 | 40 | | RedisTransportOptionsValidator.ValidateCommon(_options); |
| | 209 | 41 | | ValidatePublishOptions(_options); |
| | 209 | 42 | | _database = database; |
| | 209 | 43 | | _keys = new RedisTransportKeySchema(_options); |
| | | 44 | | |
| | | 45 | | // The dedup marker must outlive the whole retry window — attempts x (operation timeout + |
| | | 46 | | // max backoff) — so a late retry still finds it; 2x margin, then it is garbage and |
| | | 47 | | // expires. ~66s at the defaults. |
| | 209 | 48 | | var perAttempt = _options.OperationTimeout + _options.PublishRetryMaxDelay; |
| | 209 | 49 | | _publishDedupTtl = TimeSpan.FromTicks(perAttempt.Ticks * Math.Max(1, _options.PublishMaxAttempts) * 2); |
| | 209 | 50 | | } |
| | | 51 | | |
| | | 52 | | private static RedisAsyncResponseTransportOptions RedisTransportOptionsValidatorWithValue( |
| | | 53 | | IOptions<RedisAsyncResponseTransportOptions> options) |
| | | 54 | | { |
| | 195 | 55 | | RedisTransportOptionsValidator.ValidateCommon(options.Value); |
| | 195 | 56 | | ValidatePublishOptions(options.Value); |
| | 195 | 57 | | return options.Value; |
| | | 58 | | } |
| | | 59 | | |
| | | 60 | | private static void ValidatePublishOptions(RedisAsyncResponseTransportOptions options) |
| | | 61 | | { |
| | 404 | 62 | | _ = new RedisTransportKeySchema(options).WorkerStream; |
| | 404 | 63 | | _ = RedisTransportOptionsValidator.Required(options.PayloadField, nameof(options.PayloadField)); |
| | 404 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <summary>Publishes the supplied message.</summary> |
| | | 67 | | public async Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | | 68 | | { |
| | 419 | 69 | | ArgumentNullException.ThrowIfNull(job); |
| | | 70 | | |
| | 417 | 71 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 417 | 72 | | "asyncresponse.worker.publish", |
| | 417 | 73 | | ActivityKind.Producer, |
| | 417 | 74 | | job.CorrelationId); |
| | 417 | 75 | | activity?.SetTag("asyncresponse.transport", "redis"); |
| | 417 | 76 | | activity?.SetTag("messaging.system", "redis"); |
| | 417 | 77 | | activity?.SetTag("messaging.destination.name", _keys.WorkerStream.ToString()); |
| | 417 | 78 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | 417 | 79 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 80 | | |
| | | 81 | | try |
| | | 82 | | { |
| | 417 | 83 | | var fields = CreateMessageFields( |
| | 417 | 84 | | AsyncResponseJson.Serialize(job), |
| | 417 | 85 | | job.CorrelationId, |
| | 417 | 86 | | _options); |
| | | 87 | | // Identity pinned OUTSIDE the retry loop (MongoDB/ASB/SQS parity): a retry after an |
| | | 88 | | // ambiguous timeout — the adapter abandons the in-flight XADD best-effort while the |
| | | 89 | | // multiplexer keeps running it — must not append the same worker job twice. The |
| | | 90 | | // server-side marker makes the retried append a no-op instead. |
| | 417 | 91 | | var publishId = Guid.NewGuid().ToString("N"); |
| | 417 | 92 | | var dedupKey = _keys.WorkerPublishDedupKey(publishId); |
| | 417 | 93 | | var messageId = await RedisTransportRetry.ExecuteAsync( |
| | 423 | 94 | | token => _database.StreamAddOnceAsync( |
| | 423 | 95 | | _keys.WorkerStream, |
| | 423 | 96 | | dedupKey, |
| | 423 | 97 | | _publishDedupTtl, |
| | 423 | 98 | | fields, |
| | 423 | 99 | | _options.StreamMaxLength, |
| | 423 | 100 | | _options.UseApproximateStreamTrimming, |
| | 423 | 101 | | token), |
| | 417 | 102 | | _options.PublishMaxAttempts, |
| | 417 | 103 | | _options.PublishRetryBaseDelay, |
| | 417 | 104 | | _options.PublishRetryMaxDelay, |
| | 417 | 105 | | cancellationToken).ConfigureAwait(false); |
| | | 106 | | |
| | | 107 | | // Null: a previous attempt's append already committed — the job is on the stream once. |
| | 415 | 108 | | if (!messageId.IsNull) |
| | 413 | 109 | | activity?.SetTag("messaging.message.id", messageId.ToString()); |
| | 415 | 110 | | } |
| | 2 | 111 | | catch (Exception ex) |
| | | 112 | | { |
| | 2 | 113 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 2 | 114 | | throw; |
| | | 115 | | } |
| | 415 | 116 | | } |
| | | 117 | | |
| | | 118 | | internal static NameValueEntry[] CreateMessageFields( |
| | | 119 | | string payloadJson, |
| | | 120 | | string? correlationId, |
| | | 121 | | RedisAsyncResponseTransportOptions options) |
| | | 122 | | { |
| | 417 | 123 | | var payloadField = RedisTransportOptionsValidator.Required(options.PayloadField, nameof(options.PayloadField)); |
| | 417 | 124 | | var correlationField = RedisTransportOptionsValidator.Required(options.CorrelationIdField, nameof(options.Correl |
| | | 125 | | |
| | 417 | 126 | | return string.IsNullOrWhiteSpace(correlationId) |
| | 417 | 127 | | ? [new NameValueEntry(payloadField, payloadJson)] |
| | 417 | 128 | | : |
| | 417 | 129 | | [ |
| | 417 | 130 | | new NameValueEntry(payloadField, payloadJson), |
| | 417 | 131 | | new NameValueEntry(correlationField, correlationId) |
| | 417 | 132 | | ]; |
| | | 133 | | } |
| | | 134 | | } |