| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using ProjectTemplate.Infrastructure.Data.Entities; |
| | | 6 | | |
| | | 7 | | namespace ProjectTemplate.Infrastructure.Data.Auditing; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Implements durable audit-completion staging, dispatch, and minimized operational queries. |
| | | 11 | | /// </summary> |
| | | 12 | | public sealed class ApplicationAuditCompletionOutbox : |
| | | 13 | | IApplicationAuditCompletionOutbox, |
| | | 14 | | IApplicationAuditCompletionOutboxDispatcher, |
| | | 15 | | IApplicationAuditCompletionOutboxQuery |
| | | 16 | | { |
| | | 17 | | private readonly ApplicationDbContext _dbContext; |
| | | 18 | | private readonly ApplicationAuditCompletionOutboxOptions _options; |
| | | 19 | | private readonly Dictionary<string, IApplicationAuditCompletionPublisher> _publishers; |
| | | 20 | | private readonly TimeProvider _timeProvider; |
| | | 21 | | |
| | 16 | 22 | | public ApplicationAuditCompletionOutbox( |
| | 16 | 23 | | ApplicationDbContext dbContext, |
| | 16 | 24 | | IOptions<ApplicationAuditCompletionOutboxOptions> options, |
| | 16 | 25 | | IEnumerable<IApplicationAuditCompletionPublisher> publishers, |
| | 16 | 26 | | TimeProvider timeProvider) |
| | | 27 | | { |
| | 16 | 28 | | ArgumentNullException.ThrowIfNull(dbContext); |
| | 16 | 29 | | ArgumentNullException.ThrowIfNull(options); |
| | 16 | 30 | | ArgumentNullException.ThrowIfNull(publishers); |
| | 16 | 31 | | ArgumentNullException.ThrowIfNull(timeProvider); |
| | | 32 | | |
| | 16 | 33 | | _dbContext = dbContext; |
| | 16 | 34 | | _options = options.Value; |
| | 16 | 35 | | _timeProvider = timeProvider; |
| | | 36 | | |
| | 16 | 37 | | var publisherMap = new Dictionary<string, IApplicationAuditCompletionPublisher>(StringComparer.OrdinalIgnoreCase |
| | 48 | 38 | | foreach (IApplicationAuditCompletionPublisher publisher in publishers) |
| | | 39 | | { |
| | 8 | 40 | | string destination = NormalizeDestination(publisher.Destination); |
| | 8 | 41 | | if (!publisherMap.TryAdd(destination, publisher)) |
| | | 42 | | { |
| | 0 | 43 | | throw new InvalidOperationException( |
| | 0 | 44 | | $"More than one audit-completion publisher is registered for destination '{destination}'."); |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | |
| | 16 | 48 | | _publishers = publisherMap; |
| | 16 | 49 | | } |
| | | 50 | | |
| | | 51 | | /// <inheritdoc /> |
| | | 52 | | public ApplicationAuditCompletionOutboxEntry? Stage( |
| | | 53 | | ApplicationDbContext dbContext, |
| | | 54 | | ApplicationMutationAuditReceipt receipt, |
| | | 55 | | string? destination = null) |
| | | 56 | | { |
| | 0 | 57 | | ArgumentNullException.ThrowIfNull(dbContext); |
| | 0 | 58 | | ArgumentNullException.ThrowIfNull(receipt); |
| | | 59 | | |
| | 0 | 60 | | if (!_options.Enabled) |
| | | 61 | | { |
| | 0 | 62 | | return null; |
| | | 63 | | } |
| | | 64 | | |
| | 0 | 65 | | string resolvedDestination = ResolveDestination(destination); |
| | 0 | 66 | | OutboxIdentity identity = CreateIdentity(resolvedDestination, receipt.MutationBatchId); |
| | | 67 | | |
| | 0 | 68 | | ApplicationAuditCompletionOutboxEntry? existing = dbContext |
| | 0 | 69 | | .ApplicationAuditCompletionOutboxEntries |
| | 0 | 70 | | .Local |
| | 0 | 71 | | .SingleOrDefault(entry => entry.Id == identity.Id) |
| | 0 | 72 | | ?? dbContext.ApplicationAuditCompletionOutboxEntries.Find(identity.Id); |
| | | 73 | | |
| | 0 | 74 | | return existing is not null |
| | 0 | 75 | | ? ValidateExisting(existing, resolvedDestination, receipt.MutationBatchId, identity.IdempotencyKey) |
| | 0 | 76 | | : AddEntry(dbContext, receipt, resolvedDestination, identity); |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <inheritdoc /> |
| | | 80 | | public async ValueTask<ApplicationAuditCompletionOutboxEntry?> StageAsync( |
| | | 81 | | ApplicationDbContext dbContext, |
| | | 82 | | ApplicationMutationAuditReceipt receipt, |
| | | 83 | | string? destination = null, |
| | | 84 | | CancellationToken cancellationToken = default) |
| | | 85 | | { |
| | 16 | 86 | | ArgumentNullException.ThrowIfNull(dbContext); |
| | 16 | 87 | | ArgumentNullException.ThrowIfNull(receipt); |
| | 16 | 88 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 89 | | |
| | 16 | 90 | | if (!_options.Enabled) |
| | | 91 | | { |
| | 2 | 92 | | return null; |
| | | 93 | | } |
| | | 94 | | |
| | 14 | 95 | | string resolvedDestination = ResolveDestination(destination); |
| | 14 | 96 | | OutboxIdentity identity = CreateIdentity(resolvedDestination, receipt.MutationBatchId); |
| | | 97 | | |
| | 14 | 98 | | ApplicationAuditCompletionOutboxEntry? existing = dbContext |
| | 14 | 99 | | .ApplicationAuditCompletionOutboxEntries |
| | 14 | 100 | | .Local |
| | 16 | 101 | | .SingleOrDefault(entry => entry.Id == identity.Id); |
| | | 102 | | |
| | 14 | 103 | | existing ??= await dbContext.ApplicationAuditCompletionOutboxEntries |
| | 14 | 104 | | .FindAsync([identity.Id], cancellationToken) |
| | 14 | 105 | | .ConfigureAwait(false); |
| | | 106 | | |
| | 14 | 107 | | return existing is not null |
| | 14 | 108 | | ? ValidateExisting(existing, resolvedDestination, receipt.MutationBatchId, identity.IdempotencyKey) |
| | 14 | 109 | | : AddEntry(dbContext, receipt, resolvedDestination, identity); |
| | 16 | 110 | | } |
| | | 111 | | |
| | | 112 | | /// <inheritdoc /> |
| | | 113 | | public async Task<ApplicationAuditCompletionDispatchSummary> DispatchReadyAsync( |
| | | 114 | | CancellationToken cancellationToken = default) |
| | | 115 | | { |
| | 14 | 116 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 12 | 117 | | if (!_options.Enabled) |
| | | 118 | | { |
| | 2 | 119 | | return new(false, 0, 0, 0, 0, 0, 0); |
| | | 120 | | } |
| | | 121 | | |
| | 10 | 122 | | DateTime now = UtcNow(); |
| | 10 | 123 | | List<ApplicationAuditCompletionOutboxEntry> entries = await _dbContext |
| | 10 | 124 | | .ApplicationAuditCompletionOutboxEntries |
| | 10 | 125 | | .Where(entry => |
| | 10 | 126 | | (entry.Status == ApplicationAuditCompletionOutboxStatuses.Pending || |
| | 10 | 127 | | entry.Status == ApplicationAuditCompletionOutboxStatuses.RetryableFailure || |
| | 10 | 128 | | entry.Status == ApplicationAuditCompletionOutboxStatuses.Deferred) && |
| | 10 | 129 | | (!entry.NextAttemptUtc.HasValue || entry.NextAttemptUtc <= now)) |
| | 10 | 130 | | .OrderBy(entry => entry.CreatedUtc) |
| | 10 | 131 | | .Take(_options.BatchSize) |
| | 10 | 132 | | .ToListAsync(cancellationToken) |
| | 10 | 133 | | .ConfigureAwait(false); |
| | | 134 | | |
| | 10 | 135 | | int delivered = 0; |
| | 10 | 136 | | int retryScheduled = 0; |
| | 10 | 137 | | int failed = 0; |
| | 10 | 138 | | int deferred = 0; |
| | 10 | 139 | | int deadLettered = 0; |
| | | 140 | | |
| | 40 | 141 | | foreach (ApplicationAuditCompletionOutboxEntry entry in entries) |
| | | 142 | | { |
| | 10 | 143 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 144 | | ApplicationAuditCompletionPublishResult result; |
| | | 145 | | |
| | 10 | 146 | | if (!_publishers.TryGetValue(entry.Destination, out IApplicationAuditCompletionPublisher? publisher)) |
| | | 147 | | { |
| | 4 | 148 | | result = ApplicationAuditCompletionPublishResult.Defer( |
| | 4 | 149 | | "PublisherUnavailable", |
| | 4 | 150 | | "No audit-completion publisher is registered for the configured destination.", |
| | 4 | 151 | | _options.DeferredRetryDelay); |
| | | 152 | | } |
| | | 153 | | else |
| | | 154 | | { |
| | | 155 | | try |
| | | 156 | | { |
| | 6 | 157 | | result = await publisher |
| | 6 | 158 | | .PublishAsync(ToMessage(entry), cancellationToken) |
| | 6 | 159 | | .ConfigureAwait(false); |
| | 6 | 160 | | } |
| | 0 | 161 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 162 | | { |
| | 0 | 163 | | throw; |
| | | 164 | | } |
| | 0 | 165 | | catch (Exception exception) |
| | | 166 | | { |
| | 0 | 167 | | result = ApplicationAuditCompletionPublishResult.Retry( |
| | 0 | 168 | | exception.GetType().Name, |
| | 0 | 169 | | exception.Message); |
| | 0 | 170 | | } |
| | | 171 | | } |
| | | 172 | | |
| | 10 | 173 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 10 | 174 | | ApplyResult(entry, result, now); |
| | 10 | 175 | | await _dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); |
| | | 176 | | |
| | 10 | 177 | | switch (entry.Status) |
| | | 178 | | { |
| | | 179 | | case ApplicationAuditCompletionOutboxStatuses.Delivered: |
| | 2 | 180 | | delivered++; |
| | 2 | 181 | | break; |
| | | 182 | | case ApplicationAuditCompletionOutboxStatuses.RetryableFailure: |
| | 2 | 183 | | retryScheduled++; |
| | 2 | 184 | | break; |
| | | 185 | | case ApplicationAuditCompletionOutboxStatuses.Failed: |
| | 0 | 186 | | failed++; |
| | 0 | 187 | | break; |
| | | 188 | | case ApplicationAuditCompletionOutboxStatuses.Deferred: |
| | 4 | 189 | | deferred++; |
| | 4 | 190 | | break; |
| | | 191 | | case ApplicationAuditCompletionOutboxStatuses.DeadLettered: |
| | 2 | 192 | | deadLettered++; |
| | | 193 | | break; |
| | | 194 | | default: |
| | | 195 | | break; |
| | | 196 | | } |
| | 10 | 197 | | } |
| | | 198 | | |
| | 10 | 199 | | return new( |
| | 10 | 200 | | true, |
| | 10 | 201 | | entries.Count, |
| | 10 | 202 | | delivered, |
| | 10 | 203 | | retryScheduled, |
| | 10 | 204 | | failed, |
| | 10 | 205 | | deferred, |
| | 10 | 206 | | deadLettered); |
| | 12 | 207 | | } |
| | | 208 | | |
| | | 209 | | /// <inheritdoc /> |
| | | 210 | | public async Task<ApplicationAuditCompletionOutboxHealth> GetHealthAsync( |
| | | 211 | | CancellationToken cancellationToken = default) |
| | | 212 | | { |
| | 4 | 213 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 4 | 214 | | if (!_options.Enabled) |
| | | 215 | | { |
| | 2 | 216 | | return new(false, 0, null, 0, 0); |
| | | 217 | | } |
| | | 218 | | |
| | 2 | 219 | | IQueryable<ApplicationAuditCompletionOutboxEntry> backlog = _dbContext |
| | 2 | 220 | | .ApplicationAuditCompletionOutboxEntries |
| | 2 | 221 | | .AsNoTracking() |
| | 2 | 222 | | .Where(entry => |
| | 2 | 223 | | entry.Status == ApplicationAuditCompletionOutboxStatuses.Pending || |
| | 2 | 224 | | entry.Status == ApplicationAuditCompletionOutboxStatuses.RetryableFailure || |
| | 2 | 225 | | entry.Status == ApplicationAuditCompletionOutboxStatuses.Deferred); |
| | | 226 | | |
| | 2 | 227 | | long backlogCount = await backlog.LongCountAsync(cancellationToken).ConfigureAwait(false); |
| | 2 | 228 | | DateTime? oldestCreatedUtc = await backlog |
| | 2 | 229 | | .MinAsync(entry => (DateTime?)entry.CreatedUtc, cancellationToken) |
| | 2 | 230 | | .ConfigureAwait(false); |
| | 2 | 231 | | long retryCount = await _dbContext.ApplicationAuditCompletionOutboxEntries |
| | 2 | 232 | | .AsNoTracking() |
| | 2 | 233 | | .SumAsync(entry => (long)entry.RetryCount, cancellationToken) |
| | 2 | 234 | | .ConfigureAwait(false); |
| | 2 | 235 | | long deadLetterCount = await _dbContext.ApplicationAuditCompletionOutboxEntries |
| | 2 | 236 | | .AsNoTracking() |
| | 2 | 237 | | .LongCountAsync( |
| | 2 | 238 | | entry => entry.Status == ApplicationAuditCompletionOutboxStatuses.DeadLettered, |
| | 2 | 239 | | cancellationToken) |
| | 2 | 240 | | .ConfigureAwait(false); |
| | | 241 | | |
| | 2 | 242 | | TimeSpan? oldestAge = oldestCreatedUtc.HasValue |
| | 2 | 243 | | ? UtcNow() - oldestCreatedUtc.Value |
| | 2 | 244 | | : null; |
| | | 245 | | |
| | 2 | 246 | | return new(true, backlogCount, oldestAge, retryCount, deadLetterCount); |
| | 4 | 247 | | } |
| | | 248 | | |
| | | 249 | | /// <inheritdoc /> |
| | | 250 | | public async Task<IReadOnlyList<ApplicationAuditCompletionOutboxItem>> QueryAsync( |
| | | 251 | | ApplicationAuditCompletionOutboxQueryRequest request, |
| | | 252 | | CancellationToken cancellationToken = default) |
| | | 253 | | { |
| | 0 | 254 | | ArgumentNullException.ThrowIfNull(request); |
| | 0 | 255 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 256 | | |
| | 0 | 257 | | if (!_options.Enabled) |
| | | 258 | | { |
| | 0 | 259 | | return []; |
| | | 260 | | } |
| | | 261 | | |
| | 0 | 262 | | int maximumResults = Math.Clamp(request.MaximumResults, 1, 500); |
| | 0 | 263 | | IQueryable<ApplicationAuditCompletionOutboxEntry> query = _dbContext |
| | 0 | 264 | | .ApplicationAuditCompletionOutboxEntries |
| | 0 | 265 | | .AsNoTracking(); |
| | | 266 | | |
| | 0 | 267 | | if (!string.IsNullOrWhiteSpace(request.Status)) |
| | | 268 | | { |
| | 0 | 269 | | string status = request.Status.Trim(); |
| | 0 | 270 | | query = query.Where(entry => entry.Status == status); |
| | | 271 | | } |
| | | 272 | | |
| | 0 | 273 | | if (!string.IsNullOrWhiteSpace(request.Destination)) |
| | | 274 | | { |
| | 0 | 275 | | string destination = request.Destination.Trim(); |
| | 0 | 276 | | query = query.Where(entry => entry.Destination == destination); |
| | | 277 | | } |
| | | 278 | | |
| | 0 | 279 | | if (!string.IsNullOrWhiteSpace(request.MutationBatchId)) |
| | | 280 | | { |
| | 0 | 281 | | string mutationBatchId = request.MutationBatchId.Trim(); |
| | 0 | 282 | | query = query.Where(entry => entry.MutationBatchId == mutationBatchId); |
| | | 283 | | } |
| | | 284 | | |
| | 0 | 285 | | List<ApplicationAuditCompletionOutboxEntry> entries = await query |
| | 0 | 286 | | .OrderByDescending(entry => entry.CreatedUtc) |
| | 0 | 287 | | .Take(maximumResults) |
| | 0 | 288 | | .ToListAsync(cancellationToken) |
| | 0 | 289 | | .ConfigureAwait(false); |
| | | 290 | | |
| | 0 | 291 | | return entries.Select(ToItem).ToArray(); |
| | 0 | 292 | | } |
| | | 293 | | |
| | | 294 | | private ApplicationAuditCompletionOutboxEntry AddEntry( |
| | | 295 | | ApplicationDbContext dbContext, |
| | | 296 | | ApplicationMutationAuditReceipt receipt, |
| | | 297 | | string destination, |
| | | 298 | | OutboxIdentity identity) |
| | | 299 | | { |
| | 12 | 300 | | var entry = new ApplicationAuditCompletionOutboxEntry |
| | 12 | 301 | | { |
| | 12 | 302 | | Id = identity.Id, |
| | 12 | 303 | | SchemaVersion = ApplicationAuditCompletionOutboxEntry.CurrentSchemaVersion, |
| | 12 | 304 | | Destination = destination, |
| | 12 | 305 | | IdempotencyKey = identity.IdempotencyKey, |
| | 12 | 306 | | MutationBatchId = receipt.MutationBatchId, |
| | 12 | 307 | | AuditRecordCount = receipt.AuditRecordCount, |
| | 12 | 308 | | PersistenceOutcome = receipt.PersistenceOutcome, |
| | 12 | 309 | | ReceiptCompletedUtc = receipt.CompletedUtc.UtcDateTime, |
| | 12 | 310 | | MutationManifestHash = receipt.MutationManifestHash, |
| | 12 | 311 | | MutationManifestAlgorithm = receipt.MutationManifestAlgorithm, |
| | 12 | 312 | | MutationManifestSchemaVersion = receipt.MutationManifestSchemaVersion, |
| | 12 | 313 | | OperationExecutionId = receipt.OperationExecutionId, |
| | 12 | 314 | | ExecutionAttemptId = receipt.ExecutionAttemptId, |
| | 12 | 315 | | DecisionAuditRecordId = receipt.DecisionAuditRecordId, |
| | 12 | 316 | | CorrelationId = receipt.CorrelationId, |
| | 12 | 317 | | TraceId = receipt.TraceId, |
| | 12 | 318 | | Status = ApplicationAuditCompletionOutboxStatuses.Pending, |
| | 12 | 319 | | CreatedUtc = UtcNow() |
| | 12 | 320 | | }; |
| | | 321 | | |
| | 12 | 322 | | dbContext.ApplicationAuditCompletionOutboxEntries.Add(entry); |
| | 12 | 323 | | return entry; |
| | | 324 | | } |
| | | 325 | | |
| | | 326 | | private void ApplyResult( |
| | | 327 | | ApplicationAuditCompletionOutboxEntry entry, |
| | | 328 | | ApplicationAuditCompletionPublishResult result, |
| | | 329 | | DateTime attemptedUtc) |
| | | 330 | | { |
| | 10 | 331 | | entry.LastAttemptUtc = attemptedUtc; |
| | 10 | 332 | | entry.DeliveredUtc = null; |
| | 10 | 333 | | entry.LastErrorCode = SanitizeError(result.ErrorCode, 128); |
| | 10 | 334 | | entry.LastErrorMessage = SanitizeError(result.ErrorMessage, _options.MaxErrorDetailLength); |
| | 10 | 335 | | entry.ConcurrencyStamp = DataEntity.NewConcurrencyStamp(); |
| | | 336 | | |
| | 10 | 337 | | switch (result.Disposition) |
| | | 338 | | { |
| | | 339 | | case ApplicationAuditCompletionPublishDisposition.Delivered: |
| | 2 | 340 | | entry.Status = ApplicationAuditCompletionOutboxStatuses.Delivered; |
| | 2 | 341 | | entry.DeliveredUtc = attemptedUtc; |
| | 2 | 342 | | entry.NextAttemptUtc = null; |
| | 2 | 343 | | entry.LastErrorCode = null; |
| | 2 | 344 | | entry.LastErrorMessage = null; |
| | 2 | 345 | | break; |
| | | 346 | | case ApplicationAuditCompletionPublishDisposition.RetryableFailure: |
| | 4 | 347 | | entry.RetryCount++; |
| | 4 | 348 | | if (entry.RetryCount >= _options.MaxRetryAttempts) |
| | | 349 | | { |
| | 2 | 350 | | entry.Status = ApplicationAuditCompletionOutboxStatuses.DeadLettered; |
| | 2 | 351 | | entry.NextAttemptUtc = null; |
| | | 352 | | } |
| | | 353 | | else |
| | | 354 | | { |
| | 2 | 355 | | entry.Status = ApplicationAuditCompletionOutboxStatuses.RetryableFailure; |
| | 2 | 356 | | entry.NextAttemptUtc = attemptedUtc + |
| | 2 | 357 | | (result.RetryAfter ?? CalculateRetryDelay(entry.RetryCount)); |
| | | 358 | | } |
| | | 359 | | |
| | 2 | 360 | | break; |
| | | 361 | | case ApplicationAuditCompletionPublishDisposition.Failed: |
| | 0 | 362 | | entry.RetryCount++; |
| | 0 | 363 | | entry.Status = ApplicationAuditCompletionOutboxStatuses.Failed; |
| | 0 | 364 | | entry.NextAttemptUtc = null; |
| | 0 | 365 | | break; |
| | | 366 | | case ApplicationAuditCompletionPublishDisposition.Deferred: |
| | 4 | 367 | | entry.Status = ApplicationAuditCompletionOutboxStatuses.Deferred; |
| | 4 | 368 | | entry.NextAttemptUtc = attemptedUtc + |
| | 4 | 369 | | (result.RetryAfter ?? _options.DeferredRetryDelay); |
| | 4 | 370 | | break; |
| | | 371 | | default: |
| | 0 | 372 | | throw new InvalidOperationException( |
| | 0 | 373 | | $"Unsupported audit-completion publish disposition '{result.Disposition}'."); |
| | | 374 | | } |
| | | 375 | | } |
| | | 376 | | |
| | | 377 | | private TimeSpan CalculateRetryDelay(int retryCount) |
| | | 378 | | { |
| | 2 | 379 | | int exponent = Math.Clamp(retryCount - 1, 0, 20); |
| | 2 | 380 | | double ticks = Math.Min( |
| | 2 | 381 | | _options.MaxRetryDelay.Ticks, |
| | 2 | 382 | | _options.BaseRetryDelay.Ticks * Math.Pow(2, exponent)); |
| | 2 | 383 | | return TimeSpan.FromTicks((long)ticks); |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | private string ResolveDestination(string? destination) |
| | | 387 | | { |
| | 14 | 388 | | return NormalizeDestination( |
| | 14 | 389 | | string.IsNullOrWhiteSpace(destination) |
| | 14 | 390 | | ? _options.DefaultDestination |
| | 14 | 391 | | : destination); |
| | | 392 | | } |
| | | 393 | | |
| | | 394 | | private static string NormalizeDestination(string? destination) |
| | | 395 | | { |
| | 22 | 396 | | string normalized = destination?.Trim() ?? string.Empty; |
| | 22 | 397 | | return string.IsNullOrWhiteSpace(normalized) |
| | 22 | 398 | | ? throw new InvalidOperationException("An audit-completion destination must be configured.") |
| | 22 | 399 | | : normalized.Length > 128 |
| | 22 | 400 | | ? throw new InvalidOperationException("An audit-completion destination cannot exceed 128 characters.") |
| | 22 | 401 | | : normalized; |
| | | 402 | | } |
| | | 403 | | |
| | | 404 | | private static OutboxIdentity CreateIdentity(string destination, string mutationBatchId) |
| | | 405 | | { |
| | 14 | 406 | | if (string.IsNullOrWhiteSpace(mutationBatchId)) |
| | | 407 | | { |
| | 0 | 408 | | throw new InvalidOperationException("An audit-completion receipt must contain a mutation batch identifier.") |
| | | 409 | | } |
| | | 410 | | |
| | 14 | 411 | | byte[] input = Encoding.UTF8.GetBytes($"{destination}\n{mutationBatchId.Trim()}"); |
| | 14 | 412 | | byte[] hash = SHA256.HashData(input); |
| | 14 | 413 | | return new OutboxIdentity( |
| | 14 | 414 | | new Guid(hash.AsSpan(0, 16)), |
| | 14 | 415 | | $"ncat-audit-completion:{Convert.ToHexString(hash)}"); |
| | | 416 | | } |
| | | 417 | | |
| | | 418 | | private static ApplicationAuditCompletionOutboxEntry ValidateExisting( |
| | | 419 | | ApplicationAuditCompletionOutboxEntry existing, |
| | | 420 | | string destination, |
| | | 421 | | string mutationBatchId, |
| | | 422 | | string idempotencyKey) |
| | | 423 | | { |
| | 2 | 424 | | return !existing.Destination.Equals(destination, StringComparison.OrdinalIgnoreCase) || |
| | 2 | 425 | | !existing.MutationBatchId.Equals(mutationBatchId, StringComparison.Ordinal) || |
| | 2 | 426 | | !existing.IdempotencyKey.Equals(idempotencyKey, StringComparison.Ordinal) |
| | 2 | 427 | | ? throw new InvalidOperationException( |
| | 2 | 428 | | "The deterministic audit-completion outbox identity resolved to conflicting persisted data.") |
| | 2 | 429 | | : existing; |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | private static ApplicationAuditCompletionMessage ToMessage( |
| | | 433 | | ApplicationAuditCompletionOutboxEntry entry) |
| | | 434 | | { |
| | 6 | 435 | | return new( |
| | 6 | 436 | | entry.SchemaVersion, |
| | 6 | 437 | | entry.Destination, |
| | 6 | 438 | | entry.IdempotencyKey, |
| | 6 | 439 | | entry.MutationBatchId, |
| | 6 | 440 | | entry.AuditRecordCount, |
| | 6 | 441 | | entry.PersistenceOutcome, |
| | 6 | 442 | | entry.ReceiptCompletedUtc, |
| | 6 | 443 | | entry.MutationManifestHash, |
| | 6 | 444 | | entry.MutationManifestAlgorithm, |
| | 6 | 445 | | entry.MutationManifestSchemaVersion, |
| | 6 | 446 | | entry.OperationExecutionId, |
| | 6 | 447 | | entry.ExecutionAttemptId, |
| | 6 | 448 | | entry.DecisionAuditRecordId, |
| | 6 | 449 | | entry.CorrelationId, |
| | 6 | 450 | | entry.TraceId); |
| | | 451 | | } |
| | | 452 | | |
| | | 453 | | private static ApplicationAuditCompletionOutboxItem ToItem( |
| | | 454 | | ApplicationAuditCompletionOutboxEntry entry) |
| | | 455 | | { |
| | 0 | 456 | | return new( |
| | 0 | 457 | | entry.Id, |
| | 0 | 458 | | entry.SchemaVersion, |
| | 0 | 459 | | entry.Destination, |
| | 0 | 460 | | entry.IdempotencyKey, |
| | 0 | 461 | | entry.MutationBatchId, |
| | 0 | 462 | | entry.AuditRecordCount, |
| | 0 | 463 | | entry.PersistenceOutcome, |
| | 0 | 464 | | entry.ReceiptCompletedUtc, |
| | 0 | 465 | | entry.MutationManifestHash, |
| | 0 | 466 | | entry.MutationManifestAlgorithm, |
| | 0 | 467 | | entry.MutationManifestSchemaVersion, |
| | 0 | 468 | | entry.OperationExecutionId, |
| | 0 | 469 | | entry.ExecutionAttemptId, |
| | 0 | 470 | | entry.DecisionAuditRecordId, |
| | 0 | 471 | | entry.CorrelationId, |
| | 0 | 472 | | entry.TraceId, |
| | 0 | 473 | | entry.Status, |
| | 0 | 474 | | entry.RetryCount, |
| | 0 | 475 | | entry.CreatedUtc, |
| | 0 | 476 | | entry.LastAttemptUtc, |
| | 0 | 477 | | entry.NextAttemptUtc, |
| | 0 | 478 | | entry.DeliveredUtc, |
| | 0 | 479 | | entry.LastErrorCode, |
| | 0 | 480 | | entry.LastErrorMessage); |
| | | 481 | | } |
| | | 482 | | |
| | | 483 | | private static string? SanitizeError(string? value, int maximumLength) |
| | | 484 | | { |
| | 20 | 485 | | if (string.IsNullOrWhiteSpace(value)) |
| | | 486 | | { |
| | 8 | 487 | | return null; |
| | | 488 | | } |
| | | 489 | | |
| | 12 | 490 | | string sanitized = new([.. value |
| | 12 | 491 | | .Trim() |
| | 428 | 492 | | .Select(character => char.IsControl(character) ? ' ' : character)]); |
| | 12 | 493 | | return sanitized.Length <= maximumLength |
| | 12 | 494 | | ? sanitized |
| | 12 | 495 | | : sanitized[..maximumLength]; |
| | | 496 | | } |
| | | 497 | | |
| | | 498 | | private DateTime UtcNow() |
| | | 499 | | { |
| | 24 | 500 | | return _timeProvider.GetUtcNow().UtcDateTime; |
| | | 501 | | } |
| | | 502 | | |
| | 54 | 503 | | private sealed record OutboxIdentity(Guid Id, string IdempotencyKey); |
| | | 504 | | } |