fix(config): bound Alarms:ReconcileIntervalSeconds and Events:ReplayRetentionSeconds (SEC-011, #254)

ReconcileIntervalSeconds must be 1..86400 when alarms are enabled (a huge
value faulted PeriodicTimer inside an unobserved task, silently ending
reconciliation); ReplayRetentionSeconds must be finite and at most a day
(Infinity passed startup and then threw in TimeSpan.FromSeconds on every
StreamEvents). A faulted reconcile loop is now logged and surfaced.
This commit is contained in:
Joseph Doherty
2026-12-03 09:47:36 -05:00
parent b74a231f75
commit 2ee57a70fe
4 changed files with 81 additions and 4 deletions
@@ -440,6 +440,13 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
// The loop task is awaited only in teardown, so a fault here (a timer period the
// runtime rejects, say) would otherwise end reconciliation silently (SEC-011).
_lastError = $"Alarm reconcile loop stopped: {exception.Message}";
_logger.LogError(exception, "Alarm reconcile loop stopped; missed transitions will not be repaired.");
}
}
private async Task ReconcileAsync(string sessionId, CancellationToken cancellationToken)
@@ -440,6 +440,9 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
// upper-bound pattern.
private const int MaximumEventQueueCapacity = int.MaxValue / 2;
// One day. Replay retention is a reconnect window, not an archive.
private const double MaximumReplayRetentionSeconds = 86_400;
private static void ValidateEvents(EventOptions options, ValidationBuilder builder)
{
AddIfNotPositive(options.QueueCapacity, "MxGateway:Events:QueueCapacity must be greater than zero.", builder);
@@ -462,9 +465,12 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
options.ReplayBufferCapacity,
"MxGateway:Events:ReplayBufferCapacity must be greater than or equal to zero.",
builder);
// Upper bound and finiteness: the value becomes TimeSpan.FromSeconds when the first
// event distributor is built, which throws on Infinity/NaN or anything past
// TimeSpan.MaxValue — a runtime failure of every StreamEvents instead of a startup one.
builder.RequireThat(
options.ReplayRetentionSeconds >= 0,
"MxGateway:Events:ReplayRetentionSeconds must be greater than or equal to zero.");
options.ReplayRetentionSeconds >= 0 && options.ReplayRetentionSeconds <= MaximumReplayRetentionSeconds,
$"MxGateway:Events:ReplayRetentionSeconds must be between 0 and {MaximumReplayRetentionSeconds}.");
builder.RequireThat(
options.ReplayBufferMaxBytes >= 0,
"MxGateway:Events:ReplayBufferMaxBytes must be greater than or equal to zero.");
@@ -578,6 +584,8 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
// fault on the STA rather than a slow poll.
private const int MaximumMaxAlarmsPerFetch = 65_536;
private const int MaximumAlarmReconcileIntervalSeconds = 86_400;
private static void ValidateAlarms(AlarmsOptions options, ValidationBuilder builder)
{
// Validated regardless of Enabled: both values are stamped onto every
@@ -626,6 +634,14 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
@"MxGateway:Alarms:SubscriptionExpression must start with '\\' (canonical \\<host>\Galaxy!<area> shape).");
}
// Above a day the reconcile stops being a cadence, and far above it PeriodicTimer
// rejects the period at runtime, which silently ended reconciliation (SEC-011).
if (options.ReconcileIntervalSeconds is < 1 or > MaximumAlarmReconcileIntervalSeconds)
{
builder.Add(
$"MxGateway:Alarms:ReconcileIntervalSeconds must be between 1 and {MaximumAlarmReconcileIntervalSeconds}.");
}
ValidateAlarmFallback(options.Fallback, builder);
}
@@ -704,6 +704,57 @@ public sealed class GatewayOptionsValidatorTests
f => f.Contains("MxGateway:Events:ReplayRetentionSeconds"));
}
/// <summary>
/// SEC-011: a retention past one day, or a non-finite one, fails at startup; otherwise
/// <c>TimeSpan.FromSeconds</c> throws when the first event distributor is built.
/// </summary>
/// <param name="seconds">Retention under test.</param>
[Theory]
[InlineData(86_400.5)]
[InlineData(1e12)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NaN)]
public void Validate_Fails_WhenReplayRetentionSecondsIsOutOfRange(double seconds)
{
GatewayOptions options = CloneWithEvents(
ValidOptions(),
new EventOptions { ReplayRetentionSeconds = seconds });
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
Assert.True(result.Failed);
Assert.Contains(
result.Failures!,
f => f.Contains("MxGateway:Events:ReplayRetentionSeconds", StringComparison.Ordinal));
}
/// <summary>SEC-011: the alarm reconcile interval must be between 1 second and one day when alarms are enabled.</summary>
/// <param name="seconds">Interval under test.</param>
/// <param name="valid">Whether the interval is expected to validate.</param>
[Theory]
[InlineData(0, false)]
[InlineData(-5, false)]
[InlineData(1, true)]
[InlineData(30, true)]
[InlineData(86_400, true)]
[InlineData(86_401, false)]
[InlineData(int.MaxValue, false)]
public void Validate_AlarmReconcileIntervalBounds(int seconds, bool valid)
{
GatewayOptions options = CloneWithAlarms(
ValidOptions(),
new AlarmsOptions
{
Enabled = true,
DefaultArea = "Galaxy",
ReconcileIntervalSeconds = seconds,
});
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
bool reported = result.Failures?.Any(
f => f.Contains("MxGateway:Alarms:ReconcileIntervalSeconds", StringComparison.Ordinal)) ?? false;
Assert.Equal(!valid, reported);
}
/// <summary>Verifies a zero <see cref="EventOptions.ReplayRetentionSeconds"/> passes validation.</summary>
[Fact]
public void Validate_Succeeds_WhenReplayRetentionSecondsIsZero()