| | | 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 : IWorkerTransport, IAsyncDisposable |
| | | 18 | | { |
| | | 19 | | private readonly GooglePubSubAsyncResponseOptions _options; |
| | | 20 | | private readonly Func<Task<IGooglePubSubPublisherClient>> _publisherFactory; |
| | 3 | 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) |
| | 1 | 28 | | : this(options, () => CreatePublisherAsync(options.Value)) |
| | | 29 | | { |
| | 3 | 30 | | } |
| | | 31 | | |
| | 3 | 32 | | internal GooglePubSubWorkerTransport( |
| | 3 | 33 | | IOptions<GooglePubSubAsyncResponseOptions> options, |
| | 3 | 34 | | Func<Task<IGooglePubSubPublisherClient>> publisherFactory) |
| | | 35 | | { |
| | 3 | 36 | | _options = options.Value; |
| | 3 | 37 | | _ = GooglePubSubOptionsValidator.Required(_options.ProjectId, nameof(_options.ProjectId)); |
| | 3 | 38 | | _ = GooglePubSubOptionsValidator.Required(_options.WorkerTopicId, nameof(_options.WorkerTopicId)); |
| | 3 | 39 | | _publisherFactory = publisherFactory; |
| | 3 | 40 | | } |
| | | 41 | | |
| | | 42 | | private async Task<IGooglePubSubPublisherClient> GetPublisherAsync(CancellationToken cancellationToken) |
| | | 43 | | { |
| | 3 | 44 | | var publisher = Volatile.Read(ref _publisher); |
| | 3 | 45 | | if (publisher is not null) |
| | 3 | 46 | | return publisher; |
| | | 47 | | |
| | 3 | 48 | | await _publisherGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 49 | | try |
| | | 50 | | { |
| | 3 | 51 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 3 | 52 | | if (_publisher is not null) |
| | 3 | 53 | | return _publisher; |
| | | 54 | | |
| | | 55 | | // Assign only after the await succeeds, so a faulted build attempt is not cached and the next |
| | | 56 | | // publish retries instead of awaiting a permanently faulted task. |
| | 3 | 57 | | var created = await _publisherFactory().ConfigureAwait(false); |
| | 3 | 58 | | _publisher = created; |
| | 3 | 59 | | return created; |
| | | 60 | | } |
| | | 61 | | finally |
| | | 62 | | { |
| | 3 | 63 | | _publisherGate.Release(); |
| | | 64 | | } |
| | 3 | 65 | | } |
| | | 66 | | |
| | | 67 | | [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] |
| | | 68 | | private static async Task<IGooglePubSubPublisherClient> CreatePublisherAsync( |
| | | 69 | | GooglePubSubAsyncResponseOptions options) |
| | | 70 | | { |
| | | 71 | | var projectId = GooglePubSubOptionsValidator.Required(options.ProjectId, nameof(options.ProjectId)); |
| | | 72 | | var topicId = GooglePubSubOptionsValidator.Required(options.WorkerTopicId, nameof(options.WorkerTopicId)); |
| | | 73 | | var topicName = TopicName.FromProjectTopic(projectId, topicId); |
| | | 74 | | // EmulatorOrProduction honors PUBSUB_EMULATOR_HOST when present (local dev / tests) and uses |
| | | 75 | | // real Google Cloud otherwise — no behavior change in production. |
| | | 76 | | var publisher = await new PublisherClientBuilder |
| | | 77 | | { |
| | | 78 | | TopicName = topicName, |
| | | 79 | | EmulatorDetection = EmulatorDetection.EmulatorOrProduction |
| | | 80 | | }.BuildAsync().ConfigureAwait(false); |
| | | 81 | | return new GooglePubSubPublisherClientAdapter(publisher); |
| | | 82 | | } |
| | | 83 | | |
| | | 84 | | /// <summary>Publishes the supplied message.</summary> |
| | | 85 | | public async Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | | 86 | | { |
| | 3 | 87 | | ArgumentNullException.ThrowIfNull(job); |
| | | 88 | | |
| | 3 | 89 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 3 | 90 | | "asyncresponse.worker.publish", |
| | 3 | 91 | | ActivityKind.Producer, |
| | 3 | 92 | | job.CorrelationId); |
| | 3 | 93 | | activity?.SetTag("asyncresponse.transport", "google_pubsub"); |
| | 3 | 94 | | activity?.SetTag("messaging.system", "gcp_pubsub"); |
| | 3 | 95 | | activity?.SetTag("messaging.destination.name", _options.WorkerTopicId); |
| | 3 | 96 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | 3 | 97 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 98 | | |
| | | 99 | | try |
| | | 100 | | { |
| | 3 | 101 | | var message = new PubsubMessage |
| | 3 | 102 | | { |
| | 3 | 103 | | Data = ByteString.CopyFromUtf8(AsyncResponseJson.Serialize(job)) |
| | 3 | 104 | | }; |
| | | 105 | | |
| | 3 | 106 | | if (!string.IsNullOrWhiteSpace(job.CorrelationId)) |
| | 3 | 107 | | message.Attributes[_options.CorrelationIdAttribute] = job.CorrelationId; |
| | | 108 | | |
| | 3 | 109 | | var publisher = await GetPublisherAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 110 | | var messageId = await publisher.PublishAsync(message).WaitAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 111 | | activity?.SetTag("messaging.message.id", messageId); |
| | 3 | 112 | | } |
| | 2 | 113 | | catch (Exception ex) |
| | | 114 | | { |
| | 2 | 115 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 3 | 116 | | throw; |
| | | 117 | | } |
| | 3 | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 121 | | public async ValueTask DisposeAsync() |
| | | 122 | | { |
| | 3 | 123 | | if (Interlocked.Exchange(ref _disposeGate, 1) != 0) |
| | 3 | 124 | | return; |
| | | 125 | | |
| | 3 | 126 | | await _publisherGate.WaitAsync().ConfigureAwait(false); |
| | | 127 | | try |
| | | 128 | | { |
| | 3 | 129 | | _disposed = true; |
| | 3 | 130 | | if (_publisher is not null) |
| | 3 | 131 | | await _publisher.ShutdownAsync(_options.ShutdownTimeout).ConfigureAwait(false); |
| | 3 | 132 | | } |
| | | 133 | | finally |
| | | 134 | | { |
| | 3 | 135 | | _publisherGate.Release(); |
| | 3 | 136 | | _publisherGate.Dispose(); |
| | | 137 | | } |
| | 3 | 138 | | } |
| | | 139 | | } |