| | | 1 | | using Microsoft.Extensions.Options; |
| | | 2 | | using NATS.Client.Core; |
| | | 3 | | using NATS.Net; |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | |
| | | 7 | | namespace AsyncResponse.Transports.NATS; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Publishes <see cref="WorkerJobEnvelope"/> messages to a NATS JetStream subject. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <remarks> |
| | | 13 | | /// JetStream provides durable queueing and explicit acknowledgement. The correlation id travels as a |
| | | 14 | | /// message header so the consuming side can correlate without parsing the body, and transient NATS |
| | | 15 | | /// failures are retried with bounded exponential backoff before the exception is returned to the |
| | | 16 | | /// caller. |
| | | 17 | | /// </remarks> |
| | | 18 | | public sealed class NatsWorkerTransport : IWorkerTransport |
| | | 19 | | { |
| | | 20 | | private readonly NatsAsyncResponseTransportOptions _options; |
| | | 21 | | private readonly INatsJetStreamTransport _jetStream; |
| | | 22 | | private readonly NatsTransportSubjectSchema _schema; |
| | 3 | 23 | | private readonly SemaphoreSlim _ensureStreamGate = new(1, 1); |
| | | 24 | | private bool _streamEnsured; |
| | | 25 | | |
| | | 26 | | /// <summary>Runs the NatsWorkerTransport operation.</summary> |
| | | 27 | | public NatsWorkerTransport( |
| | | 28 | | IOptions<NatsAsyncResponseTransportOptions> options, |
| | | 29 | | INatsConnection connection) |
| | 3 | 30 | | : this(options, new NatsJetStreamTransportAdapter(connection.CreateJetStreamContext())) |
| | | 31 | | { |
| | 3 | 32 | | } |
| | | 33 | | |
| | 3 | 34 | | internal NatsWorkerTransport( |
| | 3 | 35 | | IOptions<NatsAsyncResponseTransportOptions> options, |
| | 3 | 36 | | INatsJetStreamTransport jetStream) |
| | | 37 | | { |
| | 3 | 38 | | _options = options.Value; |
| | 3 | 39 | | NatsTransportOptionsValidator.ValidateCommon(_options); |
| | 3 | 40 | | _jetStream = jetStream; |
| | 3 | 41 | | _schema = new NatsTransportSubjectSchema(_options); |
| | 3 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary>Publishes the supplied message.</summary> |
| | | 45 | | public async Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | | 46 | | { |
| | 3 | 47 | | ArgumentNullException.ThrowIfNull(job); |
| | | 48 | | |
| | 3 | 49 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 3 | 50 | | "asyncresponse.worker.publish", |
| | 3 | 51 | | ActivityKind.Producer, |
| | 3 | 52 | | job.CorrelationId); |
| | 3 | 53 | | activity?.SetTag("asyncresponse.transport", "nats"); |
| | 3 | 54 | | activity?.SetTag("messaging.system", "nats"); |
| | 3 | 55 | | activity?.SetTag("messaging.destination.name", _schema.WorkerSubject); |
| | 3 | 56 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | 3 | 57 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 58 | | |
| | | 59 | | try |
| | | 60 | | { |
| | 3 | 61 | | if (_options.CreateStreams) |
| | 3 | 62 | | await EnsureWorkerStreamOnceAsync(cancellationToken).ConfigureAwait(false); |
| | | 63 | | |
| | 3 | 64 | | var headers = string.IsNullOrWhiteSpace(job.CorrelationId) |
| | 3 | 65 | | ? null |
| | 3 | 66 | | : new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) |
| | 3 | 67 | | { |
| | 3 | 68 | | [_options.CorrelationIdHeader] = job.CorrelationId! |
| | 3 | 69 | | }; |
| | | 70 | | |
| | 3 | 71 | | var payload = AsyncResponseJson.Serialize(job); |
| | 3 | 72 | | var sequence = await NatsTransportRetry.ExecuteAsync( |
| | 3 | 73 | | token => _jetStream.PublishAsync(_schema.WorkerSubject, payload, headers, token), |
| | 3 | 74 | | _options.PublishMaxAttempts, |
| | 3 | 75 | | _options.PublishRetryBaseDelay, |
| | 3 | 76 | | _options.PublishRetryMaxDelay, |
| | 3 | 77 | | cancellationToken).ConfigureAwait(false); |
| | | 78 | | |
| | 3 | 79 | | activity?.SetTag("messaging.message.id", sequence); |
| | 3 | 80 | | } |
| | 2 | 81 | | catch (Exception ex) |
| | | 82 | | { |
| | 2 | 83 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 3 | 84 | | throw; |
| | | 85 | | } |
| | 3 | 86 | | } |
| | | 87 | | |
| | | 88 | | private async Task EnsureWorkerStreamOnceAsync(CancellationToken cancellationToken) |
| | | 89 | | { |
| | 3 | 90 | | if (_streamEnsured) |
| | 3 | 91 | | return; |
| | | 92 | | |
| | 3 | 93 | | await _ensureStreamGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 94 | | try |
| | | 95 | | { |
| | 3 | 96 | | if (!_streamEnsured) |
| | | 97 | | { |
| | 3 | 98 | | await _jetStream.EnsureStreamAsync( |
| | 3 | 99 | | _schema.WorkerStream, |
| | 3 | 100 | | _schema.WorkerSubject, |
| | 3 | 101 | | _options.StreamMaxMessages, |
| | 3 | 102 | | cancellationToken).ConfigureAwait(false); |
| | 3 | 103 | | _streamEnsured = true; |
| | | 104 | | } |
| | 3 | 105 | | } |
| | | 106 | | finally |
| | | 107 | | { |
| | 3 | 108 | | _ensureStreamGate.Release(); |
| | | 109 | | } |
| | 3 | 110 | | } |
| | | 111 | | } |