| | | 1 | | using Google.Api.Gax; |
| | | 2 | | using Google.Cloud.PubSub.V1; |
| | | 3 | | using Google.Protobuf; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Text.Json; |
| | | 7 | | |
| | | 8 | | namespace AsyncResponse.Transports.GooglePubSub; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Publishes <see cref="WorkerJobEnvelope"/> messages to a Google Pub/Sub topic. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <remarks> |
| | | 14 | | /// The publisher client is created lazily and re-created on demand: a transient build failure when the |
| | | 15 | | /// first job is published does not permanently break the transport (a faulted build attempt is not cached). |
| | | 16 | | /// </remarks> |
| | | 17 | | public sealed class GooglePubSubWorkerTransport : IWorkerTransportInFlightLimit, IAsyncDisposable |
| | | 18 | | { |
| | | 19 | | private readonly GooglePubSubAsyncResponseOptions _options; |
| | | 20 | | private readonly Func<CancellationToken, Task<IGooglePubSubPublisherClient>> _publisherFactory; |
| | 241 | 21 | | private readonly SemaphoreSlim _publisherGate = new(1, 1); |
| | | 22 | | private IGooglePubSubPublisherClient? _publisher; |
| | | 23 | | private int _disposeGate; |
| | | 24 | | private bool _disposed; |
| | | 25 | | |
| | | 26 | | /// <summary>Runs the GooglePubSubWorkerTransport operation.</summary> |
| | | 27 | | public GooglePubSubWorkerTransport(IOptions<GooglePubSubAsyncResponseOptions> options) |
| | 407 | 28 | | : this(options, cancellationToken => CreatePublisherAsync(options.Value, cancellationToken)) |
| | | 29 | | { |
| | 205 | 30 | | } |
| | | 31 | | |
| | 241 | 32 | | internal GooglePubSubWorkerTransport( |
| | 241 | 33 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | 241 | 34 | | Func<CancellationToken, Task<IGooglePubSubPublisherClient>> publisherFactory) |
| | | 35 | | { |
| | 241 | 36 | | _options = options.Value; |
| | 241 | 37 | | _ = GooglePubSubOptionsValidator.Required(_options.ProjectId, nameof(_options.ProjectId)); |
| | 237 | 38 | | _ = GooglePubSubOptionsValidator.Required(_options.WorkerTopicId, nameof(_options.WorkerTopicId)); |
| | 233 | 39 | | GooglePubSubOptionsValidator.ValidateTimeouts(_options); |
| | | 40 | | // Advertised below as the in-flight ceiling, whose contract is "positive": check it here |
| | | 41 | | // as well as in the subscriber, which may start later than the first consumer of the value. |
| | 233 | 42 | | GooglePubSubOptionsValidator.ValidateMaxTotalAckExtension( |
| | 233 | 43 | | _options.WorkerSubscriber, |
| | 233 | 44 | | $"{nameof(GooglePubSubAsyncResponseOptions)}.{nameof(GooglePubSubAsyncResponseOptions.WorkerSubscriber)}"); |
| | 231 | 45 | | _publisherFactory = publisherFactory; |
| | 231 | 46 | | } |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// The worker subscriber's <see cref="GooglePubSubSubscriberOptions.MaxTotalAckExtension"/>: past |
| | | 50 | | /// it the Pub/Sub client stops extending the job's ack deadline and Pub/Sub redelivers the same |
| | | 51 | | /// job while its first handler is still running. <c>null</c> when the worker subscriber uses |
| | | 52 | | /// <see cref="GooglePubSubAckMode.AckAfterEnqueue"/> — the delivery is settled at enqueue, so no |
| | | 53 | | /// handler is ever held against the ceiling. |
| | | 54 | | /// <para> |
| | | 55 | | /// The subscriber and this publisher read the same options instance, so the value is the one the |
| | | 56 | | /// consuming side applies. Pub/Sub redelivers up to one ack deadline (60 seconds) <em>after</em> |
| | | 57 | | /// the extension lapses; advertising the extension itself keeps the engine on the safe side. |
| | | 58 | | /// </para> |
| | | 59 | | /// </summary> |
| | | 60 | | public TimeSpan? MaxInFlightDuration |
| | 246 | 61 | | => _options.WorkerSubscriber.AckMode is GooglePubSubAckMode.AckAfterEnqueue |
| | 246 | 62 | | ? null |
| | 246 | 63 | | : _options.WorkerSubscriber.MaxTotalAckExtension; |
| | | 64 | | |
| | | 65 | | private async Task<IGooglePubSubPublisherClient> GetPublisherAsync(CancellationToken cancellationToken) |
| | | 66 | | { |
| | 437 | 67 | | var publisher = Volatile.Read(ref _publisher); |
| | 437 | 68 | | if (publisher is not null) |
| | 215 | 69 | | return publisher; |
| | | 70 | | |
| | 222 | 71 | | await _publisherGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 72 | | try |
| | | 73 | | { |
| | 218 | 74 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 214 | 75 | | if (_publisher is not null) |
| | 2 | 76 | | return _publisher; |
| | | 77 | | |
| | | 78 | | // Assign only after the await succeeds, so a faulted build attempt is not cached and the next |
| | | 79 | | // publish retries instead of awaiting a permanently faulted task. The token reaches the |
| | | 80 | | // build itself (sibling parity): a stalled credential/metadata lookup or gRPC handshake |
| | | 81 | | // under this gate otherwise ignored the caller's — and the host's stopping — token. |
| | 212 | 82 | | var created = await _publisherFactory(cancellationToken).ConfigureAwait(false); |
| | 208 | 83 | | _publisher = created; |
| | 208 | 84 | | return created; |
| | | 85 | | } |
| | | 86 | | finally |
| | | 87 | | { |
| | 218 | 88 | | _publisherGate.Release(); |
| | | 89 | | } |
| | 425 | 90 | | } |
| | | 91 | | |
| | | 92 | | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] |
| | | 93 | | private static async Task<IGooglePubSubPublisherClient> CreatePublisherAsync( |
| | | 94 | | GooglePubSubAsyncResponseOptions options, |
| | | 95 | | CancellationToken cancellationToken) |
| | | 96 | | { |
| | | 97 | | var projectId = GooglePubSubOptionsValidator.Required(options.ProjectId, nameof(options.ProjectId)); |
| | | 98 | | var topicId = GooglePubSubOptionsValidator.Required(options.WorkerTopicId, nameof(options.WorkerTopicId)); |
| | | 99 | | var topicName = TopicName.FromProjectTopic(projectId, topicId); |
| | | 100 | | // EmulatorOrProduction honors PUBSUB_EMULATOR_HOST when present (local dev / tests) and uses |
| | | 101 | | // real Google Cloud otherwise — no behavior change in production. |
| | | 102 | | var publisher = await new PublisherClientBuilder |
| | | 103 | | { |
| | | 104 | | TopicName = topicName, |
| | | 105 | | EmulatorDetection = EmulatorDetection.EmulatorOrProduction |
| | | 106 | | }.BuildAsync(cancellationToken).ConfigureAwait(false); |
| | | 107 | | return new GooglePubSubPublisherClientAdapter(publisher); |
| | | 108 | | } |
| | | 109 | | |
| | | 110 | | /// <summary>Publishes the supplied message.</summary> |
| | | 111 | | public async Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | | 112 | | { |
| | 439 | 113 | | ArgumentNullException.ThrowIfNull(job); |
| | | 114 | | |
| | 437 | 115 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 437 | 116 | | "asyncresponse.worker.publish", |
| | 437 | 117 | | ActivityKind.Producer, |
| | 437 | 118 | | job.CorrelationId); |
| | 437 | 119 | | activity?.SetTag("asyncresponse.transport", "google_pubsub"); |
| | 437 | 120 | | activity?.SetTag("messaging.system", "gcp_pubsub"); |
| | 437 | 121 | | activity?.SetTag("messaging.destination.name", _options.WorkerTopicId); |
| | 437 | 122 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | 437 | 123 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 124 | | |
| | | 125 | | try |
| | | 126 | | { |
| | 437 | 127 | | var message = new PubsubMessage |
| | 437 | 128 | | { |
| | 437 | 129 | | Data = ByteString.CopyFromUtf8(AsyncResponseJson.Serialize(job)) |
| | 437 | 130 | | }; |
| | | 131 | | |
| | 437 | 132 | | if (!string.IsNullOrWhiteSpace(job.CorrelationId)) |
| | 124 | 133 | | message.Attributes[_options.CorrelationIdAttribute] = job.CorrelationId; |
| | | 134 | | |
| | 437 | 135 | | var publisher = await GetPublisherAsync(cancellationToken).ConfigureAwait(false); |
| | 425 | 136 | | var messageId = await publisher.PublishAsync(message, cancellationToken).ConfigureAwait(false); |
| | 423 | 137 | | activity?.SetTag("messaging.message.id", messageId); |
| | 423 | 138 | | } |
| | 14 | 139 | | catch (Exception ex) |
| | | 140 | | { |
| | 14 | 141 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 14 | 142 | | throw; |
| | | 143 | | } |
| | 423 | 144 | | } |
| | | 145 | | |
| | | 146 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 147 | | public async ValueTask DisposeAsync() |
| | | 148 | | { |
| | 414 | 149 | | if (Interlocked.Exchange(ref _disposeGate, 1) != 0) |
| | 197 | 150 | | return; |
| | | 151 | | |
| | 217 | 152 | | await _publisherGate.WaitAsync().ConfigureAwait(false); |
| | | 153 | | try |
| | | 154 | | { |
| | 217 | 155 | | _disposed = true; |
| | 217 | 156 | | if (_publisher is not null) |
| | | 157 | | { |
| | | 158 | | // Best effort, like the RabbitMQ/Azure Service Bus worker transports' closes: the |
| | | 159 | | // SDK CANCELS the returned task when the timeout expires before the backlog |
| | | 160 | | // flushes, and this is a container-created singleton — a throw here escapes |
| | | 161 | | // ServiceProvider.DisposeAsync and aborts the disposal of every service after it. |
| | | 162 | | try |
| | | 163 | | { |
| | 200 | 164 | | await _publisher.ShutdownAsync(_options.ShutdownTimeout).ConfigureAwait(false); |
| | 198 | 165 | | } |
| | 2 | 166 | | catch |
| | | 167 | | { |
| | | 168 | | // Best effort. |
| | 2 | 169 | | } |
| | | 170 | | } |
| | 217 | 171 | | } |
| | | 172 | | finally |
| | | 173 | | { |
| | | 174 | | // Release, never Dispose: SemaphoreSlim.Dispose does not complete pending WaitAsync |
| | | 175 | | // waiters, so disposing here would strand publishers parked on the gate forever (and |
| | | 176 | | // the first woken waiter's finally would throw trying to Release a disposed |
| | | 177 | | // semaphore, never handing the permit on). Released, each parked waiter wakes in |
| | | 178 | | // turn and observes _disposed; the gate holds no unmanaged resources, so leaving it |
| | | 179 | | // undisposed leaks nothing. |
| | 217 | 180 | | _publisherGate.Release(); |
| | | 181 | | } |
| | 414 | 182 | | } |
| | | 183 | | } |