Files
ScadaBridge/tests/ScadaLink.Host.Tests/LoggerConfigurationTests.cs
T
Joseph Doherty 6ae0fea558 fix(error-handling): close Theme 4 — 18 cancellation / fire-and-forget findings
Async cancellation hygiene, fire-and-forget observability, retry/shutdown
semantics, and audit-row coverage across 9 modules. Highlights:

Cancellation & lifecycle:
- AuditLog-006: SqliteAuditWriter.Dispose hops to thread pool, escaping the
  captured SyncContext that risked sync-over-async deadlock.
- AuditLog-010: SiteAuditTelemetryActor owns a private lifecycle CTS,
  threaded through drain paths instead of CancellationToken.None.
- Comm-019: CentralCommunicationActor adds lifecycle CTS for repo calls.
- Host-019: Migration StartupRetry forwards ApplicationStopping so SIGTERM
  during the bounded-retry window aborts cleanly.

Cursor / retry / counter correctness:
- AuditLog-004: SiteAuditReconciliationActor's cursor now holds at `since`
  when any row's idempotent insert is still being retried (per-EventId
  retry counter, MaxPermanentInsertAttempts=5 escape valve with LogCritical
  abandon). No more silent abandonment of permanently-failing rows.
- ConfigDB-019: Dropped the catch-and-continue on EnsureLookaheadAsync's
  SPLIT loop — by class-doc construction the catch could only mask real
  failures and let the next iteration create permanent partition holes.
- HM-017/018: HealthReportSender + CentralHealthReportLoop snapshot
  per-interval counters before sending, restore via new
  ISiteHealthCollector.AddIntervalCounters on transport failure so counts
  aren't silently lost.

Fire-and-forget / shutdown waits:
- InboundAPI-018: AuditWriteMiddleware observes faulted audit-write tasks
  via OnlyOnFaulted continuation (Warning log; response unchanged).
- SnF-024: StoreAndForwardService.StopAsync awaits in-flight retry sweep
  with a bounded SweepShutdownWaitTimeout (10s).

Leak / refactor:
- Comm-021: SiteStreamGrpcServer.SubscribeInstance wraps Subscribe in its
  own try/catch so a throw doesn't leak the relay actor or _activeStreams
  entry.
- Comm-022: VERIFIED already-closed by Comm-016's dead-code purge.
- CLI-017: BundleCommands' three subcommands delegate to ExecuteCommandAsync
  (auth-failure exit-code contract unified).

Defensive / validation:
- CLI-021: CliConfig.Load wraps file-read/JSON parse so malformed config
  prints a warning and returns defaults instead of crashing the CLI.
- Host-022: ParseLevel emits stderr one-shot warning for unrecognised
  MinimumLevel instead of silently coercing to Information.
- ESG-019: ExternalSystemClient sets HttpClient.Timeout=Infinite so the
  per-call CTS is the sole timeout source (was clipped to 100s by .NET).
- Security-020: New SecurityOptionsValidator (IValidateOptions) rejects
  empty LdapServer/LdapSearchBase with ValidateOnStart.
- DM-019: Lifecycle command timeouts now emit DisableTimedOut/EnableTimedOut/
  DeleteTimedOut audit entries (mirrors DeployFailed pattern).

Plus reconciled stale per-module Open-findings counters that had drifted
from prior sessions.

20+ new regression tests across 11 test projects; build clean; affected
suites all green. README regenerated: 75 open (was 93).
2026-05-28 07:13:28 -04:00

112 lines
3.7 KiB
C#

using Microsoft.Extensions.Configuration;
using Serilog.Events;
namespace ScadaLink.Host.Tests;
/// <summary>
/// Host-011: <c>ScadaLink:Logging:MinimumLevel</c> must actually drive the Serilog
/// minimum level. Previously the value was bound into <see cref="LoggingOptions"/>
/// but never read, so editing it had no effect.
/// </summary>
public class LoggerConfigurationTests
{
private static IConfiguration BuildConfig(string? minimumLevel)
{
var values = new Dictionary<string, string?>();
if (minimumLevel != null)
values["ScadaLink:Logging:MinimumLevel"] = minimumLevel;
return new ConfigurationBuilder().AddInMemoryCollection(values).Build();
}
[Fact]
public void MinimumLevel_Warning_SuppressesInformationLogs()
{
var sink = new InMemorySink();
var logger = LoggerConfigurationFactory
.Build(BuildConfig("Warning"), "Central", "central", "node1")
.WriteTo.Sink(sink)
.CreateLogger();
logger.Information("info message");
logger.Warning("warning message");
Assert.Single(sink.LogEvents);
Assert.Equal(LogEventLevel.Warning, sink.LogEvents[0].Level);
}
[Fact]
public void MinimumLevel_Debug_AllowsDebugLogs()
{
var sink = new InMemorySink();
var logger = LoggerConfigurationFactory
.Build(BuildConfig("Debug"), "Site", "site-a", "node1")
.WriteTo.Sink(sink)
.CreateLogger();
logger.Debug("debug message");
Assert.Single(sink.LogEvents);
Assert.Equal(LogEventLevel.Debug, sink.LogEvents[0].Level);
}
[Fact]
public void MinimumLevel_Absent_DefaultsToInformation()
{
var sink = new InMemorySink();
var logger = LoggerConfigurationFactory
.Build(BuildConfig(null), "Central", "central", "node1")
.WriteTo.Sink(sink)
.CreateLogger();
logger.Debug("debug message");
logger.Information("info message");
Assert.Single(sink.LogEvents);
Assert.Equal(LogEventLevel.Information, sink.LogEvents[0].Level);
}
/// <summary>
/// Host-022: an unrecognised <c>ScadaLink:Logging:MinimumLevel</c> (e.g. a typo
/// like "Informaiton") must NOT abort startup but MUST emit a one-shot warning
/// naming the offending value and the fallback so the silent coercion is
/// visible. Null/blank is treated as "unset" and silently defaults.
/// </summary>
[Fact]
public void ParseLevel_UnrecognisedValue_FallsBackAndWarns()
{
var writer = new StringWriter();
var result = LoggerConfigurationFactory.ParseLevel("Informaiton", writer);
Assert.Equal(LogEventLevel.Information, result);
var warning = writer.ToString();
Assert.Contains("warning", warning, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Informaiton", warning);
Assert.Contains("Information", warning);
}
[Fact]
public void ParseLevel_NullOrBlank_FallsBackSilently()
{
var writer = new StringWriter();
var nullResult = LoggerConfigurationFactory.ParseLevel(null, writer);
var blankResult = LoggerConfigurationFactory.ParseLevel(" ", writer);
Assert.Equal(LogEventLevel.Information, nullResult);
Assert.Equal(LogEventLevel.Information, blankResult);
Assert.Empty(writer.ToString());
}
[Fact]
public void ParseLevel_RecognisedValue_NoWarning()
{
var writer = new StringWriter();
var result = LoggerConfigurationFactory.ParseLevel("Warning", writer);
Assert.Equal(LogEventLevel.Warning, result);
Assert.Empty(writer.ToString());
}
}