135 lines
7.9 KiB
C#
135 lines
7.9 KiB
C#
using JobTrackerApi.Data;
|
|
using JobTrackerApi.Models;
|
|
using JobTrackerApi.Services;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
using Moq;
|
|
using Xunit;
|
|
using Xunit.Abstractions;
|
|
|
|
namespace JobTrackerApi.Tests;
|
|
|
|
public sealed class ApplicationChecklistConcurrencyTests(ITestOutputHelper output)
|
|
{
|
|
[Fact]
|
|
public async Task Native_duplicate_seed_race_recovers_both_reads_without_losing_user_decisions()
|
|
{
|
|
await using var database = await Database.Create();
|
|
var race = new SeedRace();
|
|
await using var winner = database.Context(new SeedGate(race, winner: true));
|
|
var loserGate = new SeedGate(race, winner: false);
|
|
await using var loser = database.Context(loserGate);
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
|
var results = await Task.WhenAll(
|
|
new ApplicationChecklistService(winner).GetAsync(Database.Owner, database.JobId, timeout.Token),
|
|
new ApplicationChecklistService(loser).GetAsync(Database.Owner, database.JobId, timeout.Token));
|
|
Assert.All(results, result => Assert.NotNull(result));
|
|
Assert.Equal(results[0]!.Items.Select(x => x.Id).Order(), results[1]!.Items.Select(x => x.Id).Order());
|
|
Assert.All(results, result =>
|
|
{
|
|
Assert.Equal(14, result!.Items.Count(x => x.SystemKey != null));
|
|
Assert.Equal(ChecklistStatuses.Dismissed, result.Items.Single(x => x.SystemKey == "prepare-cv").Status);
|
|
Assert.Equal("Manual decision", result.Items.Single(x => x.SystemKey == null).Title);
|
|
Assert.Equal(ChecklistStatuses.Done, result.Items.Single(x => x.SystemKey == null).Status);
|
|
});
|
|
var duplicate = Assert.IsType<SqliteException>(Assert.IsType<DbUpdateException>(loserGate.Failure).InnerException);
|
|
Assert.Equal(2067, duplicate.SqliteExtendedErrorCode);
|
|
await using var verify = database.Context();
|
|
Assert.Equal(15, await verify.ApplicationChecklistItems.CountAsync());
|
|
Assert.Equal(7, (await verify.JobApplications.SingleAsync()).Version);
|
|
Assert.DoesNotContain(loser.ChangeTracker.Entries<ApplicationChecklistItem>(), entry => entry.State == EntityState.Added);
|
|
output.WriteLine("Native SQLite duplicate2067 observed and recovered; both calls returned the same15 persisted IDs, user decisions and job revision7 preserved.");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Concurrent_seed_recovery_does_not_swallow_an_unrelated_native_foreign_key_failure()
|
|
{
|
|
await using var database = await Database.Create();
|
|
var race = new SeedRace();
|
|
await using var winner = database.Context(new SeedGate(race, winner: true));
|
|
var loserGate = new SeedGate(race, winner: false);
|
|
await using var loser = database.Context(loserGate);
|
|
var invalidCustom = new ApplicationChecklistItem { OwnerUserId = Database.Owner, JobApplicationId = int.MaxValue, Title = "Invalid parent must fail", Status = ChecklistStatuses.Done };
|
|
loser.ApplicationChecklistItems.Add(invalidCustom);
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
|
var winningRead = new ApplicationChecklistService(winner).GetAsync(Database.Owner, database.JobId, timeout.Token);
|
|
var losingRead = new ApplicationChecklistService(loser).GetAsync(Database.Owner, database.JobId, timeout.Token);
|
|
Assert.NotNull(await winningRead);
|
|
var observed = await Record.ExceptionAsync(async () => await losingRead);
|
|
output.WriteLine($"Native save error={((loserGate.Failure as DbUpdateException)?.InnerException as SqliteException)?.SqliteExtendedErrorCode}; service exception={observed?.GetType().Name ?? "none"}.");
|
|
var error = Assert.IsType<DbUpdateException>(observed);
|
|
var native = Assert.IsType<SqliteException>(error.InnerException);
|
|
Assert.Equal(787, native.SqliteExtendedErrorCode);
|
|
Assert.Equal(EntityState.Added, loser.Entry(invalidCustom).State);
|
|
await using var verify = database.Context();
|
|
Assert.Equal(15, await verify.ApplicationChecklistItems.CountAsync());
|
|
Assert.False(await verify.ApplicationChecklistItems.AnyAsync(x => x.Title == invalidCustom.Title));
|
|
output.WriteLine("Native SQLite foreign-key787 propagated despite another request having persisted all missing default keys.");
|
|
}
|
|
|
|
private sealed class SeedRace
|
|
{
|
|
private int _arrivals;
|
|
public TaskCompletionSource BothReady { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource WinnerCommitted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public void Arrive() { if (Interlocked.Increment(ref _arrivals) == 2) BothReady.TrySetResult(); }
|
|
}
|
|
|
|
private sealed class SeedGate(SeedRace race, bool winner) : SaveChangesInterceptor
|
|
{
|
|
private bool _used;
|
|
public Exception? Failure { get; private set; }
|
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
|
{
|
|
if (_used) return result;
|
|
_used = true;
|
|
race.Arrive();
|
|
await race.BothReady.Task.WaitAsync(cancellationToken);
|
|
if (!winner) await race.WinnerCommitted.Task.WaitAsync(cancellationToken);
|
|
return result;
|
|
}
|
|
public override ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result, CancellationToken cancellationToken = default)
|
|
{
|
|
if (winner) race.WinnerCommitted.TrySetResult();
|
|
return ValueTask.FromResult(result);
|
|
}
|
|
public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, CancellationToken cancellationToken = default)
|
|
{
|
|
Failure = eventData.Exception;
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
private sealed class Database(string file) : IAsyncDisposable
|
|
{
|
|
public const string Owner = "owner";
|
|
public int JobId { get; private set; }
|
|
public JobTrackerContext Context(SaveChangesInterceptor? interceptor = null)
|
|
{
|
|
var options = new DbContextOptionsBuilder<JobTrackerContext>().UseSqlite($"Data Source={file};Pooling=False");
|
|
if (interceptor != null) options.AddInterceptors(interceptor);
|
|
var user = new Mock<ICurrentUserService>();
|
|
user.SetupGet(x => x.UserId).Returns(Owner);
|
|
return new JobTrackerContext(options.Options, user.Object);
|
|
}
|
|
public static async Task<Database> Create()
|
|
{
|
|
var database = new Database(Path.Combine(Path.GetTempPath(), $"checklist-race-{Guid.NewGuid():N}.db"));
|
|
await using var db = database.Context();
|
|
await db.Database.EnsureCreatedAsync();
|
|
db.Users.Add(new ApplicationUser { Id = Owner });
|
|
var job = new JobApplication { OwnerUserId = Owner, Company = new Company { OwnerUserId = Owner, Name = "Synthetic" }, Status = "Interview", Version = 7 };
|
|
db.JobApplications.Add(job);
|
|
await db.SaveChangesAsync();
|
|
database.JobId = job.Id;
|
|
db.ApplicationChecklistItems.AddRange(
|
|
new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = job.Id, SystemKey = "prepare-cv", AutoSignal = ChecklistSignalKeys.Cv, IsSystemGenerated = true, Title = "Prepare CV", Category = ChecklistCategories.Preparation, Status = ChecklistStatuses.Dismissed },
|
|
new ApplicationChecklistItem { OwnerUserId = Owner, JobApplicationId = job.Id, Title = "Manual decision", Category = ChecklistCategories.Custom, Status = ChecklistStatuses.Done, SortOrder = 90 });
|
|
await db.SaveChangesAsync();
|
|
return database;
|
|
}
|
|
public ValueTask DisposeAsync() { File.Delete(file); return ValueTask.CompletedTask; }
|
|
}
|
|
}
|