| | | 1 | | using Google.Api.Gax; |
| | | 2 | | using Google.Cloud.PubSub.V1; |
| | | 3 | | using Microsoft.Extensions.Hosting; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | |
| | | 7 | | namespace AsyncResponse.Transports.GooglePubSub; |
| | | 8 | | |
| | | 9 | | internal abstract class GooglePubSubSubscriberService : BackgroundService |
| | | 10 | | { |
| | | 11 | | private readonly Func<SubscriptionName, GooglePubSubSubscriberOptions, Task<IGooglePubSubSubscriberClient>> _subscri |
| | | 12 | | |
| | | 13 | | /// <summary>Runs the GooglePubSubSubscriberService operation.</summary> |
| | | 14 | | protected GooglePubSubSubscriberService( |
| | | 15 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | | 16 | | ILogger logger) |
| | 392 | 17 | | : this(options, logger, CreateSubscriberAsync) |
| | | 18 | | { |
| | 392 | 19 | | } |
| | | 20 | | |
| | | 21 | | /// <summary>Runs the GooglePubSubSubscriberService operation.</summary> |
| | 434 | 22 | | protected GooglePubSubSubscriberService( |
| | 434 | 23 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | 434 | 24 | | ILogger logger, |
| | 434 | 25 | | Func<SubscriptionName, GooglePubSubSubscriberOptions, Task<IGooglePubSubSubscriberClient>> subscriberFactory) |
| | | 26 | | { |
| | 434 | 27 | | Options = options.Value; |
| | 434 | 28 | | Logger = logger; |
| | 434 | 29 | | _subscriberFactory = subscriberFactory; |
| | 434 | 30 | | } |
| | | 31 | | |
| | 4767 | 32 | | protected GooglePubSubAsyncResponseOptions Options { get; } |
| | 1299 | 33 | | protected ILogger Logger { get; } |
| | | 34 | | |
| | | 35 | | protected abstract string SubscriptionId { get; } |
| | | 36 | | protected abstract GooglePubSubSubscriberOptions SubscriberOptions { get; } |
| | | 37 | | protected abstract GooglePubSubSubscriberRole SubscriberRole { get; } |
| | | 38 | | /// <summary>Handles the delivered message.</summary> |
| | | 39 | | protected abstract Task HandleMessageAsync(PubsubMessage message, CancellationToken cancellationToken); |
| | | 40 | | |
| | | 41 | | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] |
| | | 42 | | private static async Task<IGooglePubSubSubscriberClient> CreateSubscriberAsync( |
| | | 43 | | SubscriptionName subscriptionName, |
| | | 44 | | GooglePubSubSubscriberOptions subscriberOptions) |
| | | 45 | | { |
| | | 46 | | var subscriber = await CreateSubscriberBuilder(subscriptionName, subscriberOptions).BuildAsync().ConfigureAwait( |
| | | 47 | | return new GooglePubSubSubscriberClientAdapter(subscriber); |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Every streaming-pull knob is set explicitly. Left to the SDK they default to one connection |
| | | 52 | | /// per CPU, 1,000 outstanding messages <em>per connection</em> and a 60-minute ack-extension |
| | | 53 | | /// ceiling nothing in this package knew about — so a process leased thousands of jobs it was |
| | | 54 | | /// not running, and a handler outliving the ceiling had its message redelivered mid-run with |
| | | 55 | | /// no option to raise it and nothing advertising it to the durable-flow engine. |
| | | 56 | | /// </summary> |
| | | 57 | | internal static SubscriberClientBuilder CreateSubscriberBuilder( |
| | | 58 | | SubscriptionName subscriptionName, |
| | | 59 | | GooglePubSubSubscriberOptions subscriberOptions) |
| | | 60 | | { |
| | | 61 | | // EmulatorOrProduction honors PUBSUB_EMULATOR_HOST when present (local dev / tests) and uses |
| | | 62 | | // real Google Cloud otherwise — no behavior change in production. |
| | 396 | 63 | | return new SubscriberClientBuilder |
| | 396 | 64 | | { |
| | 396 | 65 | | SubscriptionName = subscriptionName, |
| | 396 | 66 | | EmulatorDetection = EmulatorDetection.EmulatorOrProduction, |
| | 396 | 67 | | ClientCount = subscriberOptions.ClientCount, |
| | 396 | 68 | | Settings = new SubscriberClient.Settings |
| | 396 | 69 | | { |
| | 396 | 70 | | MaxTotalAckExtension = subscriberOptions.MaxTotalAckExtension, |
| | 396 | 71 | | // In early-ACK mode, bound the streaming pull to the background queue capacity so the client |
| | 396 | 72 | | // never holds more un-ACKed messages than the dispatcher can accept. Combined with the |
| | 396 | 73 | | // dispatcher's write-side backpressure this keeps queue-full NACKs (which burn a configured |
| | 396 | 74 | | // DeadLetterPolicy's delivery attempts) out of steady-state operation. |
| | 396 | 75 | | FlowControlSettings = subscriberOptions.AckMode is GooglePubSubAckMode.AckAfterEnqueue |
| | 396 | 76 | | ? new Google.Api.Gax.FlowControlSettings( |
| | 396 | 77 | | maxOutstandingElementCount: subscriberOptions.BackgroundQueueCapacity, |
| | 396 | 78 | | maxOutstandingByteCount: null) |
| | 396 | 79 | | : new Google.Api.Gax.FlowControlSettings( |
| | 396 | 80 | | maxOutstandingElementCount: subscriberOptions.MaxOutstandingMessages, |
| | 396 | 81 | | maxOutstandingByteCount: subscriberOptions.MaxOutstandingBytes) |
| | 396 | 82 | | } |
| | 396 | 83 | | }; |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <summary>Runs this background operation until cancellation is requested.</summary> |
| | | 87 | | /// <summary> |
| | | 88 | | /// Validates subscriber options here rather than at the top of <c>ExecuteAsync</c>: since |
| | | 89 | | /// Microsoft.Extensions.Hosting.Abstractions 10.0.10, <c>BackgroundService.StartAsync</c> no |
| | | 90 | | /// longer runs <c>ExecuteAsync</c> inline, so a throw there surfaces only through the host's |
| | | 91 | | /// background-exception handling — or never, when a fast stop discards the queued work — |
| | | 92 | | /// instead of failing host startup synchronously. |
| | | 93 | | /// </summary> |
| | | 94 | | public override Task StartAsync(CancellationToken cancellationToken) |
| | | 95 | | { |
| | 424 | 96 | | _ = GooglePubSubOptionsValidator.Required(Options.ProjectId, nameof(Options.ProjectId)); |
| | 422 | 97 | | _ = SubscriptionId; // Resolving the id enforces its Required check at startup too. |
| | 422 | 98 | | GooglePubSubMessageDispatcher.ValidateOptions(Options, SubscriberOptions, SubscriberRole); |
| | 414 | 99 | | return base.StartAsync(cancellationToken); |
| | | 100 | | } |
| | | 101 | | |
| | | 102 | | protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| | | 103 | | { |
| | 414 | 104 | | var projectId = GooglePubSubOptionsValidator.Required(Options.ProjectId, nameof(Options.ProjectId)); |
| | 414 | 105 | | var subscriptionId = SubscriptionId; |
| | 414 | 106 | | var subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId); |
| | | 107 | | |
| | | 108 | | // The transport intentionally has no MaxDeliveryAttempts and no library-managed dead-letter |
| | | 109 | | // queue for Pub/Sub: capping redelivery is delegated to the subscription's native |
| | | 110 | | // DeadLetterPolicy. The client cannot cheaply probe whether one is configured, so tell the |
| | | 111 | | // operator unconditionally instead of failing silently forever on a poison message. |
| | | 112 | | // The same goes for the RetryPolicy: a subscription without one redelivers a NACKed message |
| | | 113 | | // immediately, so a transient fault burns a DeadLetterPolicy's whole delivery-attempt budget |
| | | 114 | | // in about a second and dead-letters every message that arrives during the blip. The |
| | | 115 | | // package never creates subscriptions and reading one needs an admin client plus |
| | | 116 | | // pubsub.subscriptions.get, which a consumer identity commonly lacks — so say it here too. |
| | 414 | 117 | | Logger.LogWarning( |
| | 414 | 118 | | "Pub/Sub redelivery is unbounded for subscription {Subscription} ({Role}): the transport enforces no deliver |
| | 414 | 119 | | + "Configure a DeadLetterPolicy on the subscription to cap redeliveries of failing messages, and a RetryPoli |
| | 414 | 120 | | + "without one Pub/Sub redelivers a NACKed message immediately, so a transient failure exhausts the DeadLett |
| | 414 | 121 | | subscriptionName.ToString(), |
| | 414 | 122 | | SubscriberRole); |
| | | 123 | | |
| | | 124 | | // The dispatcher outlives every supervised attempt; only host stop drains it. A streaming-pull |
| | | 125 | | // fault (network blip, UNAVAILABLE) ends an attempt, not the host — yet scoped to the attempt, |
| | | 126 | | // the early-ACK dispatcher's dispose ran its STOP-TIME drain on each one: consumption paused |
| | | 127 | | // for up to BackgroundDrainTimeout, then queued work already ACKed at the broker (which |
| | | 128 | | // Pub/Sub will never redeliver) was refused as "drain budget lapsed" on a host that was not |
| | | 129 | | // stopping. It captures nothing per attempt, so every rebuilt client feeds the same queue. |
| | 414 | 130 | | await using var dispatcher = GooglePubSubMessageDispatcher.Create( |
| | 414 | 131 | | HandleMessageAsync, |
| | 414 | 132 | | Options, |
| | 414 | 133 | | SubscriberOptions, |
| | 414 | 134 | | Logger, |
| | 414 | 135 | | subscriptionId, |
| | 414 | 136 | | SubscriberRole); |
| | | 137 | | |
| | 414 | 138 | | await SubscriberSupervisor.RunAsync( |
| | 465 | 139 | | ct => RunSubscriberAsync(subscriptionName, dispatcher, ct), |
| | 414 | 140 | | stoppingToken, |
| | 55 | 141 | | failures => AsyncResponseRetry.Backoff( |
| | 55 | 142 | | failures, |
| | 55 | 143 | | Options.SubscriberRetryBaseDelay, |
| | 55 | 144 | | Options.SubscriberRetryMaxDelay), |
| | 467 | 145 | | (ex, retryDelay) => Logger.LogWarning( |
| | 467 | 146 | | ex, |
| | 467 | 147 | | "Pub/Sub subscriber failed for subscription {Subscription} ({Role}); retrying in {RetryDelay}.", |
| | 467 | 148 | | subscriptionName.ToString(), |
| | 467 | 149 | | SubscriberRole, |
| | 467 | 150 | | retryDelay)).ConfigureAwait(false); |
| | 412 | 151 | | } |
| | | 152 | | |
| | | 153 | | private async Task RunSubscriberAsync( |
| | | 154 | | SubscriptionName subscriptionName, |
| | | 155 | | GooglePubSubMessageDispatcher dispatcher, |
| | | 156 | | CancellationToken stoppingToken) |
| | | 157 | | { |
| | 465 | 158 | | var subscriber = await _subscriberFactory(subscriptionName, SubscriberOptions).ConfigureAwait(false); |
| | | 159 | | try |
| | | 160 | | { |
| | 418 | 161 | | Logger.LogInformation( |
| | 418 | 162 | | "Pub/Sub subscriber started. Subscription: {Subscription}. Role: {Role}. AckMode: {AckMode}.", |
| | 418 | 163 | | subscriptionName.ToString(), |
| | 418 | 164 | | SubscriberRole, |
| | 418 | 165 | | SubscriberOptions.AckMode); |
| | | 166 | | |
| | 418 | 167 | | var runTask = subscriber.StartAsync(dispatcher.HandleAsync); |
| | | 168 | | |
| | | 169 | | try |
| | | 170 | | { |
| | 418 | 171 | | await runTask.WaitAsync(stoppingToken).ConfigureAwait(false); |
| | 2 | 172 | | } |
| | 410 | 173 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 174 | | { |
| | 410 | 175 | | await subscriber.StopAsync( |
| | 410 | 176 | | new SubscriberClient.ShutdownOptions |
| | 410 | 177 | | { |
| | 410 | 178 | | Timeout = Options.ShutdownTimeout |
| | 410 | 179 | | }, |
| | 410 | 180 | | CancellationToken.None).ConfigureAwait(false); |
| | 410 | 181 | | await runTask.ConfigureAwait(false); |
| | | 182 | | } |
| | 412 | 183 | | } |
| | 0 | 184 | | catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) |
| | | 185 | | { |
| | | 186 | | // Graceful shutdown: the cancellation branch above already stopped the client. |
| | 0 | 187 | | throw; |
| | | 188 | | } |
| | 6 | 189 | | catch |
| | | 190 | | { |
| | | 191 | | // A non-shutdown failure abandons the streaming pull: release the client BEFORE the |
| | | 192 | | // retry loop builds a replacement, or its gRPC channels, pull connection and |
| | | 193 | | // ack-extension timers stay alive — one leaked client per rebuild. |
| | 6 | 194 | | await StopSubscriberQuietlyAsync(subscriber).ConfigureAwait(false); |
| | 6 | 195 | | throw; |
| | | 196 | | } |
| | 412 | 197 | | } |
| | | 198 | | |
| | | 199 | | /// <summary> |
| | | 200 | | /// Best-effort stop of a failed subscriber client, swallowing stop errors: StopAsync is the |
| | | 201 | | /// seam's only release primitive, and the caller is already propagating the original failure. |
| | | 202 | | /// </summary> |
| | | 203 | | private async Task StopSubscriberQuietlyAsync(IGooglePubSubSubscriberClient subscriber) |
| | | 204 | | { |
| | | 205 | | try |
| | | 206 | | { |
| | 6 | 207 | | await subscriber.StopAsync( |
| | 6 | 208 | | new SubscriberClient.ShutdownOptions |
| | 6 | 209 | | { |
| | 6 | 210 | | Timeout = Options.ShutdownTimeout |
| | 6 | 211 | | }, |
| | 6 | 212 | | CancellationToken.None).ConfigureAwait(false); |
| | 6 | 213 | | } |
| | 0 | 214 | | catch (Exception ex) |
| | | 215 | | { |
| | 0 | 216 | | Logger.LogDebug(ex, "Best-effort stop of a failed Pub/Sub subscriber client did not complete cleanly."); |
| | 0 | 217 | | } |
| | 6 | 218 | | } |
| | | 219 | | |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | internal sealed class GooglePubSubWorkerSubscriber : GooglePubSubSubscriberService |
| | | 223 | | { |
| | | 224 | | private readonly IAsyncResponseIngress _ingress; |
| | | 225 | | |
| | | 226 | | /// <summary>Runs the GooglePubSubWorkerSubscriber operation.</summary> |
| | | 227 | | public GooglePubSubWorkerSubscriber( |
| | | 228 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | | 229 | | IAsyncResponseIngress ingress, |
| | | 230 | | ILogger<GooglePubSubWorkerSubscriber> logger) |
| | | 231 | | : base(options, logger) |
| | | 232 | | { |
| | | 233 | | _ingress = ingress; |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | internal GooglePubSubWorkerSubscriber( |
| | | 237 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | | 238 | | IAsyncResponseIngress ingress, |
| | | 239 | | ILogger<GooglePubSubWorkerSubscriber> logger, |
| | | 240 | | Func<SubscriptionName, GooglePubSubSubscriberOptions, Task<IGooglePubSubSubscriberClient>> subscriberFactory) |
| | | 241 | | : base(options, logger, subscriberFactory) |
| | | 242 | | { |
| | | 243 | | _ingress = ingress; |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | protected override string SubscriptionId |
| | | 247 | | => GooglePubSubOptionsValidator.Required(Options.WorkerSubscriptionId, nameof(Options.WorkerSubscriptionId)); |
| | | 248 | | |
| | | 249 | | protected override GooglePubSubSubscriberOptions SubscriberOptions => Options.WorkerSubscriber; |
| | | 250 | | protected override GooglePubSubSubscriberRole SubscriberRole => GooglePubSubSubscriberRole.Worker; |
| | | 251 | | |
| | | 252 | | /// <summary>Handles the delivered message.</summary> |
| | | 253 | | protected override Task HandleMessageAsync(PubsubMessage message, CancellationToken cancellationToken) |
| | | 254 | | => _ingress.HandleWorkerMessageAsync(message.Data.ToStringUtf8()); |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | internal sealed class GooglePubSubResponseIngressSubscriber : GooglePubSubSubscriberService |
| | | 258 | | { |
| | | 259 | | private readonly IAsyncResponseIngress _ingress; |
| | | 260 | | |
| | | 261 | | /// <summary>Runs the GooglePubSubResponseIngressSubscriber operation.</summary> |
| | | 262 | | public GooglePubSubResponseIngressSubscriber( |
| | | 263 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | | 264 | | IAsyncResponseIngress ingress, |
| | | 265 | | ILogger<GooglePubSubResponseIngressSubscriber> logger) |
| | | 266 | | : base(options, logger) |
| | | 267 | | { |
| | | 268 | | _ingress = ingress; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | internal GooglePubSubResponseIngressSubscriber( |
| | | 272 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | | 273 | | IAsyncResponseIngress ingress, |
| | | 274 | | ILogger<GooglePubSubResponseIngressSubscriber> logger, |
| | | 275 | | Func<SubscriptionName, GooglePubSubSubscriberOptions, Task<IGooglePubSubSubscriberClient>> subscriberFactory) |
| | | 276 | | : base(options, logger, subscriberFactory) |
| | | 277 | | { |
| | | 278 | | _ingress = ingress; |
| | | 279 | | } |
| | | 280 | | |
| | | 281 | | protected override string SubscriptionId |
| | | 282 | | => GooglePubSubOptionsValidator.Required(Options.ResponseSubscriptionId, nameof(Options.ResponseSubscriptionId)) |
| | | 283 | | |
| | | 284 | | protected override GooglePubSubSubscriberOptions SubscriberOptions => Options.ResponseSubscriber; |
| | | 285 | | protected override GooglePubSubSubscriberRole SubscriberRole => GooglePubSubSubscriberRole.ResponseIngress; |
| | | 286 | | |
| | | 287 | | /// <summary>Handles the delivered message.</summary> |
| | | 288 | | protected override Task HandleMessageAsync(PubsubMessage message, CancellationToken cancellationToken) |
| | | 289 | | { |
| | | 290 | | var messageJson = message.Data.ToStringUtf8(); |
| | | 291 | | var correlationId = !_ingress.IsOverInboundBudget(messageJson) |
| | | 292 | | ? GooglePubSubCorrelationIdExtractor.Extract(message, messageJson, Options) |
| | | 293 | | : null; |
| | | 294 | | return _ingress.HandleResponseMessageAsync(messageJson, correlationId); |
| | | 295 | | } |
| | | 296 | | } |