| | | 1 | | using Microsoft.Extensions.Hosting; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using System.Threading.Channels; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.Transports.MongoDB; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Base hosted service that consumes one MongoDB queue and routes documents to AsyncResponse ingress |
| | | 10 | | /// with configured acknowledgement, redelivery, and dead-letter behavior. |
| | | 11 | | /// </summary> |
| | | 12 | | internal abstract class MongoDbSubscriberService : BackgroundService |
| | | 13 | | { |
| | | 14 | | private readonly MongoDbTransportStore _store; |
| | 3 | 15 | | private readonly Channel<bool> _signals = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) |
| | 3 | 16 | | { |
| | 3 | 17 | | SingleReader = true, |
| | 3 | 18 | | SingleWriter = false, |
| | 3 | 19 | | FullMode = BoundedChannelFullMode.DropWrite |
| | 3 | 20 | | }); |
| | | 21 | | |
| | 3 | 22 | | protected MongoDbSubscriberService( |
| | 3 | 23 | | IOptions<MongoDbAsyncResponseTransportOptions> options, |
| | 3 | 24 | | MongoDbTransportStore store, |
| | 3 | 25 | | ILogger logger) |
| | | 26 | | { |
| | 3 | 27 | | Options = options.Value; |
| | 3 | 28 | | MongoDbTransportOptionsValidator.ValidateCommon(Options); |
| | 3 | 29 | | _store = store; |
| | 3 | 30 | | Logger = logger; |
| | 3 | 31 | | } |
| | | 32 | | |
| | | 33 | | protected MongoDbAsyncResponseTransportOptions Options { get; } |
| | | 34 | | protected ILogger Logger { get; } |
| | | 35 | | |
| | | 36 | | protected abstract string Queue { get; } |
| | | 37 | | protected abstract MongoDbSubscriberOptions SubscriberOptions { get; } |
| | | 38 | | protected abstract MongoDbSubscriberRole Role { get; } |
| | | 39 | | protected abstract Task HandleMessageAsync(MongoDbTransportDelivery delivery, CancellationToken cancellationToken); |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | | 42 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 43 | | { |
| | 3 | 44 | | MongoDbTransportOptionsValidator.ValidateSubscriber(Options, SubscriberOptions, Role.ToString()); |
| | | 45 | | |
| | 3 | 46 | | var failures = 0; |
| | 3 | 47 | | while (!stoppingToken.IsCancellationRequested) |
| | | 48 | | { |
| | | 49 | | try |
| | | 50 | | { |
| | 3 | 51 | | await RunSubscriberAsync(stoppingToken).ConfigureAwait(false); |
| | 3 | 52 | | return; |
| | | 53 | | } |
| | 3 | 54 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 55 | | { |
| | 3 | 56 | | return; |
| | | 57 | | } |
| | 3 | 58 | | catch (Exception ex) when (!stoppingToken.IsCancellationRequested) |
| | | 59 | | { |
| | 2 | 60 | | failures++; |
| | 2 | 61 | | var delay = AsyncResponseRetry.Backoff(failures, Options.SubscriberRetryBaseDelay, Options.SubscriberRet |
| | 2 | 62 | | Logger.LogWarning(ex, "MongoDB subscriber failed for queue {Queue} ({Role}); retrying in {RetryDelay}.", |
| | 2 | 63 | | await Task.Delay(delay, stoppingToken).ConfigureAwait(false); |
| | | 64 | | } |
| | | 65 | | } |
| | 3 | 66 | | } |
| | | 67 | | |
| | | 68 | | private async Task RunSubscriberAsync(CancellationToken stoppingToken) |
| | | 69 | | { |
| | 3 | 70 | | await _store.EnsureCreatedAsync(stoppingToken).ConfigureAwait(false); |
| | 3 | 71 | | using var signalCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); |
| | 3 | 72 | | var listenTask = Options.UseChangeStreamWake |
| | 3 | 73 | | ? Task.Run(() => ListenLoopAsync(signalCts.Token), signalCts.Token) |
| | 3 | 74 | | : Task.CompletedTask; |
| | | 75 | | |
| | 3 | 76 | | await using var dispatcher = new MongoDbMessageDispatcher( |
| | 3 | 77 | | HandleMessageAsync, |
| | 3 | 78 | | Options, |
| | 3 | 79 | | SubscriberOptions, |
| | 3 | 80 | | Logger, |
| | 3 | 81 | | Role); |
| | | 82 | | |
| | 3 | 83 | | Logger.LogInformation( |
| | 3 | 84 | | "MongoDB subscriber started. Queue: {Queue}. Role: {Role}. AckMode: {AckMode}.", |
| | 3 | 85 | | Queue, |
| | 3 | 86 | | Role, |
| | 3 | 87 | | SubscriberOptions.AckMode); |
| | | 88 | | |
| | | 89 | | try |
| | | 90 | | { |
| | 3 | 91 | | while (!stoppingToken.IsCancellationRequested) |
| | | 92 | | { |
| | 3 | 93 | | var claimed = 0; |
| | 3 | 94 | | await foreach (var delivery in _store.ClaimBatchAsync(Queue, SubscriberOptions.BatchSize, Options.LockTi |
| | | 95 | | { |
| | 3 | 96 | | claimed++; |
| | 3 | 97 | | await dispatcher.HandleAsync(delivery, stoppingToken).ConfigureAwait(false); |
| | | 98 | | } |
| | | 99 | | |
| | 3 | 100 | | if (claimed > 0) |
| | | 101 | | continue; |
| | | 102 | | |
| | 3 | 103 | | await WaitForSignalOrDelayAsync(stoppingToken).ConfigureAwait(false); |
| | | 104 | | } |
| | | 105 | | } |
| | | 106 | | finally |
| | | 107 | | { |
| | 3 | 108 | | await signalCts.CancelAsync().ConfigureAwait(false); |
| | | 109 | | try |
| | | 110 | | { |
| | 3 | 111 | | await listenTask.WaitAsync(Options.ShutdownTimeout).ConfigureAwait(false); |
| | 3 | 112 | | } |
| | 2 | 113 | | catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) |
| | | 114 | | { |
| | 3 | 115 | | } |
| | | 116 | | } |
| | 3 | 117 | | } |
| | | 118 | | |
| | | 119 | | private async Task ListenLoopAsync(CancellationToken cancellationToken) |
| | | 120 | | { |
| | | 121 | | try |
| | | 122 | | { |
| | 3 | 123 | | await _store.WatchQueueAsync(Queue, () => |
| | 3 | 124 | | { |
| | 3 | 125 | | _signals.Writer.TryWrite(true); |
| | 3 | 126 | | return Task.CompletedTask; |
| | 3 | 127 | | }, cancellationToken).ConfigureAwait(false); |
| | 2 | 128 | | } |
| | 3 | 129 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 130 | | { |
| | 3 | 131 | | } |
| | 2 | 132 | | catch (Exception ex) when (MongoDbTransportStore.IsChangeStreamUnsupported(ex)) |
| | | 133 | | { |
| | 2 | 134 | | Logger.LogInformation( |
| | 2 | 135 | | "MongoDB change streams are unavailable for queue {Queue} (the server is not a replica set); polling con |
| | 2 | 136 | | Queue, |
| | 2 | 137 | | SubscriberOptions.EmptyPollDelay); |
| | 2 | 138 | | } |
| | 2 | 139 | | catch (Exception ex) |
| | | 140 | | { |
| | 2 | 141 | | Logger.LogDebug(ex, "MongoDB change-stream wake for queue {Queue} stopped; polling continues.", Queue); |
| | 3 | 142 | | } |
| | 3 | 143 | | } |
| | | 144 | | |
| | | 145 | | private async Task WaitForSignalOrDelayAsync(CancellationToken cancellationToken) |
| | | 146 | | { |
| | 3 | 147 | | var delay = Task.Delay(SubscriberOptions.EmptyPollDelay, cancellationToken); |
| | 3 | 148 | | var signal = _signals.Reader.WaitToReadAsync(cancellationToken).AsTask(); |
| | 3 | 149 | | var completed = await Task.WhenAny(delay, signal).ConfigureAwait(false); |
| | 3 | 150 | | if (completed == signal) |
| | | 151 | | { |
| | 3 | 152 | | await signal.ConfigureAwait(false); |
| | 3 | 153 | | while (_signals.Reader.TryRead(out _)) |
| | | 154 | | { |
| | | 155 | | } |
| | | 156 | | } |
| | 3 | 157 | | } |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <summary>Consumes worker-job documents and executes them through the AsyncResponse ingress.</summary> |
| | | 161 | | internal sealed class MongoDbWorkerSubscriber : MongoDbSubscriberService |
| | | 162 | | { |
| | | 163 | | private readonly IAsyncResponseIngress _ingress; |
| | | 164 | | |
| | | 165 | | public MongoDbWorkerSubscriber( |
| | | 166 | | IOptions<MongoDbAsyncResponseTransportOptions> options, |
| | | 167 | | MongoDbTransportStore store, |
| | | 168 | | IAsyncResponseIngress ingress, |
| | | 169 | | ILogger<MongoDbWorkerSubscriber> logger) |
| | | 170 | | : base(options, store, logger) |
| | | 171 | | => _ingress = ingress; |
| | | 172 | | |
| | | 173 | | protected override string Queue => Options.WorkerQueue; |
| | | 174 | | protected override MongoDbSubscriberOptions SubscriberOptions => Options.WorkerSubscriber; |
| | | 175 | | protected override MongoDbSubscriberRole Role => MongoDbSubscriberRole.Worker; |
| | | 176 | | |
| | | 177 | | protected override Task HandleMessageAsync(MongoDbTransportDelivery delivery, CancellationToken cancellationToken) |
| | | 178 | | => _ingress.HandleWorkerMessageAsync(delivery.Payload); |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | /// <summary>Consumes response documents and feeds them into the AsyncResponse ingress.</summary> |
| | | 182 | | internal sealed class MongoDbResponseIngressSubscriber : MongoDbSubscriberService |
| | | 183 | | { |
| | | 184 | | private readonly IAsyncResponseIngress _ingress; |
| | | 185 | | |
| | | 186 | | public MongoDbResponseIngressSubscriber( |
| | | 187 | | IOptions<MongoDbAsyncResponseTransportOptions> options, |
| | | 188 | | MongoDbTransportStore store, |
| | | 189 | | IAsyncResponseIngress ingress, |
| | | 190 | | ILogger<MongoDbResponseIngressSubscriber> logger) |
| | | 191 | | : base(options, store, logger) |
| | | 192 | | => _ingress = ingress; |
| | | 193 | | |
| | | 194 | | protected override string Queue => Options.ResponseQueue; |
| | | 195 | | protected override MongoDbSubscriberOptions SubscriberOptions => Options.ResponseSubscriber; |
| | | 196 | | protected override MongoDbSubscriberRole Role => MongoDbSubscriberRole.ResponseIngress; |
| | | 197 | | |
| | | 198 | | protected override Task HandleMessageAsync(MongoDbTransportDelivery delivery, CancellationToken cancellationToken) |
| | | 199 | | { |
| | | 200 | | var correlationId = MongoDbCorrelationIdExtractor.Extract(delivery.Headers, delivery.Payload, Options); |
| | | 201 | | return _ingress.HandleResponseMessageAsync(delivery.Payload, correlationId); |
| | | 202 | | } |
| | | 203 | | } |