| | | 1 | | using AsyncResponse.Internal; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | using Npgsql; |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | |
| | | 7 | | namespace AsyncResponse.Transports.PostgreSQL; |
| | | 8 | | |
| | | 9 | | /// <summary>Publishes <see cref="WorkerJobEnvelope"/> messages to the PostgreSQL worker queue.</summary> |
| | | 10 | | public sealed class PostgreSqlWorkerTransport : IWorkerTransport, IDelayedWorkerTransport |
| | | 11 | | { |
| | | 12 | | private readonly PostgreSqlAsyncResponseTransportOptions _options; |
| | | 13 | | private readonly PostgreSqlTransportStore _store; |
| | | 14 | | |
| | | 15 | | /// <summary>Creates a PostgreSQL worker transport over the host's shared data source.</summary> |
| | | 16 | | public PostgreSqlWorkerTransport( |
| | | 17 | | IOptions<PostgreSqlAsyncResponseTransportOptions> options, |
| | | 18 | | NpgsqlDataSource dataSource) |
| | | 19 | | : this(options, new PostgreSqlTransportStore(dataSource, options)) |
| | | 20 | | { |
| | | 21 | | } |
| | | 22 | | |
| | | 23 | | internal PostgreSqlWorkerTransport( |
| | | 24 | | IOptions<PostgreSqlAsyncResponseTransportOptions> options, |
| | | 25 | | PostgreSqlTransportStore store) |
| | | 26 | | { |
| | | 27 | | _options = options.Value; |
| | | 28 | | PostgreSqlTransportOptionsValidator.ValidateCommon(_options); |
| | | 29 | | _store = store; |
| | | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <inheritdoc /> |
| | | 33 | | public Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | | 34 | | => PublishCoreAsync(job, delay: null, cancellationToken); |
| | | 35 | | |
| | | 36 | | /// <inheritdoc cref="IDelayedWorkerTransport.MaxPublishDelay"/> |
| | | 37 | | /// <remarks>The due time is a database timestamp; no per-hop cap applies.</remarks> |
| | | 38 | | public TimeSpan MaxPublishDelay => AsyncResponseChannelOptions.MaxPersistenceTtl; |
| | | 39 | | |
| | | 40 | | /// <inheritdoc cref="IDelayedWorkerTransport.PublishAsync(WorkerJobEnvelope, TimeSpan, CancellationToken)"/> |
| | | 41 | | public Task PublishAsync(WorkerJobEnvelope job, TimeSpan delay, CancellationToken cancellationToken = default) |
| | | 42 | | { |
| | | 43 | | ArgumentOutOfRangeException.ThrowIfGreaterThan(delay, MaxPublishDelay); |
| | | 44 | | return PublishCoreAsync(job, delay > TimeSpan.Zero ? delay : null, cancellationToken); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | private async Task PublishCoreAsync(WorkerJobEnvelope job, TimeSpan? delay, CancellationToken cancellationToken) |
| | | 48 | | { |
| | | 49 | | ArgumentNullException.ThrowIfNull(job); |
| | | 50 | | |
| | | 51 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | | 52 | | "asyncresponse.worker.publish", |
| | | 53 | | ActivityKind.Producer, |
| | | 54 | | job.CorrelationId); |
| | | 55 | | activity?.SetTag("asyncresponse.transport", "postgresql"); |
| | | 56 | | activity?.SetTag("messaging.system", "postgresql"); |
| | | 57 | | activity?.SetTag("messaging.destination.name", _options.WorkerQueue); |
| | | 58 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | | 59 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 60 | | |
| | | 61 | | try |
| | | 62 | | { |
| | | 63 | | var headers = string.IsNullOrWhiteSpace(job.CorrelationId) |
| | | 64 | | ? null |
| | | 65 | | : new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) |
| | | 66 | | { |
| | | 67 | | [_options.CorrelationIdHeader] = job.CorrelationId! |
| | | 68 | | }; |
| | | 69 | | |
| | | 70 | | var payload = AsyncResponseJson.Serialize(job); |
| | | 71 | | // Stable id outside the retry loop so a retried publish is idempotent rather than enqueuing |
| | | 72 | | // the same worker job twice. |
| | | 73 | | var messageId = Guid.NewGuid(); |
| | | 74 | | if (delay is { } delayTag) |
| | | 75 | | activity?.SetTag("asyncresponse.worker.delay_seconds", delayTag.TotalSeconds); |
| | | 76 | | await PostgreSqlTransportRetry.ExecuteAsync( |
| | | 77 | | async token => |
| | | 78 | | { |
| | | 79 | | await _store.PublishAsync(messageId, _options.WorkerQueue, payload, headers, token, delay).Configure |
| | | 80 | | return true; |
| | | 81 | | }, |
| | | 82 | | _options.PublishMaxAttempts, |
| | | 83 | | _options.PublishRetryBaseDelay, |
| | | 84 | | _options.PublishRetryMaxDelay, |
| | | 85 | | cancellationToken).ConfigureAwait(false); |
| | | 86 | | } |
| | | 87 | | catch (Exception ex) |
| | | 88 | | { |
| | | 89 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | | 90 | | throw; |
| | | 91 | | } |
| | | 92 | | } |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | internal static class PostgreSqlTransportRetry |
| | | 96 | | { |
| | | 97 | | public static Task<T> ExecuteAsync<T>( |
| | | 98 | | Func<CancellationToken, Task<T>> action, |
| | | 99 | | int maxAttempts, |
| | | 100 | | TimeSpan baseDelay, |
| | | 101 | | TimeSpan maxDelay, |
| | | 102 | | CancellationToken cancellationToken) |
| | 414 | 103 | | => AsyncResponseRetry.ExecuteAsync(action, IsTransient, maxAttempts, baseDelay, maxDelay, cancellationToken); |
| | | 104 | | |
| | 24 | 105 | | public static bool IsTransient(Exception exception) => PostgreSqlTransientFaults.IsTransient(exception); |
| | | 106 | | } |