| | | 1 | | using System.Data; |
| | | 2 | | using Microsoft.EntityFrameworkCore; |
| | | 3 | | using Microsoft.EntityFrameworkCore.Storage; |
| | | 4 | | |
| | | 5 | | namespace ProjectTemplate.Infrastructure.Data.Auditing; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Coordinates an application mutation, NCAT audit persistence, generated-value audit completion, |
| | | 9 | | /// and an optional local completion handoff inside one relational database transaction boundary. |
| | | 10 | | /// </summary> |
| | | 11 | | public sealed class ApplicationAuditedTransaction : IApplicationAuditedTransaction |
| | | 12 | | { |
| | | 13 | | private const string _savepointPrefix = "NCAT_"; |
| | | 14 | | |
| | | 15 | | private readonly ApplicationDbContext _dbContext; |
| | | 16 | | private readonly IApplicationMutationAuditReceiptAccessor _receiptAccessor; |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Initializes a new instance of the <see cref="ApplicationAuditedTransaction" /> class. |
| | | 20 | | /// </summary> |
| | 22 | 21 | | public ApplicationAuditedTransaction( |
| | 22 | 22 | | ApplicationDbContext dbContext, |
| | 22 | 23 | | IApplicationMutationAuditReceiptAccessor receiptAccessor) |
| | | 24 | | { |
| | 22 | 25 | | ArgumentNullException.ThrowIfNull(dbContext); |
| | 22 | 26 | | ArgumentNullException.ThrowIfNull(receiptAccessor); |
| | | 27 | | |
| | 22 | 28 | | _dbContext = dbContext; |
| | 22 | 29 | | _receiptAccessor = receiptAccessor; |
| | 22 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <inheritdoc /> |
| | | 33 | | public ApplicationAuditedTransactionResult Execute( |
| | | 34 | | Action<ApplicationDbContext> mutation, |
| | | 35 | | Action<ApplicationDbContext, ApplicationMutationAuditReceipt>? persistLocalCompletion = null, |
| | | 36 | | IsolationLevel? isolationLevel = null) |
| | | 37 | | { |
| | 2 | 38 | | ArgumentNullException.ThrowIfNull(mutation); |
| | 2 | 39 | | EnsureSupportedTransactionEnvironment(); |
| | 2 | 40 | | EnsureCleanChangeTracker(); |
| | | 41 | | |
| | 2 | 42 | | IDbContextTransaction? existingTransaction = _dbContext.Database.CurrentTransaction; |
| | 2 | 43 | | if (existingTransaction is not null) |
| | | 44 | | { |
| | 0 | 45 | | return ExecuteWithinExistingTransaction( |
| | 0 | 46 | | existingTransaction, |
| | 0 | 47 | | mutation, |
| | 0 | 48 | | persistLocalCompletion, |
| | 0 | 49 | | isolationLevel); |
| | | 50 | | } |
| | | 51 | | |
| | 2 | 52 | | IExecutionStrategy executionStrategy = _dbContext.Database.CreateExecutionStrategy(); |
| | 2 | 53 | | ApplicationAuditedTransactionResult? result = null; |
| | | 54 | | |
| | 2 | 55 | | executionStrategy.Execute(() => |
| | 2 | 56 | | { |
| | 2 | 57 | | using IDbContextTransaction transaction = BeginTransaction(isolationLevel); |
| | 2 | 58 | | try |
| | 2 | 59 | | { |
| | 2 | 60 | | result = ExecuteCore( |
| | 2 | 61 | | mutation, |
| | 2 | 62 | | persistLocalCompletion, |
| | 2 | 63 | | ApplicationAuditedTransactionOwnership.CoordinatorOwned, |
| | 2 | 64 | | usedSavepoint: false); |
| | 2 | 65 | | transaction.Commit(); |
| | 2 | 66 | | } |
| | 0 | 67 | | catch |
| | 2 | 68 | | { |
| | 0 | 69 | | transaction.Rollback(); |
| | 0 | 70 | | ResetAfterRollback(); |
| | 0 | 71 | | throw; |
| | 2 | 72 | | } |
| | 4 | 73 | | }); |
| | | 74 | | |
| | 2 | 75 | | return result |
| | 2 | 76 | | ?? throw new InvalidOperationException("The audited transaction execution strategy completed without a resul |
| | | 77 | | } |
| | | 78 | | |
| | | 79 | | /// <inheritdoc /> |
| | | 80 | | public async Task<ApplicationAuditedTransactionResult> ExecuteAsync( |
| | | 81 | | Func<ApplicationDbContext, CancellationToken, Task> mutation, |
| | | 82 | | Func<ApplicationDbContext, ApplicationMutationAuditReceipt, CancellationToken, Task>? persistLocalCompletion = n |
| | | 83 | | IsolationLevel? isolationLevel = null, |
| | | 84 | | CancellationToken cancellationToken = default) |
| | | 85 | | { |
| | 20 | 86 | | ArgumentNullException.ThrowIfNull(mutation); |
| | 20 | 87 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 18 | 88 | | EnsureSupportedTransactionEnvironment(); |
| | 18 | 89 | | EnsureCleanChangeTracker(); |
| | | 90 | | |
| | 18 | 91 | | IDbContextTransaction? existingTransaction = _dbContext.Database.CurrentTransaction; |
| | 18 | 92 | | if (existingTransaction is not null) |
| | | 93 | | { |
| | 4 | 94 | | return await ExecuteWithinExistingTransactionAsync( |
| | 4 | 95 | | existingTransaction, |
| | 4 | 96 | | mutation, |
| | 4 | 97 | | persistLocalCompletion, |
| | 4 | 98 | | isolationLevel, |
| | 4 | 99 | | cancellationToken) |
| | 4 | 100 | | .ConfigureAwait(false); |
| | | 101 | | } |
| | | 102 | | |
| | 14 | 103 | | IExecutionStrategy executionStrategy = _dbContext.Database.CreateExecutionStrategy(); |
| | 14 | 104 | | ApplicationAuditedTransactionResult? result = null; |
| | | 105 | | |
| | 14 | 106 | | await executionStrategy.ExecuteAsync(async () => |
| | 14 | 107 | | { |
| | 16 | 108 | | await using IDbContextTransaction transaction = await BeginTransactionAsync( |
| | 16 | 109 | | isolationLevel, |
| | 16 | 110 | | cancellationToken) |
| | 16 | 111 | | .ConfigureAwait(false); |
| | 14 | 112 | | |
| | 14 | 113 | | try |
| | 14 | 114 | | { |
| | 16 | 115 | | result = await ExecuteCoreAsync( |
| | 16 | 116 | | mutation, |
| | 16 | 117 | | persistLocalCompletion, |
| | 16 | 118 | | ApplicationAuditedTransactionOwnership.CoordinatorOwned, |
| | 16 | 119 | | usedSavepoint: false, |
| | 16 | 120 | | cancellationToken) |
| | 16 | 121 | | .ConfigureAwait(false); |
| | 6 | 122 | | await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); |
| | 6 | 123 | | } |
| | 10 | 124 | | catch |
| | 14 | 125 | | { |
| | 10 | 126 | | await transaction.RollbackAsync(CancellationToken.None).ConfigureAwait(false); |
| | 10 | 127 | | ResetAfterRollback(); |
| | 10 | 128 | | throw; |
| | 14 | 129 | | } |
| | 14 | 130 | | }).ConfigureAwait(false); |
| | | 131 | | |
| | 6 | 132 | | return result |
| | 6 | 133 | | ?? throw new InvalidOperationException("The audited transaction execution strategy completed without a resul |
| | 14 | 134 | | } |
| | | 135 | | |
| | | 136 | | private ApplicationAuditedTransactionResult ExecuteWithinExistingTransaction( |
| | | 137 | | IDbContextTransaction existingTransaction, |
| | | 138 | | Action<ApplicationDbContext> mutation, |
| | | 139 | | Action<ApplicationDbContext, ApplicationMutationAuditReceipt>? persistLocalCompletion, |
| | | 140 | | IsolationLevel? isolationLevel) |
| | | 141 | | { |
| | 0 | 142 | | EnsureExistingTransactionCanBeJoined(existingTransaction, isolationLevel); |
| | 0 | 143 | | string savepointName = CreateSavepointName(); |
| | 0 | 144 | | existingTransaction.CreateSavepoint(savepointName); |
| | | 145 | | |
| | | 146 | | try |
| | | 147 | | { |
| | 0 | 148 | | ApplicationAuditedTransactionResult result = ExecuteCore( |
| | 0 | 149 | | mutation, |
| | 0 | 150 | | persistLocalCompletion, |
| | 0 | 151 | | ApplicationAuditedTransactionOwnership.ExistingTransaction, |
| | 0 | 152 | | usedSavepoint: true); |
| | 0 | 153 | | existingTransaction.ReleaseSavepoint(savepointName); |
| | 0 | 154 | | return result; |
| | | 155 | | } |
| | 0 | 156 | | catch |
| | | 157 | | { |
| | 0 | 158 | | existingTransaction.RollbackToSavepoint(savepointName); |
| | 0 | 159 | | ResetAfterRollback(); |
| | 0 | 160 | | throw; |
| | | 161 | | } |
| | 0 | 162 | | } |
| | | 163 | | |
| | | 164 | | private async Task<ApplicationAuditedTransactionResult> ExecuteWithinExistingTransactionAsync( |
| | | 165 | | IDbContextTransaction existingTransaction, |
| | | 166 | | Func<ApplicationDbContext, CancellationToken, Task> mutation, |
| | | 167 | | Func<ApplicationDbContext, ApplicationMutationAuditReceipt, CancellationToken, Task>? persistLocalCompletion, |
| | | 168 | | IsolationLevel? isolationLevel, |
| | | 169 | | CancellationToken cancellationToken) |
| | | 170 | | { |
| | 4 | 171 | | EnsureExistingTransactionCanBeJoined(existingTransaction, isolationLevel); |
| | 4 | 172 | | string savepointName = CreateSavepointName(); |
| | 4 | 173 | | await existingTransaction.CreateSavepointAsync(savepointName, cancellationToken).ConfigureAwait(false); |
| | | 174 | | |
| | | 175 | | try |
| | | 176 | | { |
| | 4 | 177 | | ApplicationAuditedTransactionResult result = await ExecuteCoreAsync( |
| | 4 | 178 | | mutation, |
| | 4 | 179 | | persistLocalCompletion, |
| | 4 | 180 | | ApplicationAuditedTransactionOwnership.ExistingTransaction, |
| | 4 | 181 | | usedSavepoint: true, |
| | 4 | 182 | | cancellationToken) |
| | 4 | 183 | | .ConfigureAwait(false); |
| | 2 | 184 | | await existingTransaction.ReleaseSavepointAsync(savepointName, CancellationToken.None).ConfigureAwait(false) |
| | 2 | 185 | | return result; |
| | | 186 | | } |
| | 2 | 187 | | catch |
| | | 188 | | { |
| | 2 | 189 | | await existingTransaction.RollbackToSavepointAsync(savepointName, CancellationToken.None).ConfigureAwait(fal |
| | 2 | 190 | | ResetAfterRollback(); |
| | 2 | 191 | | throw; |
| | | 192 | | } |
| | 2 | 193 | | } |
| | | 194 | | |
| | | 195 | | private ApplicationAuditedTransactionResult ExecuteCore( |
| | | 196 | | Action<ApplicationDbContext> mutation, |
| | | 197 | | Action<ApplicationDbContext, ApplicationMutationAuditReceipt>? persistLocalCompletion, |
| | | 198 | | ApplicationAuditedTransactionOwnership ownership, |
| | | 199 | | bool usedSavepoint) |
| | | 200 | | { |
| | 2 | 201 | | ApplicationMutationAuditReceipt? previousReceipt = _receiptAccessor.LastCompletedReceipt; |
| | 2 | 202 | | mutation(_dbContext); |
| | | 203 | | |
| | 2 | 204 | | int mutationSaveChangesCount = _dbContext.SaveChanges(); |
| | 2 | 205 | | ApplicationMutationAuditReceipt? receipt = ResolveNewReceipt(previousReceipt); |
| | 2 | 206 | | int completionSaveChangesCount = 0; |
| | | 207 | | |
| | 2 | 208 | | if (persistLocalCompletion is not null) |
| | | 209 | | { |
| | 0 | 210 | | if (receipt is null) |
| | | 211 | | { |
| | 0 | 212 | | throw new InvalidOperationException( |
| | 0 | 213 | | "A local audit completion handoff was requested, but the mutation save produced no new audit receipt |
| | | 214 | | } |
| | | 215 | | |
| | 0 | 216 | | persistLocalCompletion(_dbContext, receipt); |
| | 0 | 217 | | completionSaveChangesCount = _dbContext.SaveChanges(); |
| | | 218 | | } |
| | | 219 | | |
| | 2 | 220 | | return new ApplicationAuditedTransactionResult( |
| | 2 | 221 | | mutationSaveChangesCount, |
| | 2 | 222 | | completionSaveChangesCount, |
| | 2 | 223 | | receipt, |
| | 2 | 224 | | ownership, |
| | 2 | 225 | | usedSavepoint); |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | private async Task<ApplicationAuditedTransactionResult> ExecuteCoreAsync( |
| | | 229 | | Func<ApplicationDbContext, CancellationToken, Task> mutation, |
| | | 230 | | Func<ApplicationDbContext, ApplicationMutationAuditReceipt, CancellationToken, Task>? persistLocalCompletion, |
| | | 231 | | ApplicationAuditedTransactionOwnership ownership, |
| | | 232 | | bool usedSavepoint, |
| | | 233 | | CancellationToken cancellationToken) |
| | | 234 | | { |
| | 20 | 235 | | ApplicationMutationAuditReceipt? previousReceipt = _receiptAccessor.LastCompletedReceipt; |
| | 20 | 236 | | await mutation(_dbContext, cancellationToken).ConfigureAwait(false); |
| | | 237 | | |
| | 16 | 238 | | int mutationSaveChangesCount = await _dbContext |
| | 16 | 239 | | .SaveChangesAsync(cancellationToken) |
| | 16 | 240 | | .ConfigureAwait(false); |
| | 14 | 241 | | ApplicationMutationAuditReceipt? receipt = ResolveNewReceipt(previousReceipt); |
| | 14 | 242 | | int completionSaveChangesCount = 0; |
| | | 243 | | |
| | 14 | 244 | | if (persistLocalCompletion is not null) |
| | | 245 | | { |
| | 8 | 246 | | if (receipt is null) |
| | | 247 | | { |
| | 0 | 248 | | throw new InvalidOperationException( |
| | 0 | 249 | | "A local audit completion handoff was requested, but the mutation save produced no new audit receipt |
| | | 250 | | } |
| | | 251 | | |
| | 8 | 252 | | await persistLocalCompletion(_dbContext, receipt, cancellationToken).ConfigureAwait(false); |
| | 2 | 253 | | completionSaveChangesCount = await _dbContext |
| | 2 | 254 | | .SaveChangesAsync(cancellationToken) |
| | 2 | 255 | | .ConfigureAwait(false); |
| | | 256 | | } |
| | | 257 | | |
| | 8 | 258 | | return new ApplicationAuditedTransactionResult( |
| | 8 | 259 | | mutationSaveChangesCount, |
| | 8 | 260 | | completionSaveChangesCount, |
| | 8 | 261 | | receipt, |
| | 8 | 262 | | ownership, |
| | 8 | 263 | | usedSavepoint); |
| | 8 | 264 | | } |
| | | 265 | | |
| | | 266 | | private ApplicationMutationAuditReceipt? ResolveNewReceipt( |
| | | 267 | | ApplicationMutationAuditReceipt? previousReceipt) |
| | | 268 | | { |
| | 16 | 269 | | ApplicationMutationAuditReceipt? currentReceipt = _receiptAccessor.LastCompletedReceipt; |
| | 16 | 270 | | return ReferenceEquals(previousReceipt, currentReceipt) ? null : currentReceipt; |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | private IDbContextTransaction BeginTransaction(IsolationLevel? isolationLevel) |
| | | 274 | | { |
| | 2 | 275 | | return isolationLevel.HasValue |
| | 2 | 276 | | ? _dbContext.Database.BeginTransaction(isolationLevel.Value) |
| | 2 | 277 | | : _dbContext.Database.BeginTransaction(); |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | private Task<IDbContextTransaction> BeginTransactionAsync( |
| | | 281 | | IsolationLevel? isolationLevel, |
| | | 282 | | CancellationToken cancellationToken) |
| | | 283 | | { |
| | 16 | 284 | | return isolationLevel.HasValue |
| | 16 | 285 | | ? _dbContext.Database.BeginTransactionAsync(isolationLevel.Value, cancellationToken) |
| | 16 | 286 | | : _dbContext.Database.BeginTransactionAsync(cancellationToken); |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | private void EnsureSupportedTransactionEnvironment() |
| | | 290 | | { |
| | 20 | 291 | | if (!_dbContext.Database.IsRelational()) |
| | | 292 | | { |
| | 0 | 293 | | throw new NotSupportedException( |
| | 0 | 294 | | "Application audited transactions require an EF Core relational database provider."); |
| | | 295 | | } |
| | | 296 | | |
| | 20 | 297 | | if (System.Transactions.Transaction.Current is not null) |
| | | 298 | | { |
| | 0 | 299 | | throw new NotSupportedException( |
| | 0 | 300 | | "Ambient System.Transactions transactions are not supported. Use an explicit EF Core transaction so owne |
| | | 301 | | } |
| | 20 | 302 | | } |
| | | 303 | | |
| | | 304 | | private void EnsureCleanChangeTracker() |
| | | 305 | | { |
| | 20 | 306 | | if (_dbContext.HasUnsavedChanges()) |
| | | 307 | | { |
| | 0 | 308 | | throw new InvalidOperationException( |
| | 0 | 309 | | "The application database context already contains unsaved changes. Stage the audited mutation inside th |
| | | 310 | | } |
| | 20 | 311 | | } |
| | | 312 | | |
| | | 313 | | private void ResetAfterRollback() |
| | | 314 | | { |
| | 12 | 315 | | _dbContext.ChangeTracker.Clear(); |
| | 12 | 316 | | } |
| | | 317 | | |
| | | 318 | | private static void EnsureExistingTransactionCanBeJoined( |
| | | 319 | | IDbContextTransaction existingTransaction, |
| | | 320 | | IsolationLevel? isolationLevel) |
| | | 321 | | { |
| | 4 | 322 | | if (isolationLevel.HasValue) |
| | | 323 | | { |
| | 0 | 324 | | throw new InvalidOperationException( |
| | 0 | 325 | | "An isolation level cannot be supplied when the audited transaction coordinator joins an existing EF Cor |
| | | 326 | | } |
| | | 327 | | |
| | 4 | 328 | | if (!existingTransaction.SupportsSavepoints) |
| | | 329 | | { |
| | 0 | 330 | | throw new NotSupportedException( |
| | 0 | 331 | | "The existing EF Core transaction does not support savepoints, so the audited transaction coordinator ca |
| | | 332 | | } |
| | 4 | 333 | | } |
| | | 334 | | |
| | | 335 | | private static string CreateSavepointName() |
| | | 336 | | { |
| | 4 | 337 | | string suffix = Guid.NewGuid().ToString("N"); |
| | 4 | 338 | | return $"{_savepointPrefix}{suffix[..27]}"; |
| | | 339 | | } |
| | | 340 | | } |