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