| | | 1 | | using AsiBackbone.Core.Emissions; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Microsoft.Extensions.Logging.Abstractions; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | |
| | | 6 | | namespace AsiBackbone.Core.Outbox; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Drains provider-neutral outbox entries through a configured governance emitter. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <remarks> |
| | | 12 | | /// This drain path is provider-neutral. It is suitable for tests, samples, local validation, and host-owned workers tha |
| | | 13 | | /// </remarks> |
| | | 14 | | /// <remarks> |
| | | 15 | | /// Initializes a new instance of the <see cref="GovernanceOutboxDrain" /> class. |
| | | 16 | | /// </remarks> |
| | | 17 | | /// <param name="outboxStore">The provider-neutral outbox store.</param> |
| | | 18 | | /// <param name="emitter">The provider-neutral governance emitter.</param> |
| | | 19 | | /// <param name="logger">The logger used to record local operational diagnostics for drain failures.</param> |
| | | 20 | | /// <param name="outboxOptions">The provider-neutral retry, poison-message, and claim options used by the drain.</param> |
| | | 21 | | /// <param name="timeProvider">The clock used for the drain time and per-page claim-lease time when <see cref="DrainAsyn |
| | 95 | 22 | | public sealed class GovernanceOutboxDrain( |
| | 95 | 23 | | IGovernanceOutboxStore outboxStore, |
| | 95 | 24 | | IGovernanceEmitter emitter, |
| | 95 | 25 | | ILogger<GovernanceOutboxDrain>? logger = null, |
| | 95 | 26 | | IOptions<GovernanceOutboxOptions>? outboxOptions = null, |
| | 95 | 27 | | TimeProvider? timeProvider = null) |
| | | 28 | | { |
| | 2 | 29 | | private static readonly Action<ILogger, string, int, string, DateTimeOffset, string?, string?, Exception?> LogGovern |
| | 2 | 30 | | LogLevel.Warning, |
| | 2 | 31 | | new EventId(19701, nameof(LogGovernanceEmissionException)), |
| | 2 | 32 | | "Governance outbox emission threw an exception for outbox entry {OutboxEntryId} on attempt {AttemptCount}. Emitt |
| | | 33 | | |
| | 2 | 34 | | private static readonly Action<ILogger, string, int, int, string?, Exception?> LogGovernanceClaimAttemptsExceeded = |
| | 2 | 35 | | LogLevel.Warning, |
| | 2 | 36 | | new EventId(19702, nameof(LogGovernanceClaimAttemptsExceeded)), |
| | 2 | 37 | | "Governance outbox entry {OutboxEntryId} was claimed {ClaimAttemptCount} times without reaching a terminal state |
| | | 38 | | |
| | 2 | 39 | | private static readonly Action<ILogger, string, string, Exception?> LogGovernanceClaimReleaseFailure = LoggerMessage |
| | 2 | 40 | | LogLevel.Warning, |
| | 2 | 41 | | new EventId(19703, nameof(LogGovernanceClaimReleaseFailure)), |
| | 2 | 42 | | "Governance outbox claim release failed during cancellation for outbox entry {OutboxEntryId} owned by worker {Cl |
| | | 43 | | |
| | 99 | 44 | | private readonly IGovernanceOutboxStore outboxStore = outboxStore ?? throw new ArgumentNullException(nameof(outboxSt |
| | 98 | 45 | | private readonly IGovernanceEmitter emitter = emitter ?? throw new ArgumentNullException(nameof(emitter)); |
| | 97 | 46 | | private readonly ILogger<GovernanceOutboxDrain> logger = logger ?? NullLogger<GovernanceOutboxDrain>.Instance; |
| | 97 | 47 | | private readonly GovernanceOutboxOptions retryOptions = ResolveOptions(outboxOptions); |
| | 95 | 48 | | private readonly TimeProvider timeProvider = timeProvider ?? TimeProvider.System; |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Drains pending and retry-ready outbox entries through the configured emitter. |
| | | 52 | | /// </summary> |
| | | 53 | | /// <param name="utcNow">The UTC timestamp used for retry-ready checks. When omitted, the configured <see cref="Time |
| | | 54 | | /// <param name="maxCount">The maximum number of entries to drain.</param> |
| | | 55 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 56 | | /// <returns>The updated outbox entries that were attempted by the drain.</returns> |
| | | 57 | | public async ValueTask<IReadOnlyList<GovernanceOutboxEntry>> DrainAsync( |
| | | 58 | | DateTimeOffset? utcNow = null, |
| | | 59 | | int maxCount = 100, |
| | | 60 | | CancellationToken cancellationToken = default) |
| | | 61 | | { |
| | 102 | 62 | | if (maxCount <= 0) |
| | | 63 | | { |
| | 1 | 64 | | throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, "Maximum count must be greater than zero." |
| | | 65 | | } |
| | | 66 | | |
| | 101 | 67 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 68 | | |
| | 101 | 69 | | DateTimeOffset drainUtc = (utcNow ?? timeProvider.GetUtcNow()).ToUniversalTime(); |
| | | 70 | | |
| | 101 | 71 | | if (retryOptions.UseClaimLeases) |
| | | 72 | | { |
| | | 73 | | // A caller-supplied timestamp is honored for every page so deterministic tests stay deterministic; |
| | | 74 | | // otherwise each page is leased from a fresh reading taken when that page is claimed. |
| | 48 | 75 | | Func<DateTimeOffset> claimClock = utcNow.HasValue |
| | 48 | 76 | | ? () => drainUtc |
| | 48 | 77 | | : timeProvider.GetUtcNow; |
| | | 78 | | |
| | 48 | 79 | | return await DrainClaimedAsync(claimClock, maxCount, cancellationToken).ConfigureAwait(false); |
| | | 80 | | } |
| | | 81 | | |
| | 53 | 82 | | IReadOnlyList<GovernanceOutboxEntry> pendingEntries = await outboxStore |
| | 53 | 83 | | .FindPendingAsync(maxCount, cancellationToken) |
| | 53 | 84 | | .ConfigureAwait(false); |
| | | 85 | | |
| | 49 | 86 | | if (pendingEntries.Count >= maxCount) |
| | | 87 | | { |
| | 5 | 88 | | return await DrainEntriesAsync(pendingEntries, drainUtc, cancellationToken).ConfigureAwait(false); |
| | | 89 | | } |
| | | 90 | | |
| | 44 | 91 | | IReadOnlyList<GovernanceOutboxEntry> retryReadyEntries = await outboxStore |
| | 44 | 92 | | .FindRetryReadyAsync(drainUtc, maxCount - pendingEntries.Count, cancellationToken) |
| | 44 | 93 | | .ConfigureAwait(false); |
| | | 94 | | |
| | 44 | 95 | | IReadOnlyList<GovernanceOutboxEntry> entriesToDrain = MergeEntries(pendingEntries, retryReadyEntries, maxCount); |
| | 44 | 96 | | return await DrainEntriesAsync(entriesToDrain, drainUtc, cancellationToken).ConfigureAwait(false); |
| | 88 | 97 | | } |
| | | 98 | | |
| | | 99 | | private async ValueTask<IReadOnlyList<GovernanceOutboxEntry>> DrainClaimedAsync( |
| | | 100 | | Func<DateTimeOffset> claimClock, |
| | | 101 | | int maxCount, |
| | | 102 | | CancellationToken cancellationToken) |
| | | 103 | | { |
| | 48 | 104 | | if (outboxStore is not IGovernanceOutboxClaimStore claimStore) |
| | | 105 | | { |
| | 3 | 106 | | throw new InvalidOperationException("Claim leases are enabled, but the configured outbox store does not impl |
| | | 107 | | } |
| | | 108 | | |
| | 45 | 109 | | string workerId = retryOptions.ClaimWorkerId ?? throw new InvalidOperationException("ClaimWorkerId is required w |
| | | 110 | | |
| | 45 | 111 | | List<GovernanceOutboxEntry> drainedEntries = []; |
| | 45 | 112 | | int remainingCount = maxCount; |
| | | 113 | | |
| | | 114 | | // Entries are claimed a page at a time rather than leasing the whole batch at once, so a slow emitter |
| | | 115 | | // cannot exhaust a single lease across the batch and leave later entries reclaimable while in flight. |
| | 66 | 116 | | while (remainingCount > 0) |
| | | 117 | | { |
| | 56 | 118 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 119 | | |
| | 56 | 120 | | int pageSize = Math.Min(retryOptions.ClaimPageSize, remainingCount); |
| | 56 | 121 | | DateTimeOffset pageUtc = claimClock().ToUniversalTime(); |
| | | 122 | | |
| | 56 | 123 | | IReadOnlyList<GovernanceOutboxClaim> pageClaims = await ClaimPageAsync( |
| | 56 | 124 | | claimStore, |
| | 56 | 125 | | workerId, |
| | 56 | 126 | | pageUtc, |
| | 56 | 127 | | pageSize, |
| | 56 | 128 | | cancellationToken) |
| | 56 | 129 | | .ConfigureAwait(false); |
| | | 130 | | |
| | 56 | 131 | | if (pageClaims.Count == 0) |
| | | 132 | | { |
| | | 133 | | break; |
| | | 134 | | } |
| | | 135 | | |
| | 52 | 136 | | IReadOnlyList<GovernanceOutboxEntry> pageEntries = await DrainClaimsAsync( |
| | 52 | 137 | | claimStore, |
| | 52 | 138 | | pageClaims, |
| | 52 | 139 | | pageUtc, |
| | 52 | 140 | | cancellationToken) |
| | 52 | 141 | | .ConfigureAwait(false); |
| | | 142 | | |
| | 47 | 143 | | drainedEntries.AddRange(pageEntries); |
| | 47 | 144 | | remainingCount -= pageClaims.Count; |
| | | 145 | | |
| | 47 | 146 | | if (pageClaims.Count < pageSize) |
| | | 147 | | { |
| | | 148 | | break; |
| | | 149 | | } |
| | 21 | 150 | | } |
| | | 151 | | |
| | 40 | 152 | | return drainedEntries; |
| | 40 | 153 | | } |
| | | 154 | | |
| | | 155 | | private async ValueTask<IReadOnlyList<GovernanceOutboxClaim>> ClaimPageAsync( |
| | | 156 | | IGovernanceOutboxClaimStore claimStore, |
| | | 157 | | string workerId, |
| | | 158 | | DateTimeOffset pageUtc, |
| | | 159 | | int pageSize, |
| | | 160 | | CancellationToken cancellationToken) |
| | | 161 | | { |
| | 56 | 162 | | var pendingRequest = GovernanceOutboxClaimRequest.Create( |
| | 56 | 163 | | workerId, |
| | 56 | 164 | | pageUtc, |
| | 56 | 165 | | retryOptions.ClaimLeaseDuration, |
| | 56 | 166 | | pageSize); |
| | 56 | 167 | | IReadOnlyList<GovernanceOutboxClaim> pendingClaims = await claimStore |
| | 56 | 168 | | .ClaimPendingAsync(pendingRequest, cancellationToken) |
| | 56 | 169 | | .ConfigureAwait(false); |
| | | 170 | | |
| | 56 | 171 | | if (pendingClaims.Count >= pageSize) |
| | | 172 | | { |
| | 25 | 173 | | return pendingClaims; |
| | | 174 | | } |
| | | 175 | | |
| | 31 | 176 | | var retryRequest = GovernanceOutboxClaimRequest.Create( |
| | 31 | 177 | | workerId, |
| | 31 | 178 | | pageUtc, |
| | 31 | 179 | | retryOptions.ClaimLeaseDuration, |
| | 31 | 180 | | pageSize - pendingClaims.Count); |
| | 31 | 181 | | IReadOnlyList<GovernanceOutboxClaim> retryReadyClaims = await claimStore |
| | 31 | 182 | | .ClaimRetryReadyAsync(retryRequest, cancellationToken) |
| | 31 | 183 | | .ConfigureAwait(false); |
| | | 184 | | |
| | 31 | 185 | | return MergeClaims(pendingClaims, retryReadyClaims, pageSize); |
| | 56 | 186 | | } |
| | | 187 | | |
| | | 188 | | private async ValueTask<IReadOnlyList<GovernanceOutboxEntry>> DrainEntriesAsync( |
| | | 189 | | IReadOnlyList<GovernanceOutboxEntry> entriesToDrain, |
| | | 190 | | DateTimeOffset drainUtc, |
| | | 191 | | CancellationToken cancellationToken) |
| | | 192 | | { |
| | 49 | 193 | | if (entriesToDrain.Count == 0) |
| | | 194 | | { |
| | 12 | 195 | | return Array.Empty<GovernanceOutboxEntry>(); |
| | | 196 | | } |
| | | 197 | | |
| | 37 | 198 | | List<GovernanceOutboxEntry> updatedEntries = new(entriesToDrain.Count); |
| | | 199 | | |
| | 151 | 200 | | foreach (GovernanceOutboxEntry entry in entriesToDrain) |
| | | 201 | | { |
| | 39 | 202 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 39 | 203 | | GovernanceOutboxEntry updatedEntry = await DrainEntryAsync(entry, drainUtc, cancellationToken).ConfigureAwai |
| | 38 | 204 | | updatedEntries.Add(updatedEntry); |
| | | 205 | | } |
| | | 206 | | |
| | 36 | 207 | | return updatedEntries; |
| | 48 | 208 | | } |
| | | 209 | | |
| | | 210 | | private async ValueTask<IReadOnlyList<GovernanceOutboxEntry>> DrainClaimsAsync( |
| | | 211 | | IGovernanceOutboxClaimStore claimStore, |
| | | 212 | | IReadOnlyList<GovernanceOutboxClaim> claimsToDrain, |
| | | 213 | | DateTimeOffset drainUtc, |
| | | 214 | | CancellationToken cancellationToken) |
| | | 215 | | { |
| | 52 | 216 | | if (claimsToDrain.Count == 0) |
| | | 217 | | { |
| | 0 | 218 | | return Array.Empty<GovernanceOutboxEntry>(); |
| | | 219 | | } |
| | | 220 | | |
| | 52 | 221 | | List<GovernanceOutboxEntry> updatedEntries = new(claimsToDrain.Count); |
| | | 222 | | |
| | 396 | 223 | | for (int claimIndex = 0; claimIndex < claimsToDrain.Count; claimIndex++) |
| | | 224 | | { |
| | 151 | 225 | | GovernanceOutboxClaim claim = claimsToDrain[claimIndex]; |
| | 151 | 226 | | bool drainAttempted = false; |
| | | 227 | | |
| | | 228 | | try |
| | | 229 | | { |
| | 151 | 230 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 150 | 231 | | drainAttempted = true; |
| | 150 | 232 | | GovernanceOutboxEntry updatedEntry = await DrainClaimAsync(claimStore, claim, drainUtc, cancellationToke |
| | 146 | 233 | | updatedEntries.Add(updatedEntry); |
| | 146 | 234 | | } |
| | 5 | 235 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 236 | | { |
| | 5 | 237 | | int releaseStartIndex = drainAttempted ? claimIndex + 1 : claimIndex; |
| | 12 | 238 | | for (int releaseIndex = releaseStartIndex; releaseIndex < claimsToDrain.Count; releaseIndex++) |
| | | 239 | | { |
| | 1 | 240 | | await ReleaseClaimLeaseAsync(claimStore, claimsToDrain[releaseIndex]).ConfigureAwait(false); |
| | | 241 | | } |
| | | 242 | | |
| | 5 | 243 | | throw; |
| | | 244 | | } |
| | | 245 | | } |
| | | 246 | | |
| | 47 | 247 | | return updatedEntries; |
| | 47 | 248 | | } |
| | | 249 | | |
| | | 250 | | private static IReadOnlyList<GovernanceOutboxEntry> MergeEntries( |
| | | 251 | | IReadOnlyList<GovernanceOutboxEntry> pendingEntries, |
| | | 252 | | IReadOnlyList<GovernanceOutboxEntry> retryReadyEntries, |
| | | 253 | | int maxCount) |
| | | 254 | | { |
| | 44 | 255 | | if (pendingEntries.Count == 0) |
| | | 256 | | { |
| | 33 | 257 | | return retryReadyEntries; |
| | | 258 | | } |
| | | 259 | | |
| | 11 | 260 | | if (retryReadyEntries.Count == 0) |
| | | 261 | | { |
| | 10 | 262 | | return pendingEntries; |
| | | 263 | | } |
| | | 264 | | |
| | 1 | 265 | | var entriesToDrain = new List<GovernanceOutboxEntry>(Math.Min(maxCount, pendingEntries.Count + retryReadyEntries |
| | 1 | 266 | | var existingEntryIds = new HashSet<string>(pendingEntries.Count + retryReadyEntries.Count, StringComparer.Ordina |
| | | 267 | | |
| | 4 | 268 | | foreach (GovernanceOutboxEntry pendingEntry in pendingEntries) |
| | | 269 | | { |
| | 1 | 270 | | _ = existingEntryIds.Add(pendingEntry.OutboxEntryId); |
| | 1 | 271 | | entriesToDrain.Add(pendingEntry); |
| | | 272 | | } |
| | | 273 | | |
| | 6 | 274 | | foreach (GovernanceOutboxEntry retryReadyEntry in retryReadyEntries) |
| | | 275 | | { |
| | 2 | 276 | | if (entriesToDrain.Count >= maxCount) |
| | | 277 | | { |
| | 0 | 278 | | break; |
| | | 279 | | } |
| | | 280 | | |
| | 2 | 281 | | if (existingEntryIds.Add(retryReadyEntry.OutboxEntryId)) |
| | | 282 | | { |
| | 1 | 283 | | entriesToDrain.Add(retryReadyEntry); |
| | | 284 | | } |
| | | 285 | | } |
| | | 286 | | |
| | 1 | 287 | | return entriesToDrain; |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | private static IReadOnlyList<GovernanceOutboxClaim> MergeClaims( |
| | | 291 | | IReadOnlyList<GovernanceOutboxClaim> pendingClaims, |
| | | 292 | | IReadOnlyList<GovernanceOutboxClaim> retryReadyClaims, |
| | | 293 | | int maxCount) |
| | | 294 | | { |
| | 38 | 295 | | if (pendingClaims.Count == 0) |
| | | 296 | | { |
| | 9 | 297 | | return retryReadyClaims; |
| | | 298 | | } |
| | | 299 | | |
| | 29 | 300 | | if (retryReadyClaims.Count == 0) |
| | | 301 | | { |
| | 24 | 302 | | return pendingClaims; |
| | | 303 | | } |
| | | 304 | | |
| | 5 | 305 | | var claimsToDrain = new List<GovernanceOutboxClaim>(Math.Min(maxCount, pendingClaims.Count + retryReadyClaims.Co |
| | 5 | 306 | | var existingEntryIds = new HashSet<string>(pendingClaims.Count + retryReadyClaims.Count, StringComparer.Ordinal) |
| | | 307 | | |
| | 22 | 308 | | foreach (GovernanceOutboxClaim pendingClaim in pendingClaims) |
| | | 309 | | { |
| | 6 | 310 | | _ = existingEntryIds.Add(pendingClaim.OutboxEntryId); |
| | 6 | 311 | | claimsToDrain.Add(pendingClaim); |
| | | 312 | | } |
| | | 313 | | |
| | 39 | 314 | | foreach (GovernanceOutboxClaim retryReadyClaim in retryReadyClaims) |
| | | 315 | | { |
| | 15 | 316 | | if (claimsToDrain.Count >= maxCount) |
| | | 317 | | { |
| | 1 | 318 | | break; |
| | | 319 | | } |
| | | 320 | | |
| | 14 | 321 | | if (existingEntryIds.Add(retryReadyClaim.OutboxEntryId)) |
| | | 322 | | { |
| | 8 | 323 | | claimsToDrain.Add(retryReadyClaim); |
| | | 324 | | } |
| | | 325 | | } |
| | | 326 | | |
| | 5 | 327 | | return claimsToDrain; |
| | | 328 | | } |
| | | 329 | | |
| | | 330 | | private async ValueTask<GovernanceOutboxEntry> DrainEntryAsync( |
| | | 331 | | GovernanceOutboxEntry entry, |
| | | 332 | | DateTimeOffset drainUtc, |
| | | 333 | | CancellationToken cancellationToken) |
| | | 334 | | { |
| | | 335 | | GovernanceEmissionResult result; |
| | | 336 | | |
| | | 337 | | try |
| | | 338 | | { |
| | 39 | 339 | | result = await emitter.EmitAsync(entry.Envelope, cancellationToken).ConfigureAwait(false); |
| | 36 | 340 | | } |
| | 1 | 341 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 342 | | { |
| | 1 | 343 | | throw; |
| | | 344 | | } |
| | 2 | 345 | | catch (Exception ex) |
| | | 346 | | { |
| | 2 | 347 | | DateTimeOffset nextRetryUtc = GetRetryUtc(drainUtc); |
| | 2 | 348 | | LogEmissionException(entry, nextRetryUtc, ex); |
| | 2 | 349 | | GovernanceEmissionError governanceEmissionError = CreateExceptionError(ex); |
| | | 350 | | |
| | 2 | 351 | | return await ApplyFailureAsync( |
| | 2 | 352 | | entry, |
| | 2 | 353 | | governanceEmissionError, |
| | 2 | 354 | | nextRetryUtc, |
| | 2 | 355 | | cancellationToken) |
| | 2 | 356 | | .ConfigureAwait(false); |
| | | 357 | | } |
| | | 358 | | |
| | 36 | 359 | | return await ApplyEmissionResultAsync(entry, result, drainUtc, cancellationToken).ConfigureAwait(false); |
| | 38 | 360 | | } |
| | | 361 | | |
| | | 362 | | private async ValueTask<GovernanceOutboxEntry> DrainClaimAsync( |
| | | 363 | | IGovernanceOutboxClaimStore claimStore, |
| | | 364 | | GovernanceOutboxClaim claim, |
| | | 365 | | DateTimeOffset drainUtc, |
| | | 366 | | CancellationToken cancellationToken) |
| | | 367 | | { |
| | | 368 | | try |
| | | 369 | | { |
| | | 370 | | // An emitter that hangs or is killed mid-emission leaves the entry claimed but never failed, so its retry |
| | | 371 | | // count does not advance and the retry-based poison-message policy never fires. The claim count does |
| | | 372 | | // advance on every reclaim, so it is the only signal that bounds that loop. Checked before emission so a |
| | | 373 | | // repeatedly reclaimed entry is not handed to the emitter again. |
| | 150 | 374 | | if (ShouldDeadLetterForClaimAttempts(claim.Entry)) |
| | | 375 | | { |
| | 2 | 376 | | var claimExhaustedError = GovernanceEmissionError.Create( |
| | 2 | 377 | | retryOptions.MaxClaimAttemptsReasonCode, |
| | 2 | 378 | | retryOptions.MaxClaimAttemptsReasonMessage); |
| | | 379 | | |
| | 2 | 380 | | LogClaimAttemptsExceeded(claim.Entry); |
| | | 381 | | |
| | 2 | 382 | | return await claimStore.MarkClaimDeadLetteredAsync( |
| | 2 | 383 | | claim, |
| | 2 | 384 | | claimExhaustedError, |
| | 2 | 385 | | retryOptions.MaxClaimAttemptsReasonMessage, |
| | 2 | 386 | | cancellationToken) |
| | 2 | 387 | | .ConfigureAwait(false); |
| | | 388 | | } |
| | | 389 | | |
| | 148 | 390 | | GovernanceEmissionResult result = await emitter.EmitAsync(claim.Entry.Envelope, cancellationToken).Configure |
| | 142 | 391 | | return await ApplyEmissionResultAsync(claimStore, claim, result, drainUtc, cancellationToken).ConfigureAwait |
| | | 392 | | } |
| | 4 | 393 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 394 | | { |
| | 4 | 395 | | await ReleaseClaimLeaseAsync(claimStore, claim).ConfigureAwait(false); |
| | 4 | 396 | | throw; |
| | 0 | 397 | | } |
| | 4 | 398 | | catch (Exception ex) |
| | | 399 | | { |
| | 4 | 400 | | DateTimeOffset nextRetryUtc = GetRetryUtc(drainUtc); |
| | 4 | 401 | | LogEmissionException(claim.Entry, nextRetryUtc, ex); |
| | 4 | 402 | | GovernanceEmissionError governanceEmissionError = CreateExceptionError(ex); |
| | | 403 | | |
| | 4 | 404 | | return await ApplyClaimFailureAsync( |
| | 4 | 405 | | claimStore, |
| | 4 | 406 | | claim, |
| | 4 | 407 | | governanceEmissionError, |
| | 4 | 408 | | nextRetryUtc, |
| | 4 | 409 | | cancellationToken) |
| | 4 | 410 | | .ConfigureAwait(false); |
| | | 411 | | } |
| | 146 | 412 | | } |
| | | 413 | | |
| | | 414 | | private async ValueTask ReleaseClaimLeaseAsync( |
| | | 415 | | IGovernanceOutboxClaimStore claimStore, |
| | | 416 | | GovernanceOutboxClaim claim) |
| | | 417 | | { |
| | | 418 | | try |
| | | 419 | | { |
| | 5 | 420 | | _ = await claimStore.ReleaseClaimAsync( |
| | 5 | 421 | | claim, |
| | 5 | 422 | | reason: "drain canceled; releasing active claim", |
| | 5 | 423 | | cancellationToken: CancellationToken.None) |
| | 5 | 424 | | .ConfigureAwait(false); |
| | 4 | 425 | | } |
| | 1 | 426 | | catch (Exception ex) |
| | | 427 | | { |
| | 1 | 428 | | LogGovernanceClaimReleaseFailure(logger, claim.OutboxEntryId, claim.WorkerId, ex); |
| | | 429 | | |
| | | 430 | | // Best-effort release must not block shutdown or surface a secondary failure while the drain is already |
| | | 431 | | // aborting. The caller is exiting and claim release is idempotent, so a transient storage failure should no |
| | | 432 | | // mask the original cancellation or leave the remaining page of leases stuck until the normal lease expiry. |
| | 1 | 433 | | } |
| | 5 | 434 | | } |
| | | 435 | | |
| | | 436 | | private async ValueTask<GovernanceOutboxEntry> ApplyEmissionResultAsync( |
| | | 437 | | GovernanceOutboxEntry entry, |
| | | 438 | | GovernanceEmissionResult result, |
| | | 439 | | DateTimeOffset drainUtc, |
| | | 440 | | CancellationToken cancellationToken) |
| | | 441 | | { |
| | 36 | 442 | | ArgumentNullException.ThrowIfNull(result); |
| | | 443 | | |
| | 36 | 444 | | if (result.IsSuccess) |
| | | 445 | | { |
| | 10 | 446 | | return await outboxStore.MarkDeliveredAsync(entry.OutboxEntryId, result, cancellationToken).ConfigureAwait(f |
| | | 447 | | } |
| | | 448 | | |
| | 26 | 449 | | if (result.Status is GovernanceEmissionStatus.DeadLettered) |
| | | 450 | | { |
| | 1 | 451 | | GovernanceEmissionError governanceEmissionError = result.Error ?? GovernanceEmissionError.Create( |
| | 1 | 452 | | "emission.deadlettered", |
| | 1 | 453 | | "Governance emission returned a dead-lettered result.", |
| | 1 | 454 | | providerName: result.ProviderName); |
| | | 455 | | |
| | 1 | 456 | | return await outboxStore.MarkDeadLetteredAsync( |
| | 1 | 457 | | entry.OutboxEntryId, |
| | 1 | 458 | | governanceEmissionError, |
| | 1 | 459 | | governanceEmissionError.Message, |
| | 1 | 460 | | cancellationToken) |
| | 1 | 461 | | .ConfigureAwait(false); |
| | | 462 | | } |
| | | 463 | | |
| | 25 | 464 | | if (result.Status is GovernanceEmissionStatus.Deferred or GovernanceEmissionStatus.Pending) |
| | | 465 | | { |
| | 3 | 466 | | GovernanceEmissionError? governanceEmissionError = result.Error ?? (result.Status is GovernanceEmissionStatu |
| | 3 | 467 | | ? GovernanceEmissionError.Create( |
| | 3 | 468 | | "emission.pending", |
| | 3 | 469 | | "Governance emission remained pending after the outbox drain attempt.", |
| | 3 | 470 | | isRetryable: true, |
| | 3 | 471 | | providerName: result.ProviderName) |
| | 3 | 472 | | : null); |
| | | 473 | | |
| | 3 | 474 | | GovernanceOutboxEntry deferredEntry = entry.MarkDeferred( |
| | 3 | 475 | | governanceEmissionError, |
| | 3 | 476 | | result.RetryAfterUtc ?? GetDeferredUtc(drainUtc), |
| | 3 | 477 | | drainUtc); |
| | | 478 | | |
| | 3 | 479 | | return await outboxStore.SaveAsync(deferredEntry, cancellationToken).ConfigureAwait(false); |
| | | 480 | | } |
| | | 481 | | |
| | 22 | 482 | | GovernanceEmissionError failure = result.Error ?? GovernanceEmissionError.Create( |
| | 22 | 483 | | "emission.failed", |
| | 22 | 484 | | "Governance emission returned a failed result without provider-neutral error details.", |
| | 22 | 485 | | isRetryable: result.ShouldRetry, |
| | 22 | 486 | | providerName: result.ProviderName); |
| | | 487 | | |
| | 22 | 488 | | return await ApplyFailureAsync( |
| | 22 | 489 | | entry, |
| | 22 | 490 | | failure, |
| | 22 | 491 | | result.RetryAfterUtc, |
| | 22 | 492 | | cancellationToken) |
| | 22 | 493 | | .ConfigureAwait(false); |
| | 36 | 494 | | } |
| | | 495 | | |
| | | 496 | | private async ValueTask<GovernanceOutboxEntry> ApplyEmissionResultAsync( |
| | | 497 | | IGovernanceOutboxClaimStore claimStore, |
| | | 498 | | GovernanceOutboxClaim claim, |
| | | 499 | | GovernanceEmissionResult result, |
| | | 500 | | DateTimeOffset drainUtc, |
| | | 501 | | CancellationToken cancellationToken) |
| | | 502 | | { |
| | 142 | 503 | | ArgumentNullException.ThrowIfNull(result); |
| | | 504 | | |
| | 142 | 505 | | if (result.IsSuccess) |
| | | 506 | | { |
| | 121 | 507 | | return await claimStore.MarkClaimDeliveredAsync(claim, result, cancellationToken).ConfigureAwait(false); |
| | | 508 | | } |
| | | 509 | | |
| | 21 | 510 | | if (result.Status is GovernanceEmissionStatus.DeadLettered) |
| | | 511 | | { |
| | 3 | 512 | | GovernanceEmissionError governanceEmissionError = result.Error ?? GovernanceEmissionError.Create( |
| | 3 | 513 | | "emission.deadlettered", |
| | 3 | 514 | | "Governance emission returned a dead-lettered result.", |
| | 3 | 515 | | providerName: result.ProviderName); |
| | | 516 | | |
| | 3 | 517 | | return await claimStore.MarkClaimDeadLetteredAsync( |
| | 3 | 518 | | claim, |
| | 3 | 519 | | governanceEmissionError, |
| | 3 | 520 | | governanceEmissionError.Message, |
| | 3 | 521 | | cancellationToken) |
| | 3 | 522 | | .ConfigureAwait(false); |
| | | 523 | | } |
| | | 524 | | |
| | 18 | 525 | | if (result.Status is GovernanceEmissionStatus.Deferred or GovernanceEmissionStatus.Pending) |
| | | 526 | | { |
| | 8 | 527 | | GovernanceEmissionError? governanceEmissionError = result.Error ?? (result.Status is GovernanceEmissionStatu |
| | 8 | 528 | | ? GovernanceEmissionError.Create( |
| | 8 | 529 | | "emission.pending", |
| | 8 | 530 | | "Governance emission remained pending after the outbox drain attempt.", |
| | 8 | 531 | | isRetryable: true, |
| | 8 | 532 | | providerName: result.ProviderName) |
| | 8 | 533 | | : null); |
| | | 534 | | |
| | 8 | 535 | | GovernanceOutboxEntry deferredEntry = claim.Entry.MarkDeferred( |
| | 8 | 536 | | governanceEmissionError, |
| | 8 | 537 | | result.RetryAfterUtc ?? GetDeferredUtc(drainUtc), |
| | 8 | 538 | | drainUtc); |
| | | 539 | | |
| | 8 | 540 | | return await claimStore.SaveClaimAsync(claim, deferredEntry, cancellationToken).ConfigureAwait(false); |
| | | 541 | | } |
| | | 542 | | |
| | 10 | 543 | | GovernanceEmissionError failure = result.Error ?? GovernanceEmissionError.Create( |
| | 10 | 544 | | "emission.failed", |
| | 10 | 545 | | "Governance emission returned a failed result without provider-neutral error details.", |
| | 10 | 546 | | isRetryable: result.ShouldRetry, |
| | 10 | 547 | | providerName: result.ProviderName); |
| | | 548 | | |
| | 10 | 549 | | return await ApplyClaimFailureAsync( |
| | 10 | 550 | | claimStore, |
| | 10 | 551 | | claim, |
| | 10 | 552 | | failure, |
| | 10 | 553 | | result.RetryAfterUtc, |
| | 10 | 554 | | cancellationToken) |
| | 10 | 555 | | .ConfigureAwait(false); |
| | 141 | 556 | | } |
| | | 557 | | |
| | | 558 | | private async ValueTask<GovernanceOutboxEntry> ApplyFailureAsync( |
| | | 559 | | GovernanceOutboxEntry entry, |
| | | 560 | | GovernanceEmissionError failure, |
| | | 561 | | DateTimeOffset? nextRetryUtc, |
| | | 562 | | CancellationToken cancellationToken) |
| | | 563 | | { |
| | 24 | 564 | | if (ShouldDeadLetter(entry)) |
| | | 565 | | { |
| | 2 | 566 | | GovernanceEmissionError deadLetterError = CreateMaxRetryError(failure); |
| | 2 | 567 | | return await outboxStore.MarkDeadLetteredAsync( |
| | 2 | 568 | | entry.OutboxEntryId, |
| | 2 | 569 | | deadLetterError, |
| | 2 | 570 | | retryOptions.DeadLetterReasonMessage, |
| | 2 | 571 | | cancellationToken) |
| | 2 | 572 | | .ConfigureAwait(false); |
| | | 573 | | } |
| | | 574 | | |
| | 22 | 575 | | return await outboxStore.MarkFailedAsync( |
| | 22 | 576 | | entry.OutboxEntryId, |
| | 22 | 577 | | failure, |
| | 22 | 578 | | nextRetryUtc, |
| | 22 | 579 | | cancellationToken) |
| | 22 | 580 | | .ConfigureAwait(false); |
| | 24 | 581 | | } |
| | | 582 | | |
| | | 583 | | private async ValueTask<GovernanceOutboxEntry> ApplyClaimFailureAsync( |
| | | 584 | | IGovernanceOutboxClaimStore claimStore, |
| | | 585 | | GovernanceOutboxClaim claim, |
| | | 586 | | GovernanceEmissionError failure, |
| | | 587 | | DateTimeOffset? nextRetryUtc, |
| | | 588 | | CancellationToken cancellationToken) |
| | | 589 | | { |
| | 14 | 590 | | if (ShouldDeadLetter(claim.Entry)) |
| | | 591 | | { |
| | 1 | 592 | | GovernanceEmissionError deadLetterError = CreateMaxRetryError(failure); |
| | 1 | 593 | | return await claimStore.MarkClaimDeadLetteredAsync( |
| | 1 | 594 | | claim, |
| | 1 | 595 | | deadLetterError, |
| | 1 | 596 | | retryOptions.DeadLetterReasonMessage, |
| | 1 | 597 | | cancellationToken) |
| | 1 | 598 | | .ConfigureAwait(false); |
| | | 599 | | } |
| | | 600 | | |
| | 13 | 601 | | return await claimStore.MarkClaimFailedAsync( |
| | 13 | 602 | | claim, |
| | 13 | 603 | | failure, |
| | 13 | 604 | | nextRetryUtc, |
| | 13 | 605 | | cancellationToken) |
| | 13 | 606 | | .ConfigureAwait(false); |
| | 14 | 607 | | } |
| | | 608 | | |
| | | 609 | | private bool ShouldDeadLetter(GovernanceOutboxEntry entry) |
| | | 610 | | { |
| | 38 | 611 | | return retryOptions.DeadLetterOnMaxRetryAttempts |
| | 38 | 612 | | && entry.RetryCount + 1 >= retryOptions.MaxRetryAttempts; |
| | | 613 | | } |
| | | 614 | | |
| | | 615 | | private bool ShouldDeadLetterForClaimAttempts(GovernanceOutboxEntry entry) |
| | | 616 | | { |
| | | 617 | | // The store has already stamped this claim, so ClaimAttemptCount includes the current attempt. |
| | 150 | 618 | | return retryOptions.DeadLetterOnMaxClaimAttempts |
| | 150 | 619 | | && entry.ClaimAttemptCount > retryOptions.MaxClaimAttempts; |
| | | 620 | | } |
| | | 621 | | |
| | | 622 | | private GovernanceEmissionError CreateMaxRetryError(GovernanceEmissionError failure) |
| | | 623 | | { |
| | 3 | 624 | | return GovernanceEmissionError.Create( |
| | 3 | 625 | | retryOptions.DeadLetterReasonCode, |
| | 3 | 626 | | retryOptions.DeadLetterReasonMessage, |
| | 3 | 627 | | providerName: failure.ProviderName, |
| | 3 | 628 | | providerErrorCode: failure.Code); |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | private void LogEmissionException(GovernanceOutboxEntry entry, DateTimeOffset nextRetryUtc, Exception exception) |
| | | 632 | | { |
| | 6 | 633 | | LogGovernanceEmissionException( |
| | 6 | 634 | | logger, |
| | 6 | 635 | | entry.OutboxEntryId, |
| | 6 | 636 | | entry.RetryCount + 1, |
| | 6 | 637 | | ResolveEmitterProvider(entry), |
| | 6 | 638 | | nextRetryUtc, |
| | 6 | 639 | | entry.Envelope.CorrelationId, |
| | 6 | 640 | | entry.Envelope.DecisionReceiptId, |
| | 6 | 641 | | exception); |
| | 6 | 642 | | } |
| | | 643 | | |
| | | 644 | | private void LogClaimAttemptsExceeded(GovernanceOutboxEntry entry) |
| | | 645 | | { |
| | 2 | 646 | | LogGovernanceClaimAttemptsExceeded( |
| | 2 | 647 | | logger, |
| | 2 | 648 | | entry.OutboxEntryId, |
| | 2 | 649 | | entry.ClaimAttemptCount, |
| | 2 | 650 | | retryOptions.MaxClaimAttempts, |
| | 2 | 651 | | entry.Envelope.CorrelationId, |
| | 2 | 652 | | null); |
| | 2 | 653 | | } |
| | | 654 | | |
| | | 655 | | private static GovernanceEmissionError CreateExceptionError(Exception exception) |
| | | 656 | | { |
| | 6 | 657 | | return GovernanceEmissionError.Create( |
| | 6 | 658 | | "emission.exception", |
| | 6 | 659 | | $"Governance emission threw {exception.GetType().Name} during outbox drain.", |
| | 6 | 660 | | isRetryable: true, |
| | 6 | 661 | | providerErrorCode: exception.GetType().FullName); |
| | | 662 | | } |
| | | 663 | | |
| | | 664 | | private DateTimeOffset GetRetryUtc(DateTimeOffset drainUtc) |
| | | 665 | | { |
| | 6 | 666 | | return drainUtc.Add(retryOptions.RetryDelay); |
| | | 667 | | } |
| | | 668 | | |
| | | 669 | | private DateTimeOffset GetDeferredUtc(DateTimeOffset drainUtc) |
| | | 670 | | { |
| | 6 | 671 | | return drainUtc.Add(retryOptions.DeferredDelay); |
| | | 672 | | } |
| | | 673 | | |
| | | 674 | | private static GovernanceOutboxOptions ResolveOptions(IOptions<GovernanceOutboxOptions>? options) |
| | | 675 | | { |
| | 97 | 676 | | GovernanceOutboxOptions resolved = options?.Value ?? new GovernanceOutboxOptions(); |
| | 97 | 677 | | resolved.Validate(); |
| | | 678 | | |
| | 95 | 679 | | return new GovernanceOutboxOptions |
| | 95 | 680 | | { |
| | 95 | 681 | | RetryDelay = resolved.RetryDelay, |
| | 95 | 682 | | DeferredDelay = resolved.DeferredDelay, |
| | 95 | 683 | | MaxRetryAttempts = resolved.MaxRetryAttempts, |
| | 95 | 684 | | DeadLetterOnMaxRetryAttempts = resolved.DeadLetterOnMaxRetryAttempts, |
| | 95 | 685 | | DeadLetterReasonCode = resolved.DeadLetterReasonCode.Trim(), |
| | 95 | 686 | | DeadLetterReasonMessage = resolved.DeadLetterReasonMessage.Trim(), |
| | 95 | 687 | | UseClaimLeases = resolved.UseClaimLeases, |
| | 95 | 688 | | ClaimWorkerId = string.IsNullOrWhiteSpace(resolved.ClaimWorkerId) ? null : resolved.ClaimWorkerId.Trim(), |
| | 95 | 689 | | ClaimLeaseDuration = resolved.ClaimLeaseDuration, |
| | 95 | 690 | | ClaimPageSize = resolved.ClaimPageSize, |
| | 95 | 691 | | MaxClaimAttempts = resolved.MaxClaimAttempts, |
| | 95 | 692 | | DeadLetterOnMaxClaimAttempts = resolved.DeadLetterOnMaxClaimAttempts, |
| | 95 | 693 | | MaxClaimAttemptsReasonCode = resolved.MaxClaimAttemptsReasonCode.Trim(), |
| | 95 | 694 | | MaxClaimAttemptsReasonMessage = resolved.MaxClaimAttemptsReasonMessage.Trim() |
| | 95 | 695 | | }; |
| | | 696 | | } |
| | | 697 | | |
| | | 698 | | private static string ResolveEmitterProvider(GovernanceOutboxEntry entry) |
| | | 699 | | { |
| | 6 | 700 | | return entry.Envelope.EmitterProvider ?? entry.ProviderName ?? "unspecified"; |
| | | 701 | | } |
| | | 702 | | } |