| | | 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.SqlServer; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Base hosted service that consumes one SQL Server queue and routes rows to AsyncResponse ingress |
| | | 10 | | /// with configured acknowledgement, redelivery, and dead-letter behavior. |
| | | 11 | | /// </summary> |
| | | 12 | | internal abstract class SqlServerSubscriberService : BackgroundService |
| | | 13 | | { |
| | | 14 | | private readonly SqlServerTransportStore _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 SqlServerSubscriberService( |
| | 3 | 23 | | IOptions<SqlServerAsyncResponseTransportOptions> options, |
| | 3 | 24 | | SqlServerTransportStore store, |
| | 3 | 25 | | ILogger logger) |
| | | 26 | | { |
| | 3 | 27 | | Options = options.Value; |
| | 3 | 28 | | SqlServerTransportOptionsValidator.ValidateCommon(Options); |
| | 3 | 29 | | _store = store; |
| | 3 | 30 | | Logger = logger; |
| | 3 | 31 | | } |
| | | 32 | | |
| | | 33 | | protected SqlServerAsyncResponseTransportOptions Options { get; } |
| | | 34 | | protected ILogger Logger { get; } |
| | | 35 | | |
| | | 36 | | protected abstract string Queue { get; } |
| | | 37 | | protected abstract SqlServerSubscriberOptions SubscriberOptions { get; } |
| | | 38 | | protected abstract SqlServerSubscriberRole Role { get; } |
| | | 39 | | protected abstract Task HandleMessageAsync(SqlServerTransportDelivery delivery, CancellationToken cancellationToken) |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | | 42 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 43 | | { |
| | 1 | 44 | | SqlServerTransportOptionsValidator.ValidateSubscriber(Options, SubscriberOptions, Role.ToString()); |
| | | 45 | | |
| | 1 | 46 | | var failures = 0; |
| | 1 | 47 | | while (!stoppingToken.IsCancellationRequested) |
| | | 48 | | { |
| | | 49 | | try |
| | | 50 | | { |
| | 1 | 51 | | await RunSubscriberAsync(stoppingToken).ConfigureAwait(false); |
| | 1 | 52 | | return; |
| | | 53 | | } |
| | 1 | 54 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 55 | | { |
| | 1 | 56 | | return; |
| | | 57 | | } |
| | 1 | 58 | | catch (Exception ex) when (!stoppingToken.IsCancellationRequested) |
| | | 59 | | { |
| | 1 | 60 | | failures++; |
| | 1 | 61 | | var delay = AsyncResponseRetry.Backoff(failures, Options.SubscriberRetryBaseDelay, Options.SubscriberRet |
| | 1 | 62 | | Logger.LogWarning(ex, "SQL Server subscriber failed for queue {Queue} ({Role}); retrying in {RetryDelay} |
| | 1 | 63 | | await Task.Delay(delay, stoppingToken).ConfigureAwait(false); |
| | | 64 | | } |
| | | 65 | | } |
| | 1 | 66 | | } |
| | | 67 | | |
| | | 68 | | private async Task RunSubscriberAsync(CancellationToken stoppingToken) |
| | | 69 | | { |
| | 1 | 70 | | await _store.EnsureCreatedAsync(stoppingToken).ConfigureAwait(false); |
| | | 71 | | |
| | | 72 | | // Same-process wake: publishes to this queue (or a NAK release, queue == null) signal the |
| | | 73 | | // loop directly since SQL Server has no LISTEN/NOTIFY; cross-process publishes are picked up |
| | | 74 | | // by the EmptyPollDelay poll below. |
| | 1 | 75 | | Action<string?> onPublished = queue => |
| | 1 | 76 | | { |
| | 1 | 77 | | if (queue is null || string.Equals(queue, Queue, StringComparison.Ordinal)) |
| | 1 | 78 | | _signals.Writer.TryWrite(true); |
| | 1 | 79 | | }; |
| | 1 | 80 | | _store.MessagePublished += onPublished; |
| | | 81 | | |
| | 1 | 82 | | await using var dispatcher = new SqlServerMessageDispatcher( |
| | 1 | 83 | | HandleMessageAsync, |
| | 1 | 84 | | Options, |
| | 1 | 85 | | SubscriberOptions, |
| | 1 | 86 | | Logger, |
| | 1 | 87 | | Role); |
| | | 88 | | |
| | 1 | 89 | | Logger.LogInformation( |
| | 1 | 90 | | "SQL Server subscriber started. Queue: {Queue}. Role: {Role}. AckMode: {AckMode}.", |
| | 1 | 91 | | Queue, |
| | 1 | 92 | | Role, |
| | 1 | 93 | | SubscriberOptions.AckMode); |
| | | 94 | | |
| | | 95 | | try |
| | | 96 | | { |
| | 1 | 97 | | while (!stoppingToken.IsCancellationRequested) |
| | | 98 | | { |
| | 1 | 99 | | var claimed = 0; |
| | 1 | 100 | | await foreach (var delivery in _store.ClaimBatchAsync(Queue, SubscriberOptions.BatchSize, Options.LockTi |
| | | 101 | | { |
| | 1 | 102 | | claimed++; |
| | 1 | 103 | | await dispatcher.HandleAsync(delivery, stoppingToken).ConfigureAwait(false); |
| | | 104 | | } |
| | | 105 | | |
| | 1 | 106 | | if (claimed > 0) |
| | | 107 | | continue; |
| | | 108 | | |
| | 1 | 109 | | await WaitForSignalOrDelayAsync(stoppingToken).ConfigureAwait(false); |
| | | 110 | | } |
| | 1 | 111 | | } |
| | | 112 | | finally |
| | | 113 | | { |
| | 1 | 114 | | _store.MessagePublished -= onPublished; |
| | | 115 | | } |
| | 1 | 116 | | } |
| | | 117 | | |
| | | 118 | | private async Task WaitForSignalOrDelayAsync(CancellationToken cancellationToken) |
| | | 119 | | { |
| | 1 | 120 | | var delay = Task.Delay(SubscriberOptions.EmptyPollDelay, cancellationToken); |
| | 1 | 121 | | var signal = _signals.Reader.WaitToReadAsync(cancellationToken).AsTask(); |
| | 1 | 122 | | var completed = await Task.WhenAny(delay, signal).ConfigureAwait(false); |
| | 1 | 123 | | if (completed == signal) |
| | | 124 | | { |
| | 1 | 125 | | await signal.ConfigureAwait(false); |
| | 1 | 126 | | while (_signals.Reader.TryRead(out _)) |
| | | 127 | | { |
| | | 128 | | } |
| | | 129 | | } |
| | 1 | 130 | | } |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | /// <summary>Consumes worker-job rows and executes them through the AsyncResponse ingress.</summary> |
| | | 134 | | internal sealed class SqlServerWorkerSubscriber : SqlServerSubscriberService |
| | | 135 | | { |
| | | 136 | | private readonly IAsyncResponseIngress _ingress; |
| | | 137 | | |
| | | 138 | | public SqlServerWorkerSubscriber( |
| | | 139 | | IOptions<SqlServerAsyncResponseTransportOptions> options, |
| | | 140 | | SqlServerTransportStore store, |
| | | 141 | | IAsyncResponseIngress ingress, |
| | | 142 | | ILogger<SqlServerWorkerSubscriber> logger) |
| | | 143 | | : base(options, store, logger) |
| | | 144 | | => _ingress = ingress; |
| | | 145 | | |
| | | 146 | | protected override string Queue => Options.WorkerQueue; |
| | | 147 | | protected override SqlServerSubscriberOptions SubscriberOptions => Options.WorkerSubscriber; |
| | | 148 | | protected override SqlServerSubscriberRole Role => SqlServerSubscriberRole.Worker; |
| | | 149 | | |
| | | 150 | | protected override Task HandleMessageAsync(SqlServerTransportDelivery delivery, CancellationToken cancellationToken) |
| | | 151 | | => _ingress.HandleWorkerMessageAsync(delivery.Payload); |
| | | 152 | | } |
| | | 153 | | |
| | | 154 | | /// <summary>Consumes response rows and feeds them into the AsyncResponse ingress.</summary> |
| | | 155 | | internal sealed class SqlServerResponseIngressSubscriber : SqlServerSubscriberService |
| | | 156 | | { |
| | | 157 | | private readonly IAsyncResponseIngress _ingress; |
| | | 158 | | |
| | | 159 | | public SqlServerResponseIngressSubscriber( |
| | | 160 | | IOptions<SqlServerAsyncResponseTransportOptions> options, |
| | | 161 | | SqlServerTransportStore store, |
| | | 162 | | IAsyncResponseIngress ingress, |
| | | 163 | | ILogger<SqlServerResponseIngressSubscriber> logger) |
| | | 164 | | : base(options, store, logger) |
| | | 165 | | => _ingress = ingress; |
| | | 166 | | |
| | | 167 | | protected override string Queue => Options.ResponseQueue; |
| | | 168 | | protected override SqlServerSubscriberOptions SubscriberOptions => Options.ResponseSubscriber; |
| | | 169 | | protected override SqlServerSubscriberRole Role => SqlServerSubscriberRole.ResponseIngress; |
| | | 170 | | |
| | | 171 | | protected override Task HandleMessageAsync(SqlServerTransportDelivery delivery, CancellationToken cancellationToken) |
| | | 172 | | { |
| | | 173 | | var correlationId = SqlServerCorrelationIdExtractor.Extract(delivery.Headers, delivery.Payload, Options); |
| | | 174 | | return _ingress.HandleResponseMessageAsync(delivery.Payload, correlationId); |
| | | 175 | | } |
| | | 176 | | } |