| | | 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.PostgreSQL; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Base hosted service that consumes one PostgreSQL queue and routes rows to AsyncResponse ingress |
| | | 10 | | /// with configured acknowledgement, redelivery, and dead-letter behavior. |
| | | 11 | | /// </summary> |
| | | 12 | | internal abstract class PostgreSqlSubscriberService : BackgroundService |
| | | 13 | | { |
| | | 14 | | private readonly PostgreSqlTransportStore _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 PostgreSqlSubscriberService( |
| | 3 | 23 | | IOptions<PostgreSqlAsyncResponseTransportOptions> options, |
| | 3 | 24 | | PostgreSqlTransportStore store, |
| | 3 | 25 | | ILogger logger) |
| | | 26 | | { |
| | 3 | 27 | | Options = options.Value; |
| | 3 | 28 | | PostgreSqlTransportOptionsValidator.ValidateCommon(Options); |
| | 3 | 29 | | _store = store; |
| | 3 | 30 | | Logger = logger; |
| | 3 | 31 | | } |
| | | 32 | | |
| | | 33 | | protected PostgreSqlAsyncResponseTransportOptions Options { get; } |
| | | 34 | | protected ILogger Logger { get; } |
| | | 35 | | |
| | | 36 | | protected abstract string Queue { get; } |
| | | 37 | | protected abstract PostgreSqlSubscriberOptions SubscriberOptions { get; } |
| | | 38 | | protected abstract PostgreSqlSubscriberRole Role { get; } |
| | | 39 | | protected abstract Task HandleMessageAsync(PostgreSqlTransportDelivery delivery, CancellationToken cancellationToken |
| | | 40 | | |
| | | 41 | | /// <inheritdoc /> |
| | | 42 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 43 | | { |
| | 1 | 44 | | PostgreSqlTransportOptionsValidator.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, "PostgreSQL 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); |
| | 1 | 71 | | using var signalCts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); |
| | 1 | 72 | | var listenTask = Task.Run(() => ListenLoopAsync(signalCts.Token), signalCts.Token); |
| | | 73 | | |
| | 1 | 74 | | await using var dispatcher = new PostgreSqlMessageDispatcher( |
| | 1 | 75 | | HandleMessageAsync, |
| | 1 | 76 | | Options, |
| | 1 | 77 | | SubscriberOptions, |
| | 1 | 78 | | Logger, |
| | 1 | 79 | | Role); |
| | | 80 | | |
| | 1 | 81 | | Logger.LogInformation( |
| | 1 | 82 | | "PostgreSQL subscriber started. Queue: {Queue}. Role: {Role}. AckMode: {AckMode}.", |
| | 1 | 83 | | Queue, |
| | 1 | 84 | | Role, |
| | 1 | 85 | | SubscriberOptions.AckMode); |
| | | 86 | | |
| | | 87 | | try |
| | | 88 | | { |
| | 1 | 89 | | while (!stoppingToken.IsCancellationRequested) |
| | | 90 | | { |
| | 1 | 91 | | var claimed = 0; |
| | 1 | 92 | | await foreach (var delivery in _store.ClaimBatchAsync(Queue, SubscriberOptions.BatchSize, Options.LockTi |
| | | 93 | | { |
| | 1 | 94 | | claimed++; |
| | 1 | 95 | | await dispatcher.HandleAsync(delivery, stoppingToken).ConfigureAwait(false); |
| | | 96 | | } |
| | | 97 | | |
| | 1 | 98 | | if (claimed > 0) |
| | | 99 | | continue; |
| | | 100 | | |
| | 1 | 101 | | await WaitForSignalOrDelayAsync(stoppingToken).ConfigureAwait(false); |
| | | 102 | | } |
| | | 103 | | } |
| | | 104 | | finally |
| | | 105 | | { |
| | 1 | 106 | | await signalCts.CancelAsync().ConfigureAwait(false); |
| | | 107 | | try |
| | | 108 | | { |
| | 1 | 109 | | await listenTask.WaitAsync(Options.ShutdownTimeout).ConfigureAwait(false); |
| | 1 | 110 | | } |
| | 0 | 111 | | catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) |
| | | 112 | | { |
| | 1 | 113 | | } |
| | | 114 | | } |
| | 1 | 115 | | } |
| | | 116 | | |
| | | 117 | | private async Task ListenLoopAsync(CancellationToken cancellationToken) |
| | | 118 | | { |
| | | 119 | | try |
| | | 120 | | { |
| | 1 | 121 | | await _store.ExecuteListenAsync(() => |
| | 1 | 122 | | { |
| | 1 | 123 | | _signals.Writer.TryWrite(true); |
| | 1 | 124 | | return Task.CompletedTask; |
| | 1 | 125 | | }, cancellationToken).ConfigureAwait(false); |
| | 1 | 126 | | } |
| | 1 | 127 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 128 | | { |
| | 1 | 129 | | } |
| | 1 | 130 | | catch (Exception ex) |
| | | 131 | | { |
| | 1 | 132 | | Logger.LogDebug(ex, "PostgreSQL LISTEN helper for queue {Queue} stopped; polling continues.", Queue); |
| | 1 | 133 | | } |
| | 1 | 134 | | } |
| | | 135 | | |
| | | 136 | | private async Task WaitForSignalOrDelayAsync(CancellationToken cancellationToken) |
| | | 137 | | { |
| | 1 | 138 | | var delay = Task.Delay(SubscriberOptions.EmptyPollDelay, cancellationToken); |
| | 1 | 139 | | var signal = _signals.Reader.WaitToReadAsync(cancellationToken).AsTask(); |
| | 1 | 140 | | var completed = await Task.WhenAny(delay, signal).ConfigureAwait(false); |
| | 1 | 141 | | if (completed == signal) |
| | | 142 | | { |
| | 1 | 143 | | await signal.ConfigureAwait(false); |
| | 1 | 144 | | while (_signals.Reader.TryRead(out _)) |
| | | 145 | | { |
| | | 146 | | } |
| | | 147 | | } |
| | 1 | 148 | | } |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | /// <summary>Consumes worker-job rows and executes them through the AsyncResponse ingress.</summary> |
| | | 152 | | internal sealed class PostgreSqlWorkerSubscriber : PostgreSqlSubscriberService |
| | | 153 | | { |
| | | 154 | | private readonly IAsyncResponseIngress _ingress; |
| | | 155 | | |
| | | 156 | | public PostgreSqlWorkerSubscriber( |
| | | 157 | | IOptions<PostgreSqlAsyncResponseTransportOptions> options, |
| | | 158 | | PostgreSqlTransportStore store, |
| | | 159 | | IAsyncResponseIngress ingress, |
| | | 160 | | ILogger<PostgreSqlWorkerSubscriber> logger) |
| | | 161 | | : base(options, store, logger) |
| | | 162 | | => _ingress = ingress; |
| | | 163 | | |
| | | 164 | | protected override string Queue => Options.WorkerQueue; |
| | | 165 | | protected override PostgreSqlSubscriberOptions SubscriberOptions => Options.WorkerSubscriber; |
| | | 166 | | protected override PostgreSqlSubscriberRole Role => PostgreSqlSubscriberRole.Worker; |
| | | 167 | | |
| | | 168 | | protected override Task HandleMessageAsync(PostgreSqlTransportDelivery delivery, CancellationToken cancellationToken |
| | | 169 | | => _ingress.HandleWorkerMessageAsync(delivery.Payload); |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <summary>Consumes response rows and feeds them into the AsyncResponse ingress.</summary> |
| | | 173 | | internal sealed class PostgreSqlResponseIngressSubscriber : PostgreSqlSubscriberService |
| | | 174 | | { |
| | | 175 | | private readonly IAsyncResponseIngress _ingress; |
| | | 176 | | |
| | | 177 | | public PostgreSqlResponseIngressSubscriber( |
| | | 178 | | IOptions<PostgreSqlAsyncResponseTransportOptions> options, |
| | | 179 | | PostgreSqlTransportStore store, |
| | | 180 | | IAsyncResponseIngress ingress, |
| | | 181 | | ILogger<PostgreSqlResponseIngressSubscriber> logger) |
| | | 182 | | : base(options, store, logger) |
| | | 183 | | => _ingress = ingress; |
| | | 184 | | |
| | | 185 | | protected override string Queue => Options.ResponseQueue; |
| | | 186 | | protected override PostgreSqlSubscriberOptions SubscriberOptions => Options.ResponseSubscriber; |
| | | 187 | | protected override PostgreSqlSubscriberRole Role => PostgreSqlSubscriberRole.ResponseIngress; |
| | | 188 | | |
| | | 189 | | protected override Task HandleMessageAsync(PostgreSqlTransportDelivery delivery, CancellationToken cancellationToken |
| | | 190 | | { |
| | | 191 | | var correlationId = PostgreSqlCorrelationIdExtractor.Extract(delivery.Headers, delivery.Payload, Options); |
| | | 192 | | return _ingress.HandleResponseMessageAsync(delivery.Payload, correlationId); |
| | | 193 | | } |
| | | 194 | | } |