Availability: deterministische volgorde bij het lezen van de beschikbaarheidsstatus (geen First zonder OrderBy)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using SlpModularCms.Core.Availability;
|
||||
using SlpModularCms.Core.Data;
|
||||
using SlpModularCms.Core.Identity.Entities;
|
||||
using SlpModularCms.Modules.Availability.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace SlpModularCms.Modules.Availability.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The availability state is read on every API request. EF logs a warning for First/FirstOrDefault without
|
||||
/// OrderBy (it ended up in Sentry); the reads must have an explicit order and still pick one row every time.
|
||||
/// </summary>
|
||||
public class AvailabilityQueryOrderTests
|
||||
{
|
||||
private sealed class Capture : ILoggerProvider, ILogger
|
||||
{
|
||||
public List<EventId> Events { get; } = [];
|
||||
public ILogger CreateLogger(string categoryName) => this;
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) => Events.Add(eventId);
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static (PersistentAvailabilityService Service, ApplicationDbContext Context, Capture Log) Create()
|
||||
{
|
||||
var capture = new Capture();
|
||||
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.UseLoggerFactory(LoggerFactory.Create(b => b.AddProvider(capture).SetMinimumLevel(LogLevel.Trace)))
|
||||
.Options;
|
||||
var context = new ApplicationDbContext(options);
|
||||
var availability = Substitute.For<IOptions<AvailabilityOptions>>();
|
||||
availability.Value.Returns(new AvailabilityOptions { CircuitBreakerSeconds = 30 });
|
||||
var master = Substitute.For<IMasterAvailabilityService>();
|
||||
master.GetMasterStatus().Returns(new MasterGateStatus(true, null));
|
||||
return (new PersistentAvailabilityService(context, availability, master), context, capture);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadingAndUpdatingTheState_NeverTriggersTheFirstWithoutOrderByWarning()
|
||||
{
|
||||
var (service, _, log) = Create();
|
||||
|
||||
await service.IsAvailableAsync();
|
||||
await service.GetStatusDetailsAsync();
|
||||
await service.UpdateStatusAsync(AvailabilityStatus.Maintenance, "m", "t");
|
||||
await service.IsAvailableAsync();
|
||||
await service.GetStatusDetailsAsync();
|
||||
|
||||
log.Events.Should().NotContain(e => e.Id == CoreEventId.FirstWithoutOrderByAndFilterWarning.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithMoreThanOneRow_TheMostRecentlyUpdatedWins_EveryTime()
|
||||
{
|
||||
var (service, context, _) = Create();
|
||||
context.AvailabilityStates.AddRange(
|
||||
new GlobalAvailabilityState { Id = Guid.NewGuid(), Status = AvailabilityStatus.Available, LastUpdatedAt = DateTimeOffset.UtcNow.AddDays(-2) },
|
||||
new GlobalAvailabilityState { Id = Guid.NewGuid(), Status = AvailabilityStatus.Maintenance, Message = "newest", LastUpdatedAt = DateTimeOffset.UtcNow },
|
||||
new GlobalAvailabilityState { Id = Guid.NewGuid(), Status = AvailabilityStatus.Available, LastUpdatedAt = DateTimeOffset.UtcNow.AddDays(-1) });
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
(await service.GetStatusDetailsAsync()).Message.Should().Be("newest");
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,11 @@ public class PersistentAvailabilityService : IAvailabilityService
|
||||
_masterAvailabilityService = masterAvailabilityService;
|
||||
}
|
||||
|
||||
/// <summary>The state row in a deterministic order (newest update, then id). There is normally exactly one row;
|
||||
/// the explicit order keeps EF from warning about First without OrderBy and picks the same row every time.</summary>
|
||||
private IQueryable<GlobalAvailabilityState> CurrentState() =>
|
||||
_context.AvailabilityStates.OrderByDescending(s => s.LastUpdatedAt).ThenBy(s => s.Id);
|
||||
|
||||
public async Task<AvailabilityStatus> IsAvailableAsync()
|
||||
{
|
||||
// Check Circuit Breaker
|
||||
@@ -39,7 +44,7 @@ public class PersistentAvailabilityService : IAvailabilityService
|
||||
|
||||
try
|
||||
{
|
||||
var state = await _context.AvailabilityStates.FirstOrDefaultAsync();
|
||||
var state = await CurrentState().FirstOrDefaultAsync();
|
||||
|
||||
// Als er nog geen state is, maken we een default aan (Available)
|
||||
if (state == null)
|
||||
@@ -69,7 +74,7 @@ public class PersistentAvailabilityService : IAvailabilityService
|
||||
|
||||
try
|
||||
{
|
||||
var state = await _context.AvailabilityStates.FirstOrDefaultAsync();
|
||||
var state = await CurrentState().FirstOrDefaultAsync();
|
||||
if (state == null)
|
||||
return new AvailabilityStatusDetails(AvailabilityStatus.Available, null);
|
||||
|
||||
@@ -94,7 +99,7 @@ public class PersistentAvailabilityService : IAvailabilityService
|
||||
throw new MasterControlledAvailabilityException(masterStatus.DisableMessage);
|
||||
}
|
||||
|
||||
var state = await _context.AvailabilityStates.FirstOrDefaultAsync();
|
||||
var state = await CurrentState().FirstOrDefaultAsync();
|
||||
|
||||
if (state == null)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user