|
| 1 | +using Microsoft.Data.Sqlite; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | +using Microsoft.EntityFrameworkCore.Storage; |
| 4 | +using Vulthil.Messaging.Abstractions.Consumers; |
| 5 | +using Vulthil.Messaging.Inbox.EntityFrameworkCore; |
| 6 | +using Vulthil.xUnit; |
| 7 | + |
| 8 | +namespace Vulthil.Messaging.Inbox.Relational.Tests; |
| 9 | + |
| 10 | +public sealed class RelationalIdempotencyStoreConflictTests : BaseUnitTestCase |
| 11 | +{ |
| 12 | + private readonly string _databasePath = Path.Combine(Path.GetTempPath(), $"vulthil-inbox-conflict-{Guid.NewGuid():N}.db"); |
| 13 | + |
| 14 | + protected override async ValueTask Initialize() |
| 15 | + { |
| 16 | + await using var context = NewContext(); |
| 17 | + await context.Database.EnsureCreatedAsync(CancellationToken); |
| 18 | + } |
| 19 | + |
| 20 | + protected override ValueTask Dispose() |
| 21 | + { |
| 22 | + SqliteConnection.ClearAllPools(); |
| 23 | + File.Delete(_databasePath); |
| 24 | + return ValueTask.CompletedTask; |
| 25 | + } |
| 26 | + |
| 27 | + [Fact] |
| 28 | + public async Task ConcurrentDeliveriesForTheSameKeyLetExactlyOneCommit() |
| 29 | + { |
| 30 | + // Arrange |
| 31 | + await using var contextA = NewContext(); |
| 32 | + await using var contextB = NewContext(); |
| 33 | + |
| 34 | + // Act — SQLite serializes the two own-transaction attempts under the hood (a shared busy timeout |
| 35 | + // resolves the lock contention instead of failing fast), so of two genuinely concurrent deliveries |
| 36 | + // for the same key, exactly one commits its business write and marker; the loser observes the |
| 37 | + // marker as already processed and never runs its consumer body. |
| 38 | + var taskA = CreateStore(contextA).ProcessAsync("race-key", MessageContext, async token => |
| 39 | + { |
| 40 | + contextA.Things.Add(new Thing { Id = 1, Name = "a" }); |
| 41 | + await contextA.SaveChangesAsync(token); |
| 42 | + }, CancellationToken); |
| 43 | + |
| 44 | + var taskB = CreateStore(contextB).ProcessAsync("race-key", MessageContext, async token => |
| 45 | + { |
| 46 | + contextB.Things.Add(new Thing { Id = 2, Name = "b" }); |
| 47 | + await contextB.SaveChangesAsync(token); |
| 48 | + }, CancellationToken); |
| 49 | + |
| 50 | + var results = await Task.WhenAll(taskA, taskB); |
| 51 | + |
| 52 | + // Assert |
| 53 | + results.Count(processed => processed).ShouldBe(1); |
| 54 | + await using var verify = NewContext(); |
| 55 | + (await verify.Things.CountAsync(CancellationToken)).ShouldBe(1); |
| 56 | + (await verify.InboxMessages.CountAsync(CancellationToken)).ShouldBe(1); |
| 57 | + } |
| 58 | + |
| 59 | + [Fact] |
| 60 | + public async Task AmbientTransactionConflictPropagatesInsteadOfCommittingDuplicateWork() |
| 61 | + { |
| 62 | + // Act |
| 63 | + var propagated = await RunAmbientConflictScenarioAsync(); |
| 64 | + |
| 65 | + // Assert — a marker conflict inside an ambient transaction must never let the caller commit this |
| 66 | + // delivery's business write: it either surfaces so the caller rolls back (fixed) or is silently |
| 67 | + // absorbed while the caller commits anyway (the defect this pins). |
| 68 | + propagated.ShouldNotBeNull(); |
| 69 | + await using var verify = NewContext(); |
| 70 | + (await verify.Things.AnyAsync(thing => thing.Name == "losing-consumer-write", CancellationToken)).ShouldBeFalse(); |
| 71 | + (await verify.InboxMessages.AnyAsync(CancellationToken)).ShouldBeFalse(); |
| 72 | + } |
| 73 | + |
| 74 | + private async Task<DbUpdateException?> RunAmbientConflictScenarioAsync() |
| 75 | + { |
| 76 | + await using var outerContext = NewContext(); |
| 77 | + await using var outerTransaction = await outerContext.Database.BeginTransactionAsync(CancellationToken); |
| 78 | + var store = CreateStore(outerContext); |
| 79 | + |
| 80 | + try |
| 81 | + { |
| 82 | + await store.ProcessAsync("race-key", MessageContext, async token => |
| 83 | + { |
| 84 | + outerContext.Things.Add(new Thing { Id = 1, Name = "losing-consumer-write" }); |
| 85 | + await outerContext.SaveChangesAsync(token); |
| 86 | + |
| 87 | + await InsertConflictingMarkerOnTheSameTransactionAsync(outerContext, outerTransaction, token); |
| 88 | + }, CancellationToken); |
| 89 | + |
| 90 | + await outerTransaction.CommitAsync(CancellationToken); |
| 91 | + return null; |
| 92 | + } |
| 93 | + catch (DbUpdateException exception) |
| 94 | + { |
| 95 | + await outerTransaction.RollbackAsync(CancellationToken); |
| 96 | + return exception; |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + private static async Task InsertConflictingMarkerOnTheSameTransactionAsync( |
| 101 | + TestDbContext outerContext, IDbContextTransaction outerTransaction, CancellationToken cancellationToken) |
| 102 | + { |
| 103 | + await using var conflictContext = new TestDbContext( |
| 104 | + new DbContextOptionsBuilder<TestDbContext>().UseSqlite(outerContext.Database.GetDbConnection()).Options); |
| 105 | + await conflictContext.Database.UseTransactionAsync(outerTransaction.GetDbTransaction(), cancellationToken); |
| 106 | + conflictContext.InboxMessages.Add(new InboxMessage { MessageId = "race-key", ProcessedOnUtc = TimeProvider.System.GetUtcNow() }); |
| 107 | + await conflictContext.SaveChangesAsync(cancellationToken); |
| 108 | + } |
| 109 | + |
| 110 | + private static IMessageContext MessageContext => Mock.Of<IMessageContext>(); |
| 111 | + |
| 112 | + private TestDbContext NewContext() => |
| 113 | + new(new DbContextOptionsBuilder<TestDbContext>() |
| 114 | + .UseSqlite(new SqliteConnectionStringBuilder { DataSource = _databasePath, DefaultTimeout = 5 }.ToString()) |
| 115 | + .Options); |
| 116 | + |
| 117 | + private static RelationalIdempotencyStore<TestDbContext> CreateStore(TestDbContext context) => |
| 118 | + new(context, TimeProvider.System); |
| 119 | + |
| 120 | + public sealed class TestDbContext(DbContextOptions<TestDbContext> options) : DbContext(options), ISaveInboxMessages |
| 121 | + { |
| 122 | + public DbSet<InboxMessage> InboxMessages => Set<InboxMessage>(); |
| 123 | + |
| 124 | + public DbSet<Thing> Things => Set<Thing>(); |
| 125 | + |
| 126 | + protected override void OnModelCreating(ModelBuilder modelBuilder) |
| 127 | + { |
| 128 | + ArgumentNullException.ThrowIfNull(modelBuilder); |
| 129 | + modelBuilder.ApplyRelationalInbox(); |
| 130 | + modelBuilder.Entity<InboxMessage>().Property(message => message.ProcessedOnUtc) |
| 131 | + .HasConversion(value => value.UtcDateTime, value => new DateTimeOffset(value, TimeSpan.Zero)); |
| 132 | + modelBuilder.Entity<Thing>().HasKey(thing => thing.Id); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + public sealed class Thing |
| 137 | + { |
| 138 | + public int Id { get; set; } |
| 139 | + |
| 140 | + public required string Name { get; set; } |
| 141 | + } |
| 142 | +} |
0 commit comments