diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 076705f4..a0ab3893 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -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 `\\\Galaxy!` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\\Galaxy!` 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`. | diff --git a/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs b/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs index 26539c60..e3bd487e 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs @@ -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) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs index 2acd8fcc..41212c2b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs @@ -440,6 +440,9 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase= 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\Galaxy! 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); } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs index cfeebb46..75b1e6f1 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs @@ -704,6 +704,57 @@ public sealed class GatewayOptionsValidatorTests f => f.Contains("MxGateway:Events:ReplayRetentionSeconds")); } + /// + /// SEC-011: a retention past one day, or a non-finite one, fails at startup; otherwise + /// TimeSpan.FromSeconds throws when the first event distributor is built. + /// + /// Retention under test. + [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)); + } + + /// SEC-011: the alarm reconcile interval must be between 1 second and one day when alarms are enabled. + /// Interval under test. + /// Whether the interval is expected to validate. + [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); + } + /// Verifies a zero passes validation. [Fact] public void Validate_Succeeds_WhenReplayRetentionSecondsIsZero()