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
+5 -2
View File
@@ -221,7 +221,10 @@ healthy subscribers. With `DisconnectSubscriber`, overflow terminates only the
affected stream while the MXAccess session remains active.
`ReplayBufferCapacity`, `ReplayRetentionSeconds` and `ReplayBufferMaxBytes` must
each be greater than or equal to zero (any dimension can be disabled with `0`). A returning subscriber
each be greater than or equal to zero (any dimension can be disabled with `0`).
`ReplayRetentionSeconds` is also capped at 86,400 (one day) and must be finite, so
an out-of-range value fails at startup instead of failing every `StreamEvents`
when the replay ring is first built. A returning subscriber
that asks for events older than the oldest still-retained event is told it missed
events (a "gap") and must re-snapshot; whatever is still retained is replayed.
@@ -524,7 +527,7 @@ behavior.
| `MxGateway:Alarms:Enabled` | `false` | Gates the gateway's always-on central alarm monitor. When `true`, the gateway opens one gateway-owned worker session dedicated to alarms, caches the active-alarm set, and fans it out to every client through the `StreamAlarms` RPC — no client opens its own session to see alarms. |
| `MxGateway:Alarms:SubscriptionExpression` | _(empty)_ | AVEVA alarm-subscription expression the monitor subscribes on startup, in canonical `\\<machine>\Galaxy!<area>` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\<MachineName>\Galaxy!<DefaultArea>` if `DefaultArea` is set. |
| `MxGateway:Alarms:DefaultArea` | _(empty)_ | Area name used to compose a default subscription when `SubscriptionExpression` is empty. If both are empty while `Enabled` is `true`, the monitor faults with a configuration diagnostic. |
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor re-resolves and, on material change, hot-swaps the subtag fallback watch-list, then reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot. The acknowledged watch-list fingerprint advances only after an OK worker reply. Floored at 5 seconds. |
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor re-resolves and, on material change, hot-swaps the subtag fallback watch-list, then reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot. The acknowledged watch-list fingerprint advances only after an OK worker reply. Must be between 1 and 86,400 when `Enabled` is true; the monitor floors it at 5 seconds. |
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR (streamed into one record per alarm, not a DOM), so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
| `MxGateway:Alarms:AckClientName` | `MxGateway` | MXAccess client name the alarm worker's ack writer registers with; the Historian records it as each acknowledgement's OperatorNode. 1-64 printable characters. Conveyed via `MXGATEWAY_ALARM_ACK_CLIENT_NAME`. |
@@ -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()