fix(site-event-logging): resolve SiteEventLogging-005,007,008,010 — background async writer, drop concrete downcast, surface write failures, test coverage
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ScadaLink.Commons.Messages.RemoteQuery;
|
||||
|
||||
namespace ScadaLink.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-010: previously untested behaviours —
|
||||
/// the query service error path and the recorder's disposed-state semantics.
|
||||
/// </summary>
|
||||
public class EventLogCoverageTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath;
|
||||
|
||||
public EventLogCoverageTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_coverage_{Guid.NewGuid()}.db");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
private SiteEventLogger NewLogger() => new(
|
||||
Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
|
||||
NullLogger<SiteEventLogger>.Instance);
|
||||
|
||||
private static EventLogQueryRequest MakeRequest() => new(
|
||||
CorrelationId: "corr-err",
|
||||
SiteId: "site-1",
|
||||
From: null,
|
||||
To: null,
|
||||
EventType: null,
|
||||
Severity: null,
|
||||
InstanceId: null,
|
||||
KeywordFilter: null,
|
||||
ContinuationToken: null,
|
||||
PageSize: 500,
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
[Fact]
|
||||
public void ExecuteQuery_ReturnsFailureResponse_WhenDatabaseUnavailable()
|
||||
{
|
||||
// The catch block in EventLogQueryService.ExecuteQuery was untested.
|
||||
// Disposing the recorder makes WithConnection throw ObjectDisposedException;
|
||||
// the query service must convert that into a Success=false response rather
|
||||
// than letting the exception escape to the actor.
|
||||
var logger = NewLogger();
|
||||
var queryService = new EventLogQueryService(
|
||||
logger,
|
||||
Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath }),
|
||||
NullLogger<EventLogQueryService>.Instance);
|
||||
|
||||
logger.Dispose();
|
||||
|
||||
var response = queryService.ExecuteQuery(MakeRequest());
|
||||
|
||||
Assert.False(response.Success);
|
||||
Assert.NotNull(response.ErrorMessage);
|
||||
Assert.Empty(response.Entries);
|
||||
Assert.Null(response.ContinuationToken);
|
||||
Assert.Equal("corr-err", response.CorrelationId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_AfterDispose_CompletesWithoutThrowing()
|
||||
{
|
||||
// Logging after disposal must not throw or hang — the event is simply
|
||||
// dropped because the background writer has been completed.
|
||||
var logger = NewLogger();
|
||||
logger.Dispose();
|
||||
|
||||
await logger.LogEventAsync("script", "Info", null, "Source", "After dispose")
|
||||
.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dispose_IsIdempotent()
|
||||
{
|
||||
// Re-entrant / repeated Dispose must be a safe no-op.
|
||||
var logger = NewLogger();
|
||||
logger.Dispose();
|
||||
logger.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit.Xunit2;
|
||||
using ScadaLink.Commons.Messages.RemoteQuery;
|
||||
|
||||
namespace ScadaLink.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-010: the actor message contract of
|
||||
/// <see cref="EventLogHandlerActor"/> was previously untested.
|
||||
/// </summary>
|
||||
public class EventLogHandlerActorTests : TestKit
|
||||
{
|
||||
/// <summary>Test double returning a canned response and recording the request.</summary>
|
||||
private sealed class FakeQueryService : IEventLogQueryService
|
||||
{
|
||||
private readonly Func<EventLogQueryRequest, EventLogQueryResponse> _handler;
|
||||
public EventLogQueryRequest? LastRequest { get; private set; }
|
||||
|
||||
public FakeQueryService(Func<EventLogQueryRequest, EventLogQueryResponse> handler)
|
||||
=> _handler = handler;
|
||||
|
||||
public EventLogQueryResponse ExecuteQuery(EventLogQueryRequest request)
|
||||
{
|
||||
LastRequest = request;
|
||||
return _handler(request);
|
||||
}
|
||||
}
|
||||
|
||||
private static EventLogQueryRequest MakeRequest(string correlationId) => new(
|
||||
CorrelationId: correlationId,
|
||||
SiteId: "site-1",
|
||||
From: null,
|
||||
To: null,
|
||||
EventType: null,
|
||||
Severity: null,
|
||||
InstanceId: null,
|
||||
KeywordFilter: null,
|
||||
ContinuationToken: null,
|
||||
PageSize: 500,
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
private static EventLogQueryResponse MakeResponse(EventLogQueryRequest req, bool success = true) => new(
|
||||
CorrelationId: req.CorrelationId,
|
||||
SiteId: req.SiteId,
|
||||
Entries: [],
|
||||
ContinuationToken: null,
|
||||
HasMore: false,
|
||||
Success: success,
|
||||
ErrorMessage: success ? null : "boom",
|
||||
Timestamp: DateTimeOffset.UtcNow);
|
||||
|
||||
[Fact]
|
||||
public void Actor_RepliesToSender_WithQueryResponse()
|
||||
{
|
||||
var fake = new FakeQueryService(req => MakeResponse(req));
|
||||
var actor = Sys.ActorOf(Props.Create(() => new EventLogHandlerActor(fake)));
|
||||
|
||||
var request = MakeRequest("corr-1");
|
||||
actor.Tell(request, TestActor);
|
||||
|
||||
var response = ExpectMsg<EventLogQueryResponse>();
|
||||
Assert.Equal("corr-1", response.CorrelationId);
|
||||
Assert.Equal("site-1", response.SiteId);
|
||||
Assert.True(response.Success);
|
||||
Assert.Same(request, fake.LastRequest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Actor_PropagatesQueryServiceErrorResponse_ToSender()
|
||||
{
|
||||
var fake = new FakeQueryService(req => MakeResponse(req, success: false));
|
||||
var actor = Sys.ActorOf(Props.Create(() => new EventLogHandlerActor(fake)));
|
||||
|
||||
actor.Tell(MakeRequest("corr-2"), TestActor);
|
||||
|
||||
var response = ExpectMsg<EventLogQueryResponse>();
|
||||
Assert.False(response.Success);
|
||||
Assert.Equal("corr-2", response.CorrelationId);
|
||||
Assert.Equal("boom", response.ErrorMessage);
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,11 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Akka.TestKit.Xunit2" />
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
|
||||
71
tests/ScadaLink.SiteEventLogging.Tests/ServiceWiringTests.cs
Normal file
71
tests/ScadaLink.SiteEventLogging.Tests/ServiceWiringTests.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ScadaLink.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-007: the purge and query services must not
|
||||
/// downcast an injected <see cref="ISiteEventLogger"/> to the concrete type. They now
|
||||
/// depend on the concrete <see cref="SiteEventLogger"/> directly, and DI must resolve
|
||||
/// the recorder, query service, and purge service to a single shared instance.
|
||||
/// </summary>
|
||||
public class ServiceWiringTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath;
|
||||
private ServiceProvider? _provider;
|
||||
|
||||
public ServiceWiringTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_wiring_{Guid.NewGuid()}.db");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_provider?.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AddSiteEventLogging_ResolvesAllServices_SharingOneRecorderInstance()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.Configure<SiteEventLogOptions>(o => o.DatabasePath = _dbPath);
|
||||
services.AddSiteEventLogging();
|
||||
|
||||
_provider = services.BuildServiceProvider();
|
||||
|
||||
var recorderViaInterface = _provider.GetRequiredService<ISiteEventLogger>();
|
||||
var recorderConcrete = _provider.GetRequiredService<SiteEventLogger>();
|
||||
var queryService = _provider.GetRequiredService<IEventLogQueryService>();
|
||||
|
||||
// The interface registration must forward to the concrete singleton — purge
|
||||
// and query depend on that same instance, so all three share one connection.
|
||||
Assert.Same(recorderConcrete, recorderViaInterface);
|
||||
Assert.NotNull(queryService);
|
||||
|
||||
// The hosted purge service must also resolve without an InvalidCastException.
|
||||
var hosted = _provider.GetServices<Microsoft.Extensions.Hosting.IHostedService>();
|
||||
Assert.Contains(hosted, h => h is EventLogPurgeService);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PurgeAndQueryServices_AcceptConcreteRecorder_WithoutDowncast()
|
||||
{
|
||||
// The services no longer take ISiteEventLogger and downcast it; they take the
|
||||
// concrete SiteEventLogger. Constructing them directly must compile and work.
|
||||
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
||||
using var loggerFactory = LoggerFactory.Create(_ => { });
|
||||
using var recorder = new SiteEventLogger(
|
||||
options, loggerFactory.CreateLogger<SiteEventLogger>());
|
||||
|
||||
var purge = new EventLogPurgeService(
|
||||
recorder, options, loggerFactory.CreateLogger<EventLogPurgeService>());
|
||||
var query = new EventLogQueryService(
|
||||
recorder, options, loggerFactory.CreateLogger<EventLogQueryService>());
|
||||
|
||||
Assert.NotNull(purge);
|
||||
Assert.NotNull(query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace ScadaLink.SiteEventLogging.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Regression tests for SiteEventLogging-005 (synchronous I/O on caller thread)
|
||||
/// and SiteEventLogging-008 (write failures silently swallowed).
|
||||
/// </summary>
|
||||
public class SiteEventLoggerAsyncTests : IDisposable
|
||||
{
|
||||
private readonly SiteEventLogger _logger;
|
||||
private readonly string _dbPath;
|
||||
|
||||
public SiteEventLoggerAsyncTests()
|
||||
{
|
||||
_dbPath = Path.Combine(Path.GetTempPath(), $"test_async_{Guid.NewGuid()}.db");
|
||||
var options = Options.Create(new SiteEventLogOptions { DatabasePath = _dbPath });
|
||||
_logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_logger.Dispose();
|
||||
if (File.Exists(_dbPath)) File.Delete(_dbPath);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_DoesNotBlockCaller_WhenWriteIsSlow()
|
||||
{
|
||||
// SiteEventLogging-005: LogEventAsync must not perform the SQLite write
|
||||
// inline on the caller's thread. We hold the recorder busy on a long
|
||||
// database operation from one thread, then time how long it takes the
|
||||
// caller of LogEventAsync to get control back. If recording is offloaded
|
||||
// to a background writer, the caller returns essentially immediately even
|
||||
// though the database is busy. If recording is synchronous (the bug), the
|
||||
// caller blocks on the write lock for the full busy period.
|
||||
var busyStarted = new ManualResetEventSlim(false);
|
||||
var releaseBusy = new ManualResetEventSlim(false);
|
||||
|
||||
var busyThread = new Thread(() =>
|
||||
{
|
||||
_logger.WithConnection(_ =>
|
||||
{
|
||||
busyStarted.Set();
|
||||
// Hold the connection lock until the test releases it.
|
||||
releaseBusy.Wait(TimeSpan.FromSeconds(10));
|
||||
});
|
||||
});
|
||||
busyThread.Start();
|
||||
|
||||
Assert.True(busyStarted.Wait(TimeSpan.FromSeconds(5)), "Busy thread did not start.");
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
var recordTask = _logger.LogEventAsync("script", "Info", null, "Caller", "Should not block");
|
||||
sw.Stop();
|
||||
|
||||
// The CALL must return quickly even though the database is busy for ~1s.
|
||||
Assert.True(sw.ElapsedMilliseconds < 500,
|
||||
$"LogEventAsync blocked the caller for {sw.ElapsedMilliseconds} ms — recording is not offloaded.");
|
||||
|
||||
// Release the busy thread; the record must still complete successfully.
|
||||
releaseBusy.Set();
|
||||
busyThread.Join(TimeSpan.FromSeconds(10));
|
||||
|
||||
await recordTask.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_TaskCompletes_AfterEventIsPersisted()
|
||||
{
|
||||
// Awaiting the returned Task must guarantee the row is durably written.
|
||||
await _logger.LogEventAsync("script", "Info", "inst-1", "Source", "Persisted event");
|
||||
|
||||
var count = _logger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM site_events";
|
||||
return (long)cmd.ExecuteScalar()!;
|
||||
});
|
||||
Assert.Equal(1, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LogEventAsync_FaultsTask_AndCountsFailure_OnWriteError()
|
||||
{
|
||||
// SiteEventLogging-008: a write failure must not be silently swallowed.
|
||||
// The returned Task must fault and the failure counter must increment so
|
||||
// Health Monitoring can surface a logging outage.
|
||||
using var failingConnection = new SqliteConnection("Data Source=:memory:");
|
||||
failingConnection.Open();
|
||||
var options = Options.Create(new SiteEventLogOptions
|
||||
{
|
||||
DatabasePath = Path.Combine(Path.GetTempPath(), $"test_fail_{Guid.NewGuid()}.db")
|
||||
});
|
||||
var logger = new SiteEventLogger(options, NullLogger<SiteEventLogger>.Instance);
|
||||
|
||||
// Drop the table so every write fails with "no such table".
|
||||
logger.WithConnection(connection =>
|
||||
{
|
||||
using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "DROP TABLE site_events";
|
||||
cmd.ExecuteNonQuery();
|
||||
});
|
||||
|
||||
await Assert.ThrowsAnyAsync<SqliteException>(() =>
|
||||
logger.LogEventAsync("script", "Error", null, "Source", "Failing write"));
|
||||
|
||||
Assert.True(logger.FailedWriteCount > 0,
|
||||
"FailedWriteCount must increment when an event write fails.");
|
||||
|
||||
logger.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user