diff --git a/docs/DesignDecisions.md b/docs/DesignDecisions.md index 340bb5c6..fce12706 100644 --- a/docs/DesignDecisions.md +++ b/docs/DesignDecisions.md @@ -417,7 +417,7 @@ it is about to do; a deployment that needs crash-durable admin audit should ship rather than rely on this table. `MxGateway:Security:AuditRetentionDays` (default 90, minimum 1) bounds the table: the drain sweeps -at startup and hourly, deleting older rows. Retention cannot be configured off. The sweep compares +hourly, deleting older rows in 5,000-row chunks (the first sweep runs from the background loop right after host startup, not inside it; an expression index on `datetime(occurred_at_utc)`, created by the first sweep, keeps the delete from scanning the table). Retention cannot be configured off. The sweep compares through SQLite's `datetime()` rather than on the stored ISO-8601 text. Text comparison is correct only while every row is UTC-normalized — which the canonical model guarantees for rows written through the store, but not for rows that entered the table any other way — and on a mixed-format diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 431119c2..900d62fa 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -471,7 +471,7 @@ model requires otherwise. | `MxGateway:Security:ApiKeyFailureWindowSeconds` | `60` | Sliding-window length, in seconds, over which API-key verification failures are counted, for both the per-partition and the per-key-id aggregate layer. Must be greater than zero. | | `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(remote IP, key id)` partition. A successful verification does not clear it (it decays by window); addresses that verified the key inside the window, and cached verifications, are exempt so the holder is never locked out. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. | | `MxGateway:Security:ApiKeyFailureProbeIntervalSeconds` | `5` | Minimum interval, in seconds, between probe admissions for an over-limit partition or key-id aggregate. An over-limit state is a valve rather than a wall: one request per interval reaches the real verifier — exactly one, even when a burst arrives together at the interval boundary — so the holder of the correct secret always gets through and clears the state, while everything else is still refused before the store read. `0` blocks absolutely instead — **not recommended**, because an unauthenticated peer can then deny the key to its holder for the whole window. Must be zero or greater. | -| `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps once at startup and hourly thereafter, deleting rows older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. | +| `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps hourly (the first sweep runs from the background loop right after startup, without delaying host startup), deleting rows in bounded chunks older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. | | `MxGateway:Security:ApiKeyFailureTrackedPeers` | `4096` | Maximum distinct partitions tracked by the failure counter (a bounded LRU) so a spray of unique tokens cannot grow memory without limit. It cannot be used to flush an active block either: only a validly shaped `mxgw__` token mints a key-id partition (everything else lands on the sender's transport-peer partition), each address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition, and eviction prefers fully expired windows, never removing an over-limit partition until the map exceeds twice this cap. Must be greater than zero. | ## Metrics Options diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index a9d360fc..b7d609c4 100644 --- a/docs/GatewayDashboardDesign.md +++ b/docs/GatewayDashboardDesign.md @@ -274,7 +274,7 @@ bearer). Each hub class is `[Authorize(Policy = HubClientsPolicy)]`. | Hub | Path | Producer | Payload | Routing | |---|---|---|---|---| | `DashboardSnapshotHub` | `/hubs/snapshot` | `DashboardSnapshotPublisher` (BackgroundService consuming `IDashboardSnapshotService.WatchSnapshotsAsync`) | `SnapshotUpdated`: `DashboardSnapshot` **without** `configuration`; `ConfigurationUpdated`: `EffectiveGatewayConfiguration` | Ticks go to all connected clients on every snapshot interval, but only while at least one client is connected (see "Idle gating" below). The effective configuration is startup-static and the largest part of the record, so it is `[JsonIgnore]`d on `DashboardSnapshot` and sent once per connection instead: `OnConnectedAsync` pushes `ConfigurationUpdated` and then the current `SnapshotUpdated`, and the hub method `GetConfiguration()` returns it on demand. Each tick broadcast is bounded to 1 s; a send that misses the bound is abandoned, so one slow client cannot delay the next tick for everyone. | -| `AlarmsHub` | `/hubs/alarms` | `AlarmsHubPublisher` (BackgroundService consuming `IGatewayAlarmService.StreamAsync(filter: null)`) | `AlarmFeedMessage` (`active_alarm` / `snapshot_complete` / `transition` / `provider_status` / `snapshot_status`) | Guarded by `MxGateway.Dashboard.Alarms`, not `HubClients`: a real authenticated dashboard role is required, so the `Authentication:Mode=Disabled` and anonymous-localhost bypasses are excluded (SEC-40). Connected clients auto-join `__alarms__`; all admitted clients receive every message — the feed is galaxy-wide and carries no session provenance, so no per-caller scoping applies (see "Alarm-feed visibility"). Publisher auto-reconnects every 5s on stream faults. Every subscription to the monitor — the first and each resubscribe — is preceded by an `AlarmFeedReset` frame (`{ generation }`, monotonic per process): the monitor primes each new subscription with a full `active_alarm` snapshot ending in `snapshot_complete`, so a client must discard its accumulated alarm state on the marker and rebuild from that snapshot rather than double-counting it. The publisher's subscription normally opens before any browser connects, so `AlarmsHub.OnConnectedAsync` also primes each new connection itself: it joins the group, sends that client an `AlarmFeedReset` with generation `0`, then the provider status, snapshot status, `active_alarm` rows and `snapshot_complete` read from a fresh monitor subscription (redacted by the same rule). Without it a client connecting after startup saw only later transitions and never the standing alarms or the current provider status. The reset goes out before the snapshot is read, so a transition is either in the snapshot or arrives live after the reset; one applied while the snapshot rows are being sent can land ahead of the older row for the same alarm, which the alarm's next transition or reconcile repair corrects. Each broadcast is bounded to 2 s and abandoned on timeout: awaiting it unbounded let one slow client stall the drain until the monitor dropped the publisher as a slow subscriber, and the resubscribe then replayed the whole snapshot to every client. The tradeoff: a client whose send is abandoned misses that one frame and receives no reset for it, so its alarm view can be stale until the next resubscribe (or until SignalR drops the stalled connection); there is no in-family consumer of `/hubs/alarms` today. The alarm value fields (`current_value` / `limit_value`) are stripped from a deep-cloned copy of the message when `Dashboard:ShowTagValues` is false (the default) — on both value-bearing payload arms, so neither a live transition nor a snapshot record leaks a process value; every other field still renders. The source message is never mutated: it fans out from the same feed to gRPC `StreamAlarms` subscribers, which this dashboard-display flag does not govern. Arms carrying no value are forwarded as-is, uncloned. | +| `AlarmsHub` | `/hubs/alarms` | `AlarmsHubPublisher` (BackgroundService consuming `IGatewayAlarmService.StreamAsync(filter: null)`) | `AlarmFeedMessage` (`active_alarm` / `snapshot_complete` / `transition` / `provider_status` / `snapshot_status`) | Guarded by `MxGateway.Dashboard.Alarms`, not `HubClients`: a real authenticated dashboard role is required, so the `Authentication:Mode=Disabled` and anonymous-localhost bypasses are excluded (SEC-40). Connected clients auto-join `__alarms__`; all admitted clients receive every message — the feed is galaxy-wide and carries no session provenance, so no per-caller scoping applies (see "Alarm-feed visibility"). Publisher auto-reconnects every 5s on stream faults. The publisher is idle-gated on a live-connection count (`AlarmsHubConnectionCounter`): with no hub client connected it holds no monitor subscription and does no cloning or sending; a connection is counted after it has been primed (below), so the first connection opens the subscription without interleaving with its priming frames, and the last disconnect closes it. Every subscription to the monitor — the first and each resubscribe — is preceded by an `AlarmFeedReset` frame (`{ generation }`, monotonic per process): the monitor primes each new subscription with a full `active_alarm` snapshot ending in `snapshot_complete`, so a client must discard its accumulated alarm state on the marker and rebuild from that snapshot rather than double-counting it. The publisher's subscription normally opens before any browser connects, so `AlarmsHub.OnConnectedAsync` also primes each new connection itself: it joins the group, sends that client an `AlarmFeedReset` with generation `0`, then the provider status, snapshot status, `active_alarm` rows and `snapshot_complete` read from a fresh monitor subscription (redacted by the same rule). Without it a client connecting after startup saw only later transitions and never the standing alarms or the current provider status. The reset goes out before the snapshot is read, so a transition is either in the snapshot or arrives live after the reset; one applied while the snapshot rows are being sent can land ahead of the older row for the same alarm, which the alarm's next transition or reconcile repair corrects. Each broadcast is bounded to 2 s and abandoned on timeout: awaiting it unbounded let one slow client stall the drain until the monitor dropped the publisher as a slow subscriber, and the resubscribe then replayed the whole snapshot to every client. The tradeoff: a client whose send is abandoned misses that one frame and receives no reset for it, so its alarm view can be stale until the next resubscribe (or until SignalR drops the stalled connection); there is no in-family consumer of `/hubs/alarms` today. The alarm value fields (`current_value` / `limit_value`) are stripped from a deep-cloned copy of the message when `Dashboard:ShowTagValues` is false (the default) — on both value-bearing payload arms, so neither a live transition nor a snapshot record leaks a process value; every other field still renders. The source message is never mutated: it fans out from the same feed to gRPC `StreamAlarms` subscribers, which this dashboard-display flag does not govern. Arms carrying no value are forwarded as-is, uncloned. | | `EventsHub` | `/hubs/events` | `DashboardEventBroadcaster` invoked by each session's internal dashboard-mirror subscriber on its `SessionEventDistributor` (registered when the session becomes Ready) | `MxEvent` | Clients call `SubscribeSession(sessionId)` to join `session:{id}`, which also registers them in `EventsHubViewerRegistry`. Delivery to the group goes through one bounded per-session pump (see "Mirror gating"), so a slow viewer loses its oldest events instead of accumulating pending sends — the mirror is gated on that registry, which counts hub and in-process viewers alike (see "Mirror gating" below). The dashboard is a first-class distributor subscriber, so it receives the session's events whether or not a gRPC client is streaming. It sees RAW session events — not the per-gRPC-subscriber `AfterWorkerSequence` filtering that `EventStreamService` applies at its own boundary — because the dashboard is a separate LDAP-authenticated monitoring view meant to show the session's full event activity. Tag values are stripped from the mirrored `MxEvent` copy by `DashboardEventBroadcaster` when `Dashboard:ShowTagValues` is false (the default) — event metadata (tag reference, quality, status, timestamps) still renders, but the value fields are blanked, so no value leaks through this seam. `SubscribeSession` is gated by `IDashboardSessionAcl` (SEC-25 / TST-15): a denied caller gets a `HubException`, is not joined to the group, and is not registered as a viewer, so the mirror stays off for a session nobody is legitimately watching. The same ACL gates the in-process seam the session-details page uses, so neither path is the weaker one. Value redaction remains an independent layer — it bounds what a *permitted* subscriber sees. | No hub client ships in this repository: the server-rendered pages read the diff --git a/docs/Sessions.md b/docs/Sessions.md index ab5c2f4a..c9f2784d 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -297,6 +297,8 @@ Emit order on a resumed stream: When `after_worker_sequence` is inside the retained window (nothing was evicted), step 1 is skipped: the stream replays the retained tail then resumes live with no sentinel. +**A cursor ahead of the stream is rejected.** If `after_worker_sequence` is greater than every `worker_sequence` the session has produced (a cursor carried over from an earlier session, a corrupted one, or `2^64 - 1` from an unsigned `0 - 1`), `StreamEvents` fails the attach with gRPC `InvalidArgument` and registers nothing. Accepting it would attach a stream whose live filter drops every event until the session catches up to the bogus value, with nothing replayed and no gap signalled — a silently dead stream. The cursor equal to the newest sequence is valid (fully caught up). A client that gets this error should discard the cursor and attach fresh (`after_worker_sequence = 0`) after re-snapshotting. + **`oldest_available_sequence` when the ring is empty.** Age eviction (`ReplayRetentionSeconds`, default 300) and a disabled ring (`ReplayBufferCapacity = 0`) both leave nothing retained, so there is no oldest-retained sequence to report. In that case the sentinel carries the **next sequence that can possibly be delivered** — the highest sequence the distributor has observed plus one — rather than `0`. That keeps `after_worker_sequence = oldest_available_sequence - 1` the single universal resume formula: the follow-up resume lands exactly on the highest observed sequence, replays nothing, reports no gap, and receives every subsequent live event. Reporting `0` here would make an unsigned client compute `2^64 - 1` and then silently receive nothing, because the live filter drops every event at or below that watermark. Nothing is lost relative to reporting `0` — the evicted interval is unrecoverable either way, and the sentinel's job is to tell the client to re-snapshot. `0` remains the value when there is no gap, where the field is meaningless and never emitted. The ReplayGap sentinel is emitted **only** on the `StreamEvents` server stream and only to the resuming subscriber — it is never fanned to other subscribers and never appears in `DrainEventsReply` (the diagnostic drain path is untouched). Replay retention itself is bounded by `MxGateway:Events:ReplayBufferCapacity` (count), `ReplayRetentionSeconds` (age) and `ReplayBufferMaxBytes` (summed serialized size, so a burst of large-array events cannot pin memory the count cap would allow); whichever binds first evicts oldest-first. Evicted slots are cleared at once, so an evicted event is released immediately rather than when its slot is next reused. See [Configuration](GatewayConfiguration.md). diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/AlarmsPage.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/AlarmsPage.razor index 690a6be2..86a847cd 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/AlarmsPage.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/AlarmsPage.razor @@ -414,11 +414,19 @@ _snapshotTruncated = result.SnapshotTruncated; _workerPid = result.WorkerProcessId; _lastRefresh = DateTimeOffset.UtcNow; - _alarms.Clear(); - _alarms.AddRange(result.Alarms); - _alarmGeneration++; - _unackedCount = _alarms.Count(alarm => alarm.State == AlarmConditionState.Active); - _ackedCount = _alarms.Count(alarm => alarm.State == AlarmConditionState.ActiveAcked); + + // Replace the list, and bump the generation that invalidates the memoized filter/sort and + // area views, only when the alarms actually differ: the poll runs every 3 s per viewer and + // the alarm set is usually static (DSH-010). + if (!DashboardAlarmView.AreSame(_alarms, result.Alarms)) + { + _alarms.Clear(); + _alarms.AddRange(result.Alarms); + _alarmGeneration++; + _unackedCount = _alarms.Count(alarm => alarm.State == AlarmConditionState.Active); + _ackedCount = _alarms.Count(alarm => alarm.State == AlarmConditionState.ActiveAcked); + } + StateHasChanged(); } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SessionDetailsPage.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SessionDetailsPage.razor index 480e6331..523b3736 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SessionDetailsPage.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Pages/SessionDetailsPage.razor @@ -142,9 +142,10 @@ else - @foreach (MxEvent evt in _recentEvents) + @foreach (EventRow row in _recentEvents) { - + MxEvent evt = row.Event; + @evt.WorkerSequence @evt.Family @evt.ServerHandle @@ -162,6 +163,20 @@ else @code { private const int MaxRecentEvents = 50; + /// + /// Minimum spacing between event-driven renders. A busy session emits hundreds of events a + /// second; the page shows only the newest , so rendering more + /// often than a few times a second only costs circuit bandwidth and gateway CPU. + /// + internal static readonly TimeSpan EventRenderInterval = TimeSpan.FromMilliseconds(250); + + // A row's key is page-local rather than the worker sequence: a duplicate key among siblings + // throws in the renderer, and a circuit-killing exception is the wrong failure mode for a + // display-only table. + private sealed record EventRow(long Id, MxEvent Event); + + private long _nextEventRowId; + [Parameter] public string SessionId { get; set; } = string.Empty; @@ -196,7 +211,7 @@ else // subscription (never disposed, its viewer registration never released, its pump never // cancelled) behind the fields it overwrites. private int _attachGeneration; - private readonly LinkedList _recentEvents = new(); + private readonly LinkedList _recentEvents = new(); private bool CanManage { get; set; } @@ -367,13 +382,17 @@ else { while (await subscription.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) { - // Drain what is queued and render once: a burst costs one render pass, - // not one per event. Reading past the display cap would be wasted work, - // and anything left queued is picked up on the next pass. - List batch = new(); - while (batch.Count < MaxRecentEvents && subscription.Reader.TryRead(out MxEvent? mxEvent)) + // Drain everything queued and render once: a burst costs one render pass, + // not one per event. Only the newest MaxRecentEvents can be shown, so older + // ones are discarded as the drain goes rather than held. + Queue batch = new(); + while (subscription.Reader.TryRead(out MxEvent? mxEvent)) { - batch.Add(mxEvent); + batch.Enqueue(mxEvent); + if (batch.Count > MaxRecentEvents) + { + batch.Dequeue(); + } } if (batch.Count == 0) @@ -396,7 +415,7 @@ else foreach (MxEvent mxEvent in batch) { - _recentEvents.AddFirst(mxEvent); + _recentEvents.AddFirst(new EventRow(++_nextEventRowId, mxEvent)); } while (_recentEvents.Count > MaxRecentEvents) @@ -406,6 +425,10 @@ else StateHasChanged(); }).ConfigureAwait(false); + + // Time-based coalescing: events arriving during this wait queue up and are + // drained into the next single render. + await Task.Delay(EventRenderInterval, cancellationToken).ConfigureAwait(false); } } catch (OperationCanceledException) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor index 2ea34f4c..78610fa4 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Shared/NativeDialog.razor @@ -22,6 +22,10 @@ private bool _cancelPending; private object? _lastTarget; private long _generation; + // Generation the JS side was last told to close. close() on an already-closed dialog is a + // no-op there, and the host pages re-render every snapshot tick, so without this a dismissed + // dialog cost one interop round trip per tick for the life of the tab (DSH-008). + private long _closedGeneration = -1; private Task? _disposeTask; /// Whether the parent requests an interactive native modal. @@ -72,7 +76,11 @@ if (_module is null) return; if (!IsOpen) { - await _module.InvokeVoidAsync("close", _element); + if (_closedGeneration != generation) + { + await _module.InvokeVoidAsync("close", _element); + _closedGeneration = generation; + } } else if (_needsOpen) { @@ -82,6 +90,9 @@ openedNow = opened; if (!opened) rejectedGeneration = generation; } + // update() is deliberately not de-duplicated: the JS side clears its in-flight "pending" + // flag there, and a re-render with unchanged parameters is how a rejected submit + // (validation error, guarded handler) re-enables Escape-to-cancel. if (!openedNow && !_disposed && generation == _generation && IsOpen) await _module.InvokeVoidAsync("update", _element, generation, IsBusy); } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAlarmView.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAlarmView.cs index afa4aa69..75259b86 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAlarmView.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAlarmView.cs @@ -43,6 +43,22 @@ public sealed class DashboardAlarmView /// Gets how many times the area list was actually computed (diagnostic, for tests). internal int AreaComputations { get; private set; } + /// + /// Returns whether two poll results hold the same alarms in the same order, so the caller can keep + /// its list and generation (and with them the memoized filter and area views) when nothing changed. + /// + /// The list the page currently holds. + /// The latest poll result. + /// when every alarm row is value-equal, in order. + public static bool AreSame(IReadOnlyList current, IReadOnlyList incoming) + { + ArgumentNullException.ThrowIfNull(current); + ArgumentNullException.ThrowIfNull(incoming); + + // DashboardActiveAlarm is a record, so Equals compares every displayed field. + return current.SequenceEqual(incoming); + } + /// Returns the alarms matching , highest severity then newest first. /// /// Version of ; the caller bumps it whenever it replaces the list's contents. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs index 7ac053fb..b6564332 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs @@ -107,6 +107,7 @@ public static class DashboardServiceCollectionExtensions static provider => provider.GetRequiredService()); services.AddSingleton(); services.AddHostedService(); + services.AddSingleton(); services.AddHostedService(); services.AddHttpContextAccessor(); services.AddSingleton(); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs index 1b1be7dc..5a2d15d6 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardSnapshotService.cs @@ -23,8 +23,20 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService /// internal const string UnknownStatus = "Unknown"; - /// Upper bound on one health evaluation, so a hung check cannot stall the snapshot tick. - private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(2); + /// + /// Upper bound on one health evaluation. Longer than the slowest per-check timeout + /// (Galaxy SQL, 5 s) so a slow check reports its own Unhealthy result instead of + /// being cancelled into . The evaluation runs off the snapshot + /// tick, so the bound no longer affects snapshot cadence. + /// + private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(8); + + /// + /// Minimum spacing between health evaluations. The checks open a SQLite connection and + /// round-trip to the Galaxy SQL server, so running them on every ~1s snapshot tick for as + /// long as a dashboard tab is open is a steady 1-2 Hz ping against both. + /// + private static readonly TimeSpan GatewayStatusRefreshInterval = TimeSpan.FromSeconds(10); /// /// Minimum spacing between API key list reads. The list is a SQLite query whose @@ -53,6 +65,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService private readonly SemaphoreSlim _apiKeySummaryRefreshGate = new(1, 1); private readonly SemaphoreSlim _gatewayStatusRefreshGate = new(1, 1); private string _gatewayStatus = UnknownStatus; + private long _gatewayStatusRefreshedAtTicks = NeverRefreshedTicks; private IReadOnlyList _apiKeySummaries = Array.Empty(); private long _apiKeySummariesRefreshedAtTicks = NeverRefreshedTicks; // The effective configuration is built from IOptions and is startup-static: @@ -80,7 +93,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService /// Optional logger for the dashboard snapshot service. /// /// The gateway's registered health checks. - /// is the aggregate status of one evaluation per snapshot tick; without it the + /// is the aggregate status of the latest evaluation (refreshed every 10 s off the tick); without it the /// status stays . /// public DashboardSnapshotService( @@ -191,6 +204,8 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService } await RefreshApiKeySummariesAsync(cancellationToken).ConfigureAwait(false); + + // The first snapshot waits for an evaluation so it never shows a status nobody checked. await RefreshGatewayStatusAsync(cancellationToken).ConfigureAwait(false); yield return GetSnapshot(); @@ -213,23 +228,55 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService } await RefreshApiKeySummariesAsync(cancellationToken).ConfigureAwait(false); - await RefreshGatewayStatusAsync(cancellationToken).ConfigureAwait(false); + StartGatewayStatusRefreshIfDue(); yield return GetSnapshot(); } } + private bool IsGatewayStatusDue() + { + long refreshedAt = Volatile.Read(ref _gatewayStatusRefreshedAtTicks); + return refreshedAt == NeverRefreshedTicks + || _timeProvider.GetUtcNow().UtcTicks - refreshedAt >= GatewayStatusRefreshInterval.Ticks; + } + /// - /// Evaluates the registered health checks once and caches the aggregate status + /// Starts a health evaluation in the background when the cached status is older than + /// . The snapshot tick reads the cached value and + /// never waits on a check, so a slow or unreachable Galaxy SQL server cannot slow the cadence. + /// + private void StartGatewayStatusRefreshIfDue() + { + if (_healthCheckService is null || _gatewayStatusRefreshGate.CurrentCount == 0 || !IsGatewayStatusDue()) + { + return; + } + + _ = Task.Run(async () => + { + try + { + await RefreshGatewayStatusAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception exception) + { + _logger.LogDebug(exception, "Dashboard background health refresh failed."); + } + }); + } + + /// + /// Evaluates the registered health checks and caches the aggregate status /// for , which is synchronous and also serves page seeds - /// and hub connects between ticks. One evaluation per tick, not per - /// call: the checks include an auth-store query, and the - /// tick is already the cadence at which the dashboard refreshes. + /// and hub connects between ticks. A cached status younger than + /// is reused: the checks include an auth-store + /// query and a Galaxy SQL round trip. /// /// Token to cancel the evaluation. /// A task that represents the asynchronous operation. public async Task RefreshGatewayStatusAsync(CancellationToken cancellationToken) { - if (_healthCheckService is null) + if (_healthCheckService is null || !IsGatewayStatusDue()) { return; } @@ -243,10 +290,17 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService try { + // An evaluation that finished while this call waited on the gate already refreshed the cache. + if (!IsGatewayStatusDue()) + { + return; + } + using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); timeout.CancelAfter(GatewayStatusRefreshTimeout); HealthReport report = await _healthCheckService.CheckHealthAsync(timeout.Token).ConfigureAwait(false); Volatile.Write(ref _gatewayStatus, report.Status.ToString()); + Volatile.Write(ref _gatewayStatusRefreshedAtTicks, _timeProvider.GetUtcNow().UtcTicks); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -256,6 +310,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService { // A health evaluation that cannot complete is not evidence of health. Volatile.Write(ref _gatewayStatus, UnknownStatus); + Volatile.Write(ref _gatewayStatusRefreshedAtTicks, _timeProvider.GetUtcNow().UtcTicks); _logger.LogDebug(exception, "Dashboard gateway health evaluation failed."); } finally diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs index 0670d28e..8c6d5771 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHub.cs @@ -31,12 +31,19 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; /// /// The gateway's central alarm feed. /// Gateway options supplying Dashboard:ShowTagValues. +/// Live-connection count that idle-gates . [Authorize(Policy = DashboardAuthenticationDefaults.AlarmsPolicy)] -public sealed class AlarmsHub(IGatewayAlarmService alarmService, IOptions options) : Hub +public sealed class AlarmsHub( + IGatewayAlarmService alarmService, + IOptions options, + AlarmsHubConnectionCounter connectionCounter) : Hub { /// Group every admitted connection joins on connect. public const string AllAlarmsGroup = "__alarms__"; + /// Context.Items key marking a connection that was added to the live count. + private const string CountedItemKey = "mxgw.alarms.counted"; + /// Method name used to push AlarmFeedMessage values to clients. public const string AlarmMessage = "AlarmFeed"; @@ -59,6 +66,25 @@ public sealed class AlarmsHub(IGatewayAlarmService alarmService, IOptions + public override async Task OnDisconnectedAsync(Exception? exception) + { + // A connection whose priming failed was never counted; decrementing it would drive the + // count negative and leave the publisher subscribed to nobody. + if (Context.Items.Remove(CountedItemKey)) + { + connectionCounter.Decrement(); + } + + await base.OnDisconnectedAsync(exception).ConfigureAwait(false); + } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs new file mode 100644 index 00000000..44b4eaa1 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubConnectionCounter.cs @@ -0,0 +1,40 @@ +namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; + +/// +/// Process-wide count of live connections. Read by +/// to idle-gate the alarm broadcast: the server-rendered +/// Alarms page does not use the hub, so in most deployments there is no connection and nothing +/// to broadcast to. +/// +public sealed class AlarmsHubConnectionCounter +{ + private int _count; + + /// Gets the number of live alarms hub connections. + public int Count => Volatile.Read(ref _count); + + /// Records a new alarms hub connection. + /// The connection count after the increment. + public int Increment() => Interlocked.Increment(ref _count); + + /// + /// Records an alarms hub disconnection, clamped at zero inside the compare-and-swap for the + /// same reason as : SignalR can + /// raise a disconnect for a connection whose connect faulted, and a negative count would gate + /// the publisher off while a real client is attached. + /// + /// The connection count after the decrement. + public int Decrement() + { + int current; + int next; + do + { + current = Volatile.Read(ref _count); + next = current > 0 ? current - 1 : 0; + } + while (Interlocked.CompareExchange(ref _count, next, current) != current); + + return next; + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs index 0eab4519..76659cfe 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Hubs/AlarmsHubPublisher.cs @@ -32,6 +32,13 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs; /// per-caller scope the feed does not carry. /// /// +/// The loop is idle-gated on . With no hub client +/// connected the publisher holds no monitor subscription at all, so it pays no redaction clone, +/// no group send and no snapshot replay for output nobody receives; the first connection opens the +/// subscription (and so receives the reset marker and the primed snapshot), and the last +/// disconnect closes it. +/// +/// /// Each broadcast is time-bounded (). A group send /// completes only once every member accepted the frame, so awaiting it unbounded /// let one slow browser stall this loop; the stalled loop stopped draining its @@ -53,45 +60,58 @@ public sealed class AlarmsHubPublisher : BackgroundService /// Upper bound on one alarm broadcast before it is abandoned. internal static readonly TimeSpan DefaultSendTimeout = TimeSpan.FromSeconds(2); + /// How often the idle publisher re-checks for a connected client, and the live one for none. + internal static readonly TimeSpan DefaultIdlePollInterval = TimeSpan.FromSeconds(1); + private readonly IGatewayAlarmService _alarmService; private readonly IHubContext _hubContext; private readonly ILogger _logger; private readonly TimeSpan _sendTimeout; + private readonly AlarmsHubConnectionCounter _connectionCounter; + private readonly TimeSpan _idlePollInterval; private readonly bool _showTagValues; private long _subscriptionGeneration; /// Initializes a new instance of the class. /// The gateway's central alarm feed. /// Hub context used to broadcast to the alarms group. + /// Live alarms hub connection count used to idle-gate the subscription. /// Gateway options supplying Dashboard:ShowTagValues. /// Logger for best-effort broadcast failures. public AlarmsHubPublisher( IGatewayAlarmService alarmService, IHubContext hubContext, + AlarmsHubConnectionCounter connectionCounter, IOptions options, ILogger logger) - : this(alarmService, hubContext, options, logger, DefaultSendTimeout) + : this(alarmService, hubContext, connectionCounter, options, logger, DefaultSendTimeout, DefaultIdlePollInterval) { } /// Initializes a new instance with a custom send timeout (test hook). /// The gateway's central alarm feed. /// Hub context used to broadcast to the alarms group. + /// Live alarms hub connection count used to idle-gate the subscription. /// Gateway options supplying Dashboard:ShowTagValues. /// Logger for best-effort broadcast failures. /// Upper bound on one broadcast. + /// How often the connection count is re-checked. internal AlarmsHubPublisher( IGatewayAlarmService alarmService, IHubContext hubContext, + AlarmsHubConnectionCounter connectionCounter, IOptions options, ILogger logger, - TimeSpan sendTimeout) + TimeSpan sendTimeout, + TimeSpan idlePollInterval) { ArgumentNullException.ThrowIfNull(options); _alarmService = alarmService ?? throw new ArgumentNullException(nameof(alarmService)); _hubContext = hubContext ?? throw new ArgumentNullException(nameof(hubContext)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _sendTimeout = sendTimeout; + _connectionCounter = connectionCounter ?? throw new ArgumentNullException(nameof(connectionCounter)); + _idlePollInterval = idlePollInterval; _showTagValues = options.Value.Dashboard.ShowTagValues; } @@ -105,26 +125,49 @@ public sealed class AlarmsHubPublisher : BackgroundService { try { - // Sent before the subscription opens, so it reaches clients ahead of - // the snapshot the monitor primes the new subscription with. - long generation = Interlocked.Increment(ref _subscriptionGeneration); - await BroadcastAsync( - AlarmsHub.ResetMessage, - new AlarmFeedReset(generation), - stoppingToken) - .ConfigureAwait(false); - - await foreach (AlarmFeedMessage message in _alarmService - .StreamAsync(alarmFilterPrefix: null, stoppingToken) - .ConfigureAwait(false)) + // No client, no subscription: nothing to clone, send or replay. + if (_connectionCounter.Count == 0) { - if (stoppingToken.IsCancellationRequested) - { - break; - } + await Task.Delay(_idlePollInterval, stoppingToken).ConfigureAwait(false); + continue; + } - AlarmFeedMessage outbound = _showTagValues ? message : RedactValues(message); - await BroadcastAsync(AlarmsHub.AlarmMessage, outbound, stoppingToken).ConfigureAwait(false); + // Cancelled when the last client disconnects (or the host stops), which ends the + // monitor subscription; the loop then idles until the next connection. + using CancellationTokenSource subscription = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + Task idleWatcher = CancelWhenIdleAsync(subscription); + try + { + // Sent before the subscription opens, so it reaches clients ahead of + // the snapshot the monitor primes the new subscription with. + long generation = Interlocked.Increment(ref _subscriptionGeneration); + await BroadcastAsync( + AlarmsHub.ResetMessage, + new AlarmFeedReset(generation), + subscription.Token) + .ConfigureAwait(false); + + await foreach (AlarmFeedMessage message in _alarmService + .StreamAsync(alarmFilterPrefix: null, subscription.Token) + .ConfigureAwait(false)) + { + if (subscription.IsCancellationRequested) + { + break; + } + + AlarmFeedMessage outbound = _showTagValues ? message : RedactValues(message); + await BroadcastAsync(AlarmsHub.AlarmMessage, outbound, subscription.Token).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (!stoppingToken.IsCancellationRequested) + { + // The last client left; fall through to the idle check. + } + finally + { + await subscription.CancelAsync().ConfigureAwait(false); + await idleWatcher.ConfigureAwait(false); } } catch (OperationCanceledException) @@ -146,6 +189,26 @@ public sealed class AlarmsHubPublisher : BackgroundService } } + private async Task CancelWhenIdleAsync(CancellationTokenSource subscription) + { + try + { + while (!subscription.IsCancellationRequested) + { + await Task.Delay(_idlePollInterval, subscription.Token).ConfigureAwait(false); + if (_connectionCounter.Count == 0) + { + await subscription.CancelAsync().ConfigureAwait(false); + return; + } + } + } + catch (OperationCanceledException) + { + // The subscription ended first; nothing left to watch. + } + } + /// /// Primes one newly connected client with the feed's current state: a /// marker with generation 0, then the provider diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs index 01a51c2d..cc3a308a 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs @@ -1224,6 +1224,7 @@ public sealed class MxAccessGatewayService( SessionManagerErrorCode.CloseFailed => StatusCode.Unavailable, SessionManagerErrorCode.PermissionDenied => StatusCode.PermissionDenied, SessionManagerErrorCode.GatewayStopping => StatusCode.Unavailable, + SessionManagerErrorCode.InvalidResumeCursor => StatusCode.InvalidArgument, _ => StatusCode.Unavailable, }; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs index 5bba3037..13378178 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/AuditDrainService.cs @@ -45,7 +45,6 @@ public sealed class AuditDrainService( try { await sink.EnsureInitializedAsync(cancellationToken).ConfigureAwait(false); - await SweepRetentionAsync(cancellationToken).ConfigureAwait(false); } catch (Exception exception) { @@ -250,6 +249,10 @@ public sealed class AuditDrainService( { try { + // The first sweep runs here rather than in StartAsync: on a large audit table it can + // take a while (and builds the retention index once), and host startup must not wait on it. + await SweepRetentionAsync(stoppingToken).ConfigureAwait(false); + using PeriodicTimer timer = new(RetentionSweepInterval, timeProvider); while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs index 11170abc..b638478e 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/SqliteCanonicalAuditStore.cs @@ -66,6 +66,19 @@ public sealed class SqliteCanonicalAuditStore( $category, $target, $source_node, $correlation_id, $details_json); """; + // Index on the same expression the sweep compares, so the DELETE seeks instead of scanning the + // whole table. It is the instant (datetime()), not the raw text, that is indexed: the sweep + // compares instants so rows in a non-UTC or mixed format are still judged correctly. + private const string CreateRetentionIndexSql = + "CREATE INDEX IF NOT EXISTS ix_audit_event_occurred_instant ON audit_event (datetime(occurred_at_utc));"; + + // Rows removed per statement. Each chunk is its own implicit transaction, so the single SQLite + // write lock (shared with the API-key store's last_used writes) is released between chunks. + private const int SweepChunkSize = 5000; + + /// 0 until the retention index has been created at least once by this instance. + private int _retentionIndexEnsured; + /// 0 until the audit_event table has been created at least once by this instance. private int _tableEnsured; @@ -162,17 +175,32 @@ public sealed class SqliteCanonicalAuditStore( await EnsureTableAsync(connection, cancellationToken).ConfigureAwait(false); - await using SqliteCommand command = connection.CreateCommand(); - command.CommandText = - """ - DELETE FROM audit_event - WHERE datetime(occurred_at_utc) < datetime($cutoff); - """; - command.Parameters.AddWithValue( - "$cutoff", - cutoffUtc.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)); + await EnsureRetentionIndexAsync(connection, cancellationToken).ConfigureAwait(false); - return await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + string cutoff = cutoffUtc.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture); + int total = 0; + int deleted; + + do + { + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = + """ + DELETE FROM audit_event + WHERE rowid IN ( + SELECT rowid FROM audit_event + WHERE datetime(occurred_at_utc) < datetime($cutoff) + LIMIT $chunk); + """; + command.Parameters.AddWithValue("$cutoff", cutoff); + command.Parameters.AddWithValue("$chunk", SweepChunkSize); + + deleted = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + total += deleted; + } + while (deleted >= SweepChunkSize); + + return total; } /// Returns the most recent canonical audit events, newest first. @@ -226,6 +254,22 @@ public sealed class SqliteCanonicalAuditStore( return events; } + // Created lazily by the sweep rather than with the table: building it over a large existing + // table is a one-time cost, and it belongs on the background retention loop, not on startup. + private async Task EnsureRetentionIndexAsync(SqliteConnection connection, CancellationToken cancellationToken) + { + if (Volatile.Read(ref _retentionIndexEnsured) == 1) + { + return; + } + + await using SqliteCommand command = connection.CreateCommand(); + command.CommandText = CreateRetentionIndexSql; + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + + Volatile.Write(ref _retentionIndexEnsured, 1); + } + // Latched bootstrap: after the first success this is a single volatile read, so the DDL // round-trip is paid once per process rather than once per audit write. private async Task EnsureTableAsync(SqliteConnection connection, CancellationToken cancellationToken) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs index bb1b2741..04250387 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; @@ -478,8 +479,35 @@ public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalid return false; } - byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(token.ToString())); - cacheKey = CacheKeyPrefix + Convert.ToHexString(hash); - return true; + // Hashed from a stack buffer straight off the header span: this runs on every authenticated + // RPC, so the per-call token string, UTF-8 array, hash array and hex string are avoided; + // the only allocation left is the cache key itself. + const int StackLimit = 512; + int byteCount = Encoding.UTF8.GetByteCount(token); + byte[]? rented = null; + Span utf8 = byteCount <= StackLimit + ? stackalloc byte[StackLimit] + : (rented = ArrayPool.Shared.Rent(byteCount)); + try + { + int written = Encoding.UTF8.GetBytes(token, utf8); + Span hash = stackalloc byte[SHA256.HashSizeInBytes]; + SHA256.HashData(utf8[..written], hash); + + Span chars = stackalloc char[CacheKeyPrefix.Length + (SHA256.HashSizeInBytes * 2)]; + CacheKeyPrefix.AsSpan().CopyTo(chars); + Convert.TryToHexString(hash, chars[CacheKeyPrefix.Length..], out _); + cacheKey = new string(chars); + return true; + } + finally + { + // The buffer held the bearer token; clear it before it is reused or left on the stack. + CryptographicOperations.ZeroMemory(utf8[..byteCount]); + if (rented is not null) + { + ArrayPool.Shared.Return(rented); + } + } } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs index 69d73c98..cd304197 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/GatewayApiKeyIdentityMapper.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Runtime.CompilerServices; using LibApiKeyIdentity = ZB.MOM.WW.Auth.Abstractions.ApiKeys.ApiKeyIdentity; @@ -45,6 +46,14 @@ public static class GatewayApiKeyIdentityMapper private static readonly ConcurrentQueue InsertionOrder = new(); private static readonly object EvictionLock = new(); + /// + /// Mapped gateway identity per shared-library identity instance. The caching verifier hands + /// back the same library identity for every RPC inside its TTL, so the mapping (and its + /// record allocation) is done once per cached verification instead of once per RPC. The + /// table is weak, so an identity that ages out of the verifier cache takes its mapping with it. + /// + private static readonly ConditionalWeakTable MappedIdentities = new(); + /// Current cache size, exposed for tests asserting the cap is honoured. internal static int CurrentCacheSize => ConstraintCache.Count; @@ -103,11 +112,16 @@ public static class GatewayApiKeyIdentityMapper { ArgumentNullException.ThrowIfNull(identity); + if (MappedIdentities.TryGetValue(identity, out ApiKeyIdentity? mapped)) + { + return mapped; + } + // The library stores the opaque constraints blob in Constraints as the ConstraintsJson // string (or null when the key has no constraints). string? constraintsJson = identity.Constraints as string; - return new ApiKeyIdentity( + ApiKeyIdentity created = new( KeyId: identity.KeyId, // The gateway token prefix is fixed ("mxgw"); the key id is its own field. KeyPrefix // is retained only for surface compatibility with the gateway identity record. @@ -115,5 +129,8 @@ public static class GatewayApiKeyIdentityMapper DisplayName: identity.DisplayName, Scopes: identity.Scopes, Constraints: DeserializeConstraints(constraintsJson)); + + // GetValue-style race: two racers may both build one; both are equivalent, keep the winner. + return MappedIdentities.GetValue(identity, _ => created); } } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs index 9f61c2e0..d6b5d8f1 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs @@ -1527,12 +1527,15 @@ public sealed class GatewaySession : IAsyncDisposable CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(command); + + // Readiness first: expanding a sparse array write allocates a whole array, so a session that + // cannot take the command must fail before that cost is paid (SES-008). + IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false); if (command.Command is not null) { NormalizeOutboundCommand(command.Command); } - IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false); TouchClientActivity(_eventStreaming.TimeProvider.GetUtcNow()); return await workerClient.InvokeAsync(command, CommandTimeout, cancellationToken).ConfigureAwait(false); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs index c2f5032a..6523815f 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionEventDistributor.cs @@ -534,6 +534,19 @@ public sealed class SessionEventDistributor : IAsyncDisposable { EvictAged(); + // A cursor above every sequence this session has produced cannot have come from this + // session's stream (a stale cursor from an earlier session, or a corrupted one). Resuming + // from it would attach a stream whose live filter drops every event until the session + // catches up, with nothing replayed and no gap signalled — a silently dead stream. Refuse + // it before anything is registered so the client learns of the mistake at attach time. + if (afterSequence > _highestSequenceSeen) + { + throw new SessionManagerException( + SessionManagerErrorCode.InvalidResumeCursor, + $"after_worker_sequence {afterSequence} is ahead of the newest event ({_highestSequenceSeen}) session {_sessionId} has produced; " + + "resume with the last worker_sequence this session delivered, or use 0 for a fresh stream."); + } + List newer = []; ulong highestReplayed = afterSequence; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs index d302cf48..6e1c324b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManagerErrorCode.cs @@ -25,4 +25,12 @@ public enum SessionManagerErrorCode /// against the restarted gateway. /// GatewayStopping, + + /// + /// A StreamEvents resume cursor (after_worker_sequence) is ahead of every + /// event the session has produced, so it cannot have come from this session's stream. + /// Accepting it would attach a stream that silently drops every event until the session + /// catches up to the bogus cursor. Maps to gRPC InvalidArgument. + /// + InvalidResumeCursor, } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs index ec38ce7b..cbd1416b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SparseArrayExpander.cs @@ -26,6 +26,10 @@ namespace ZB.MOM.WW.MxGateway.Server.Sessions; /// internal static class SparseArrayExpander { + // Shared filler for unspecified Time slots. Timestamp is a mutable protobuf type, so this must + // never be handed to code that edits array elements in place; the expanded value is serialized only. + private static readonly Timestamp DefaultTimestamp = new() { Seconds = 0, Nanos = 0 }; + /// /// Replaces 's with an /// equivalent full . If is not @@ -231,9 +235,12 @@ internal static class SparseArrayExpander { TimestampArray values = new(); values.Values.Capacity = length; + // One shared default instance for every unspecified slot: the expanded array is only + // serialized, never mutated in place, and a distinct Timestamp per slot cost a million + // objects for a request of a few dozen bytes (SES-008). for (int i = 0; i < length; i++) { - values.Values.Add(new Timestamp { Seconds = 0, Nanos = 0 }); + values.Values.Add(DefaultTimestamp); } foreach (MxSparseElement element in elements) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs index 1257bd45..17ba7ec0 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs @@ -24,7 +24,7 @@ public sealed class WorkerClient : IWorkerClient private readonly ILogger _logger; private readonly WorkerFrameReader _reader; private readonly WorkerFrameWriter _writer; - private readonly Channel _outboundEnvelopes; + private readonly Channel _outboundEnvelopes; private readonly Channel _events; // Staging hand-off between the read loop and the dedicated event writer. The read loop writes @@ -94,7 +94,7 @@ public sealed class WorkerClient : IWorkerClient _reader = new WorkerFrameReader(connection.Stream, connection.FrameOptions); _writer = new WorkerFrameWriter(connection.Stream, connection.FrameOptions); _pendingCommandSlots = new SemaphoreSlim(_options.MaxPendingCommands, _options.MaxPendingCommands); - _outboundEnvelopes = Channel.CreateBounded( + _outboundEnvelopes = Channel.CreateBounded( new BoundedChannelOptions(_options.MaxPendingCommands + 4) { SingleReader = true, @@ -301,10 +301,13 @@ public sealed class WorkerClient : IWorkerClient // nothing; only a full channel pays for a linked, deadline-bound token. cancellationToken.ThrowIfCancellationRequested(); TimeSpan replyTimeout = timeout; - if (!_outboundEnvelopes.Writer.TryWrite(commandEnvelope)) + // envelopeSize rides along so the write loop does not walk the whole command graph again + // to size the frame (it adds the exact sequence-stamp bytes instead). + if (!_outboundEnvelopes.Writer.TryWrite(new OutboundEnvelope(commandEnvelope, envelopeSize))) { replyTimeout = await EnqueueCommandWithinDeadlineAsync( commandEnvelope, + envelopeSize, correlationId, pendingCommand, method, @@ -383,11 +386,26 @@ public sealed class WorkerClient : IWorkerClient throw; } } - catch + catch (Exception exception) { + // Reached with the entry still present only for exits that never got a reply: the + // CommandTooLarge rejection, a failed enqueue, or cancellation during the enqueue. Every + // other exit (reply, timeout, wait cancellation, worker fault) already removed the entry + // and recorded its own terminal metric, so the removal below is what keeps this from + // double-counting. Without it commands.started climbed with no matching terminal counter. if (_pendingCommands.TryRemove(correlationId, out _)) { ReleasePendingCommandSlot(); + string category = exception switch + { + WorkerClientException workerException => workerException.ErrorCode.ToString(), + OperationCanceledException => WorkerClientErrorCode.CallerCancelled.ToString(), + _ => exception.GetType().Name, + }; + _metrics?.CommandFailed( + pendingCommand.Method, + category, + _timeProvider.GetElapsedTime(pendingCommand.StartTimestamp)); } throw; @@ -574,13 +592,19 @@ public sealed class WorkerClient : IWorkerClient /// private const int MaxSequenceEncodingBytes = 11; + // An envelope queued for the write loop, with the size measured by the CommandTooLarge pre-check + // (-1 when the envelope was not measured). Carrying it spares the writer a second walk of the + // whole message graph per command. + private readonly record struct OutboundEnvelope(WorkerEnvelope Envelope, int SizeBeforeSequence); + /// Manages writing envelopes to the worker pipe. private async Task WriteLoopAsync() { try { - await foreach (WorkerEnvelope envelope in _outboundEnvelopes.Reader.ReadAllAsync(_stopCts.Token).ConfigureAwait(false)) + await foreach (OutboundEnvelope outbound in _outboundEnvelopes.Reader.ReadAllAsync(_stopCts.Token).ConfigureAwait(false)) { + WorkerEnvelope envelope = outbound.Envelope; // stamp the sequence at the point of writing, not when the envelope is built. // Stamping at construction let two concurrent InvokeAsync callers take 1 and 2 and then // enqueue in the order 2, 1 — non-monotonic on the wire, breaking gateway.md's @@ -588,7 +612,7 @@ public sealed class WorkerClient : IWorkerClient // (SingleReader = true), so wire order and stamp order are the same thing here and // _nextSequence needs no interlocking. Mirrors the worker's equivalent fix. envelope.Sequence = unchecked(++_nextSequence); - await _writer.WriteAsync(envelope, _stopCts.Token).ConfigureAwait(false); + await _writer.WriteAsync(envelope, outbound.SizeBeforeSequence, _stopCts.Token).ConfigureAwait(false); } } catch (OperationCanceledException) when (_stopCts.IsCancellationRequested || IsTerminalState()) @@ -1025,7 +1049,7 @@ public sealed class WorkerClient : IWorkerClient Reason = reason, }); - if (_outboundEnvelopes.Writer.TryWrite(cancelEnvelope)) + if (_outboundEnvelopes.Writer.TryWrite(new OutboundEnvelope(cancelEnvelope, -1))) { return; } @@ -1411,13 +1435,17 @@ public sealed class WorkerClient : IWorkerClient /// Enqueues an envelope for writing to the worker. /// Envelope to enqueue. /// Cancellation token. + /// + /// The envelope's CalculateSize() while its sequence was still unset, or -1 when not measured. + /// private async Task EnqueueAsync( WorkerEnvelope envelope, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + int sizeBeforeSequence = -1) { try { - await _outboundEnvelopes.Writer.WriteAsync(envelope, cancellationToken).ConfigureAwait(false); + await _outboundEnvelopes.Writer.WriteAsync(new OutboundEnvelope(envelope, sizeBeforeSequence), cancellationToken).ConfigureAwait(false); } catch (ChannelClosedException exception) { @@ -1434,6 +1462,7 @@ public sealed class WorkerClient : IWorkerClient /// deadline for the reply wait. /// /// Command envelope to enqueue. + /// The envelope's size before its sequence is stamped. /// Command correlation id. /// The command's pending entry. /// Command method name for metrics and messages. @@ -1442,6 +1471,7 @@ public sealed class WorkerClient : IWorkerClient /// The part of left for the reply wait. private async Task EnqueueCommandWithinDeadlineAsync( WorkerEnvelope commandEnvelope, + int envelopeSize, string correlationId, PendingCommand pendingCommand, string method, @@ -1452,7 +1482,7 @@ public sealed class WorkerClient : IWorkerClient deadlineCts.CancelAfter(timeout); try { - await EnqueueAsync(commandEnvelope, deadlineCts.Token).ConfigureAwait(false); + await EnqueueAsync(commandEnvelope, deadlineCts.Token, envelopeSize).ConfigureAwait(false); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs index a7f1cf43..ad71dd93 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerFrameWriter.cs @@ -32,14 +32,36 @@ public sealed class WorkerFrameWriter /// Worker envelope message to write. /// Token to cancel the asynchronous operation. /// A task that represents the asynchronous operation. + public ValueTask WriteAsync( + WorkerEnvelope envelope, + CancellationToken cancellationToken = default) => + WriteAsync(envelope, sizeBeforeSequence: -1, cancellationToken); + + /// + /// Writes a WorkerEnvelope as a length-prefixed message, reusing a size the caller already + /// computed so the writer does not walk the whole message graph a second time. + /// + /// Worker envelope message to write. + /// + /// envelope.CalculateSize() as measured while was still + /// 0, or a negative value when no size is known. The writer adds the exact encoded size of the + /// sequence stamp applied since. Only valid when nothing but Sequence changed after the + /// measurement; WriteTo fails loudly (it checks the buffer is filled exactly) rather than + /// emitting a wrong length prefix if that is ever violated. + /// + /// Token to cancel the asynchronous operation. + /// A task that represents the asynchronous operation. public async ValueTask WriteAsync( WorkerEnvelope envelope, + int sizeBeforeSequence, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(envelope); WorkerEnvelopeValidator.Validate(envelope, _options); - int payloadLength = envelope.CalculateSize(); + int payloadLength = sizeBeforeSequence >= 0 + ? sizeBeforeSequence + SequenceStampSize(envelope.Sequence) + : envelope.CalculateSize(); if (payloadLength == 0) { throw new WorkerFrameProtocolException( @@ -75,4 +97,12 @@ public sealed class WorkerFrameWriter ArrayPool.Shared.Return(frame); } } + + // Bytes the sequence field adds to an envelope that was measured with Sequence == 0 (an unset + // proto3 scalar is not encoded): its tag plus the varint of the stamped value. + private static int SequenceStampSize(ulong sequence) => + sequence == 0 + ? 0 + : CodedOutputStream.ComputeTagSize(WorkerEnvelope.SequenceFieldNumber) + + CodedOutputStream.ComputeUInt64Size(sequence); } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardAlarmViewTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardAlarmViewTests.cs index d9a56452..864cc070 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardAlarmViewTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardAlarmViewTests.cs @@ -27,6 +27,37 @@ public sealed class DashboardAlarmViewTests Assert.Equal(["B", "A"], first.Select(alarm => alarm.Reference)); } + /// + /// DSH-010: a poll that returns an unchanged alarm set is detected as such, so the page keeps its + /// generation and the filter/sort stays at one computation; a real change is detected. + /// + [Fact] + public void AreSame_DetectsUnchangedPollsSoTheGenerationIsNotBumped() + { + DashboardAlarmView view = new(); + List held = [Alarm("A", 500), Alarm("B", 800)]; + long generation = 1; + view.Filtered(generation, DefaultCriteria, held); + + // Two further polls with value-equal (but freshly projected) rows. + for (int poll = 0; poll < 2; poll++) + { + DashboardActiveAlarm[] incoming = [Alarm("A", 500), Alarm("B", 800)]; + if (!DashboardAlarmView.AreSame(held, incoming)) + { + held = [.. incoming]; + generation++; + } + + view.Filtered(generation, DefaultCriteria, held); + } + + Assert.Equal(1, view.FilterComputations); + + Assert.False(DashboardAlarmView.AreSame(held, [Alarm("A", 500), Alarm("B", 900)])); + Assert.False(DashboardAlarmView.AreSame(held, [Alarm("A", 500)])); + } + /// A changed filter input or a new alarm generation recomputes. [Fact] public void Filtered_WhenCriteriaOrGenerationChange_Recomputes() diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs new file mode 100644 index 00000000..b345baa4 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/NativeDialogInteropTests.cs @@ -0,0 +1,156 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Rendering; +using Microsoft.AspNetCore.Components.RenderTree; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.JSInterop; +using ZB.MOM.WW.MxGateway.Server.Dashboard.Components.Shared; + +namespace ZB.MOM.WW.MxGateway.Tests.Dashboard; + +/// DSH-008: a dismissed must not cost JS interop on every parent render. +public sealed class NativeDialogInteropTests +{ + /// Open then close, then ten parent re-renders: only the one close call reaches JS. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ClosedDialog_WhenParentRerenders_DoesNotCallCloseAgain() + { + RecordingJsRuntime js = new(); + ServiceCollection services = new(); + services.AddLogging(); + services.AddSingleton(js); + await using ServiceProvider provider = services.BuildServiceProvider(); + await using TestRenderer renderer = new(provider, provider.GetRequiredService()); + HostHandle handle = new(); + + await renderer.MountAsync(handle); + + await SetOpenAsync(renderer, handle, true); + Assert.Equal(1, js.ModuleCalls.Count(call => call == "open")); + + await SetOpenAsync(renderer, handle, false); + Assert.Equal(1, js.ModuleCalls.Count(call => call == "close")); + + for (int i = 0; i < 10; i++) + { + await renderer.Dispatcher.InvokeAsync(() => handle.Host!.Rerender()); + await Task.Delay(10); + } + + Assert.Equal(1, js.ModuleCalls.Count(call => call == "close")); + } + + private static async Task SetOpenAsync(TestRenderer renderer, HostHandle handle, bool open) + { + await renderer.Dispatcher.InvokeAsync(() => + { + handle.Host!.Open = open; + handle.Host.Rerender(); + }); + await Task.Delay(50); + } + + // Minimal renderer that runs OnAfterRenderAsync (the static HtmlRenderer does not), which is + // where NativeDialog makes its interop calls. BL0006 is suppressed for this test-only scaffold. +#pragma warning disable BL0006 + private sealed class TestRenderer(IServiceProvider services, ILoggerFactory loggerFactory) + : Renderer(services, loggerFactory) + { + /// + public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault(); + + /// Mounts the host component and renders it. + /// Handle the host publishes itself through. + /// A task that completes once the first render has been dispatched. + public Task MountAsync(HostHandle handle) => Dispatcher.InvokeAsync(() => + { + DialogHost host = (DialogHost)InstantiateComponent(typeof(DialogHost)); + host.Handle = handle; + int id = AssignRootComponentId(host); + return RenderRootComponentAsync(id); + }); + + /// + protected override void HandleException(Exception exception) => throw new InvalidOperationException("render fault", exception); + + /// + protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask; + } +#pragma warning restore BL0006 + + private sealed class HostHandle + { + /// Gets or sets the mounted host. + public DialogHost? Host { get; set; } + } + + private sealed class DialogHost : ComponentBase + { + /// Gets or sets the handle the test uses to reach this instance. + public HostHandle Handle { get; set; } = null!; + + /// Gets or sets a value indicating whether the dialog is open. + public bool Open { get; set; } + + /// Requests a render, as a snapshot tick does for the host pages. + public void Rerender() => StateHasChanged(); + + /// + protected override void OnInitialized() => Handle.Host = this; + + /// + protected override void BuildRenderTree(RenderTreeBuilder builder) + { + builder.OpenComponent(0); + builder.AddAttribute(1, nameof(NativeDialog.IsOpen), Open); + builder.AddAttribute(2, nameof(NativeDialog.LabelledBy), "title"); + + // A RenderFragment is not a change-detectable parameter, so the dialog re-renders with + // its host exactly as it does on the real pages. + builder.AddAttribute(3, nameof(NativeDialog.ChildContent), (RenderFragment)(content => { })); + builder.CloseComponent(); + } + } + + private sealed class RecordingJsRuntime : IJSRuntime + { + private readonly RecordingModule _module = new(); + + /// Gets the module-level calls made, in order. + public List ModuleCalls => _module.Calls; + + /// + public ValueTask InvokeAsync(string identifier, object?[]? args) => + new((TValue)(object)_module); + + /// + public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) => + InvokeAsync(identifier, args); + } + + private sealed class RecordingModule : IJSObjectReference + { + /// Gets the calls made, in order. + public List Calls { get; } = []; + + /// + public ValueTask InvokeAsync(string identifier, object?[]? args) + { + lock (Calls) + { + Calls.Add(identifier); + } + + return new(typeof(TValue) == typeof(bool) ? (TValue)(object)true : default!); + } + + /// + public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) => + InvokeAsync(identifier, args); + + /// + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs index acaff93c..a566dbfc 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmsHubPublisherTests.cs @@ -195,11 +195,55 @@ public sealed class AlarmsHubPublisherTests Assert.Equal("Tank02.Level.Lo", hubContext.Sent[1].ActiveAlarm.AlarmFullReference); } + private static AlarmsHubConnectionCounter ConnectedCounter() + { + AlarmsHubConnectionCounter counter = new(); + counter.Increment(); + return counter; + } + + /// + /// DSH-009: with no hub client connected the publisher holds no monitor subscription and sends + /// nothing; the first connection opens one (reset marker, then the primed frames) and the last + /// disconnect closes it again. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ExecuteAsync_WithNoConnectedClients_DoesNotSubscribeOrSend() + { + AlarmFeedMessage active = BuildActiveAlarm(); + ScriptedAlarmService alarmService = new([active]); + CapturingHubContext hubContext = new(); + AlarmsHubConnectionCounter counter = new(); + AlarmsHubPublisher publisher = CreatePublisher( + alarmService, hubContext, AlarmsHubPublisher.DefaultSendTimeout, showTagValues: false, counter); + + using CancellationTokenSource cts = new(); + await publisher.StartAsync(cts.Token).WaitAsync(TestTimeout); + + await Task.Delay(300); + Assert.Equal(0, alarmService.SubscriptionCount); + Assert.Empty(hubContext.Frames); + + counter.Increment(); + await WaitUntilAsync(() => hubContext.Sent.Count >= 1); + Assert.Equal(1, alarmService.SubscriptionCount); + Assert.Equal(AlarmsHub.ResetMessage, hubContext.Frames[0].Method); + + // The last client leaves: the subscription is closed and the loop idles again. + counter.Decrement(); + await WaitUntilAsync(() => alarmService.ActiveSubscriptions == 0); + + await cts.CancelAsync(); + await publisher.StopAsync(CancellationToken.None); + } + private static AlarmsHubPublisher CreatePublisher( IGatewayAlarmService alarmService, CapturingHubContext hubContext, TimeSpan sendTimeout, - bool showTagValues = true) + bool showTagValues = true, + AlarmsHubConnectionCounter? counter = null) { GatewayOptions gatewayOptions = new() { @@ -209,9 +253,11 @@ public sealed class AlarmsHubPublisherTests return new AlarmsHubPublisher( alarmService, hubContext, + counter ?? ConnectedCounter(), Options.Create(gatewayOptions), NullLogger.Instance, - sendTimeout); + sendTimeout, + TimeSpan.FromMilliseconds(20)); } /// @@ -337,6 +383,13 @@ public sealed class AlarmsHubPublisherTests private sealed class ScriptedAlarmService(params IReadOnlyList[] batches) : IGatewayAlarmService { private int _subscriptions; + private int _active; + + /// Gets how many times a subscription was opened. + public int SubscriptionCount => Volatile.Read(ref _subscriptions); + + /// Gets how many subscriptions are currently open. + public int ActiveSubscriptions => Volatile.Read(ref _active); /// public GatewayAlarmMonitorState State => GatewayAlarmMonitorState.Monitoring; @@ -359,29 +412,37 @@ public sealed class AlarmsHubPublisherTests [EnumeratorCancellation] CancellationToken cancellationToken) { int index = Interlocked.Increment(ref _subscriptions) - 1; - IReadOnlyList messages = batches[Math.Min(index, batches.Length - 1)]; - if (index >= batches.Length) - { - // Past the script: stay open and quiet rather than replaying the last batch. - messages = []; - } - - foreach (AlarmFeedMessage message in messages) - { - yield return message; - } - - if (index < batches.Length - 1) - { - yield break; - } - + Interlocked.Increment(ref _active); try { - await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + IReadOnlyList messages = batches[Math.Min(index, batches.Length - 1)]; + if (index >= batches.Length) + { + // Past the script: stay open and quiet rather than replaying the last batch. + messages = []; + } + + foreach (AlarmFeedMessage message in messages) + { + yield return message; + } + + if (index < batches.Length - 1) + { + yield break; + } + + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } } - catch (OperationCanceledException) + finally { + Interlocked.Decrement(ref _active); } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs index 23d016e1..014e7aac 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardSnapshotServiceTests.cs @@ -85,6 +85,54 @@ public sealed class DashboardSnapshotServiceTests Assert.Equal(1, health.CheckCount); } + /// + /// DSH-003: health checks run on their own cadence, off the snapshot tick. A slow check does not + /// slow the snapshots, and ticks inside the refresh interval do not re-run the checks. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task WatchSnapshotsAsync_WhenHealthCheckIsSlow_KeepsTickingAndEvaluatesOncePerInterval() + { + using GatewayMetrics metrics = new(); + StubHealthCheckService health = new(HealthStatus.Healthy); + FakeTimeProvider timeProvider = new(DateTimeOffset.Parse("2026-08-15T00:00:00Z", CultureInfo.InvariantCulture)); + DashboardSnapshotService service = CreateService( + new SessionRegistry(), + metrics, + new GatewayOptions { Dashboard = new DashboardOptions { SnapshotIntervalMilliseconds = 1000 } }, + timeProvider: timeProvider, + healthCheckService: health); + using CancellationTokenSource cancellation = new(TimeSpan.FromSeconds(30)); + await using IAsyncEnumerator enumerator = service + .WatchSnapshotsAsync(cancellation.Token) + .GetAsyncEnumerator(cancellation.Token); + + Assert.True(await enumerator.MoveNextAsync()); + Assert.Equal(1, health.CheckCount); + + // Ticks inside the refresh interval reuse the cached status. + await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(1)); + await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(1)); + Assert.Equal(1, health.CheckCount); + + // Past the interval the next evaluation is slow; the tick still yields, with the cached value. + health.Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + DashboardSnapshot during = await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(20)); + Assert.Equal(HealthStatus.Healthy.ToString(), during.GatewayStatus); + DashboardSnapshot stillTicking = await NextSnapshotAsync(enumerator, timeProvider, TimeSpan.FromSeconds(1)); + Assert.Equal(HealthStatus.Healthy.ToString(), stillTicking.GatewayStatus); + + // The evaluation starts on a background task, so it can land just after the tick yields. + for (int i = 0; i < 500 && health.CheckCount < 2; i++) + { + await Task.Delay(10); + } + + Assert.Equal(2, health.CheckCount); + + health.Gate.SetResult(); + } + /// A health evaluation that throws is reported as Unknown, never as Healthy. /// A task that represents the asynchronous operation. [Fact] @@ -756,11 +804,14 @@ public sealed class DashboardSnapshotServiceTests /// Gets or sets a value indicating whether the evaluation throws. public bool Throw { get; set; } + /// Gets or sets a gate the evaluation awaits before reporting, to model a slow check. + public TaskCompletionSource? Gate { get; set; } + /// Gets the number of evaluations requested. public int CheckCount => Volatile.Read(ref _checkCount); /// - public override Task CheckHealthAsync( + public override async Task CheckHealthAsync( Func? predicate, CancellationToken cancellationToken = default) { @@ -770,7 +821,12 @@ public sealed class DashboardSnapshotServiceTests throw new InvalidOperationException("health evaluation failed"); } - return Task.FromResult(new HealthReport( + if (Gate is { } gate) + { + await gate.Task.WaitAsync(cancellationToken); + } + + return (new HealthReport( new Dictionary { ["stub"] = new(status, null, TimeSpan.Zero, null, null), diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/SessionDetailsPageEventAclTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/SessionDetailsPageEventAclTests.cs index 1bb16b5c..c8bee4c7 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/SessionDetailsPageEventAclTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/SessionDetailsPageEventAclTests.cs @@ -134,6 +134,56 @@ public sealed class SessionDetailsPageEventAclTests Assert.Empty(subscriber.UndisposedAfterReplacement); } + /// + /// DSH-004: a session emitting hundreds of events a second renders a bounded number of times, + /// and the retained rows are the newest ones. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Page_WhenEventsArriveInABurst_CoalescesRendersAndKeepsNewestRows() + { + RecordingEventSubscriber subscriber = new(); + ServiceCollection services = BuildServices(subscriber, allow: true); + await using ServiceProvider provider = services.BuildServiceProvider(); + await using ParameterDrivingRenderer renderer = new(provider, provider.GetRequiredService()); + + SessionDetailsPage page = await renderer.MountAsync(); + await renderer.SetParametersAsync(page, SessionId).WaitAsync(TestTimeout); + int baseline = renderer.RenderBatches; + + // ~1.2 s of traffic at roughly 800 events/s. + const int total = 1000; + for (int sequence = 1; sequence <= total; sequence++) + { + subscriber.Latest.Write(new MxEvent { WorkerSequence = (ulong)sequence }); + if (sequence % 4 == 0) + { + await Task.Delay(1); + } + } + + // Let the pump drain what the last interval left queued. + await Task.Delay(SessionDetailsPage.EventRenderInterval * 3); + + int renders = renderer.RenderBatches - baseline; + Assert.Empty(renderer.Exceptions); + Assert.InRange(renders, 1, 20); + + System.Reflection.FieldInfo rows = typeof(SessionDetailsPage).GetField( + "_recentEvents", + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!; + System.Collections.IEnumerable recent = (System.Collections.IEnumerable)rows.GetValue(page)!; + int count = 0; + foreach (object row in recent) + { + MxEvent evt = (MxEvent)row.GetType().GetProperty("Event")!.GetValue(row)!; + Assert.Equal((ulong)(total - count), evt.WorkerSequence); + count++; + } + + Assert.Equal(50, count); + } + private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(30); private static ServiceCollection BuildServices( @@ -192,6 +242,9 @@ public sealed class SessionDetailsPageEventAclTests public IReadOnlyList UndisposedAfterReplacement => [.. _handedOut.SkipLast(1).Where(subscription => !subscription.IsDisposed)]; + /// Gets the most recently handed-out subscription. + internal IdleSubscription Latest => _handedOut[^1]; + /// public IDashboardEventSubscription Subscribe(string sessionId) { @@ -214,6 +267,10 @@ public sealed class SessionDetailsPageEventAclTests /// public ChannelReader Reader => _channel.Reader; + /// Queues an event for the page's pump to read. + /// The event to queue. + public void Write(MxEvent mxEvent) => _channel.Writer.TryWrite(mxEvent); + /// Marks the subscription as released and completes its channel. public void Dispose() { @@ -271,6 +328,11 @@ public sealed class SessionDetailsPageEventAclTests /// Gets exceptions the renderer surfaced, so a test never passes over a swallowed fault. public List Exceptions { get; } = []; + /// Gets the number of render batches the renderer produced. + public int RenderBatches => Volatile.Read(ref _renderBatches); + + private int _renderBatches; + /// public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault(); @@ -306,7 +368,11 @@ public sealed class SessionDetailsPageEventAclTests protected override void HandleException(Exception exception) => Exceptions.Add(exception); /// - protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask; + protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) + { + Interlocked.Increment(ref _renderBatches); + return Task.CompletedTask; + } } #pragma warning restore BL0006 diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs index 6380cc9a..2ff76489 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/GatewayEndToEndReconnectReplayTests.cs @@ -234,6 +234,41 @@ public sealed class GatewayEndToEndReconnectReplayTests(ITestOutputHelper output Assert.Equal(expectedTail, tail.Select(e => e.WorkerSequence).ToArray()); } + /// + /// SES-006, end to end: a resume cursor ahead of every event the session has produced is + /// rejected with InvalidArgument rather than attaching a stream that silently drops + /// every live event until the session catches up. The rejected attach leaves the session + /// usable: a fresh stream still attaches. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task StreamEvents_ResumeCursorAheadOfStream_IsRejectedWithInvalidArgument() + { + GatedEventFakeWorkerProcessLauncher launcher = new(); + await using ReconnectReplayGatewayServiceFixture fixture = new(launcher, replayBufferCapacity: 16, diagnosticOutput: output.WriteLine); + string sessionId = await OpenSessionAsync(fixture, "reconnect-bogus-cursor"); + + RpcException rejected = await Assert.ThrowsAsync(async () => + await fixture.Service.StreamEvents( + new StreamEventsRequest { SessionId = sessionId, AfterWorkerSequence = 50_000 }, + new RecordingServerStreamWriter(), + new TestServerCallContext())); + Assert.Equal(StatusCode.InvalidArgument, rejected.StatusCode); + + // The failed attach rolled back its subscriber slot: a fresh stream attaches. + using CancellationTokenSource writerCts = new(); + Task streamTask = Task.Run(async () => + await fixture.Service.StreamEvents( + new StreamEventsRequest { SessionId = sessionId }, + new RecordingServerStreamWriter(), + new TestServerCallContext(cancellationToken: writerCts.Token))); + await fixture.WaitForSubscriberCountAsync(sessionId, n: 1, TestTimeout); + + launcher.StopEmitting(); + await DetachAsync(writerCts, streamTask); + await CloseAndDrainAsync(fixture, sessionId, Task.CompletedTask, launcher); + } + /// /// Regression, end to end: when age eviction has emptied the replay ring, the /// ReplayGap sentinel carries the next deliverable sequence (highest observed + 1), diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs index 8236226c..5a863611 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewayArrayWriteWiringTests.cs @@ -144,6 +144,53 @@ public sealed class GatewayArrayWriteWiringTests Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values); } + /// + /// SES-008: a sparse write to a session that cannot take commands fails on readiness before the + /// sparse value is expanded, so a not-ready session never pays for the whole-array allocation. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Write_SparseArrayValue_ToNotReadySession_FailsWithoutExpanding() + { + GatewaySession session = new( + sessionId: "session-not-ready", + backendName: "mxaccess", + pipeName: "mxaccess-gateway-1-session-not-ready", + nonce: "nonce", + clientIdentity: "client-1", + ownerKeyId: null, + clientSessionName: "test-session", + clientCorrelationId: "client-correlation-1", + commandTimeout: TimeSpan.FromSeconds(5), + startupTimeout: TimeSpan.FromSeconds(5), + shutdownTimeout: TimeSpan.FromSeconds(5), + leaseDuration: TimeSpan.FromMinutes(30), + openedAt: DateTimeOffset.UtcNow, + addressNormalizer: CreateNormalizer()); + MxValue value = new() + { + SparseArrayValue = new MxSparseArray + { + ElementDataType = MxDataType.Time, + TotalLength = 1_000_000, + }, + }; + WorkerCommand command = new() + { + Command = new MxCommand + { + Kind = MxCommandKind.Write, + Write = new WriteCommand { ServerHandle = 1, ItemHandle = 42, Value = value }, + }, + }; + + SessionManagerException exception = await Assert.ThrowsAsync( + () => session.InvokeAsync(command, CancellationToken.None)); + + Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode); + Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, value.KindCase); + } + /// /// A bare array AddItem2 address is normalized to its writable array form on the wire, /// and the normalized address lands in the tracked . diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs index 4f828c2a..f0b52a89 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionEventDistributorTests.cs @@ -881,6 +881,55 @@ public sealed class SessionEventDistributorTests Assert.Equal(5ul, liveResume); } + /// + /// SES-006: a resume cursor ahead of every event the session has produced is rejected at + /// attach time instead of silently dropping live events until the session catches up. The + /// rejection registers nothing, and a cursor equal to the newest sequence is still accepted. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RegisterWithReplay_CursorAheadOfStream_IsRejectedAndRegistersNothing() + { + Channel source = Channel.CreateUnbounded(); + await using SessionEventDistributor distributor = CreateDistributor( + source.Reader, + replayBufferCapacity: 10, + replayRetentionSeconds: 0); + await distributor.StartAsync(CancellationToken.None); + + using IEventSubscriberLease primer = distributor.Register(); + for (ulong sequence = 1; sequence <= 10; sequence++) + { + source.Writer.TryWrite(Event(sequence)); + _ = await ReadOneAsync(primer.Reader); + } + + SessionManagerException exception = Assert.Throws(() => distributor.RegisterWithReplay( + 1000, + out _, + out _, + out _, + out _)); + Assert.Equal(SessionManagerErrorCode.InvalidResumeCursor, exception.ErrorCode); + Assert.Throws(() => distributor.RegisterWithReplay( + ulong.MaxValue, + out _, + out _, + out _, + out _)); + + // The newest sequence itself is a valid, fully-caught-up cursor. + using IEventSubscriberLease caughtUp = distributor.RegisterWithReplay( + 10, + out IReadOnlyList replay, + out bool gap, + out _, + out ulong liveResume); + Assert.Empty(replay); + Assert.False(gap); + Assert.Equal(10ul, liveResume); + } + /// When nothing retained is newer than the requested sequence, the live resume watermark equals the requested sequence and no gap is reported. /// A task that represents the asynchronous operation. [Fact] diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs index 8a658c4d..1f92e3e6 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SparseArrayExpanderTests.cs @@ -143,6 +143,24 @@ public sealed class SparseArrayExpanderTests Assert.Equal(5, value.ArrayValue.TimestampValues.Values[1].Seconds); } + /// SES-008: unspecified Time slots share one default instance instead of allocating one each. + [Fact] + public void Expand_Time_UnspecifiedSlotsShareOneDefaultInstance() + { + MxValue value = SparseValue( + MxDataType.Time, + 100_000, + (3, new MxValue { TimestampValue = new Timestamp { Seconds = 9 } })); + + SparseArrayExpander.Expand(value); + + IList slots = value.ArrayValue.TimestampValues.Values; + Assert.Equal(100_000, slots.Count); + Assert.Equal(9, slots[3].Seconds); + Assert.Same(slots[0], slots[99_999]); + Assert.Equal(0, slots[0].Seconds); + } + /// Verifies that expanding a Double sparse array fills defaults and applies the given element. [Fact] public void Expand_Double_HappyPath() diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs index 08b9a864..5fc6102b 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs @@ -162,6 +162,83 @@ public sealed class WorkerClientTests Assert.Equal(WorkerClientState.Ready, client.State); } + /// + /// WRK-007: a command rejected before it reaches the worker (here CommandTooLarge) is counted + /// as started and as failed, so commands.started does not climb without a terminal counter. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InvokeAsync_WhenCommandExceedsFrameMax_RecordsOneFailedCommand() + { + await using PipePair pipePair = await PipePair.CreateAsync(); + using GatewayMetrics metrics = new(); + await using WorkerClient client = CreateClient(pipePair, metrics: metrics, maxMessageBytes: 4096); + await CompleteHandshakeAsync(client, pipePair); + + WorkerCommand oversized = new() + { + Command = new MxCommand + { + Kind = MxCommandKind.Write, + Write = new WriteCommand + { + ServerHandle = 1, + ItemHandle = 2, + Value = new MxValue { StringValue = new string('x', 8192) }, + }, + }, + }; + + await Assert.ThrowsAsync( + async () => await client.InvokeAsync(oversized, TestTimeout, CancellationToken.None)); + + GatewayMetricsSnapshot snapshot = metrics.GetSnapshot(); + Assert.Equal(1, snapshot.CommandsStarted); + Assert.Equal(1, snapshot.CommandsFailed); + Assert.Equal(0, snapshot.CommandsSucceeded); + } + + /// + /// WRK-010: the write loop sizes a command frame from the pre-check's measurement plus the exact + /// sequence-stamp bytes, and the frame on the wire still parses to the stamped envelope. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InvokeAsync_LargeCommand_FramesCorrectlyAfterSequenceStamp() + { + await using PipePair pipePair = await PipePair.CreateAsync(); + await using WorkerClient client = CreateClient(pipePair); + await CompleteHandshakeAsync(client, pipePair); + + string payload = new('y', 70_000); + for (int attempt = 0; attempt < 3; attempt++) + { + Task invoke = client.InvokeAsync( + new WorkerCommand + { + Command = new MxCommand + { + Kind = MxCommandKind.Write, + Write = new WriteCommand + { + ServerHandle = 1, + ItemHandle = 2, + Value = new MxValue { StringValue = payload }, + }, + }, + }, + TestTimeout, + CancellationToken.None); + + WorkerEnvelope onWire = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + Assert.Equal(payload, onWire.WorkerCommand.Command.Write.Value.StringValue); + Assert.True(onWire.Sequence > 0); + + await pipePair.WriteAsync(CreateCommandReplyEnvelope(onWire.CorrelationId, MxCommandKind.Write)); + await invoke.WaitAsync(TestTimeout); + } + } + /// Verifies that InvokeAsync ignores late replies and keeps the client ready. /// A task that represents the asynchronous operation. [Fact] diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs index ea92ded0..c8da5a59 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerFrameProtocolTests.cs @@ -29,6 +29,34 @@ public sealed class WorkerFrameProtocolTests Assert.Equal(original, parsed); } + /// + /// WRK-010: writing with a size measured before the sequence stamp produces byte-identical frames + /// to the writer's own measurement, across sequence values whose varints differ in length. + /// + /// The sequence stamped after the pre-stamp size was measured. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(1UL)] + [InlineData(127UL)] + [InlineData(128UL)] + [InlineData(16384UL)] + [InlineData(ulong.MaxValue)] + public async Task WriteAsync_WithSizeMeasuredBeforeTheSequenceStamp_MatchesTheWritersOwnFrame(ulong sequence) + { + WorkerFrameProtocolOptions options = new(SessionId); + WorkerEnvelope envelope = CreateEnvelope(); + envelope.Sequence = 0; + int sizeBeforeSequence = envelope.CalculateSize(); + envelope.Sequence = sequence; + + await using MemoryStream known = new(); + await new WorkerFrameWriter(known, options).WriteAsync(envelope, sizeBeforeSequence); + await using MemoryStream measured = new(); + await new WorkerFrameWriter(measured, options).WriteAsync(envelope); + + Assert.Equal(measured.ToArray(), known.ToArray()); + } + /// Verifies that a large payload near the message cap round-trips through the pooled write/read path. /// A task that represents the asynchronous operation. [Fact] diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs index 9f40f2ab..95ed6f13 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/ChannelAuditWriterTests.cs @@ -6,6 +6,7 @@ using ZB.MOM.WW.Auth.ApiKeys.Sqlite; using ZB.MOM.WW.MxGateway.Server.Configuration; using ZB.MOM.WW.MxGateway.Server.Security.Audit; using ZB.MOM.WW.MxGateway.Tests.Security.Authentication; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; namespace ZB.MOM.WW.MxGateway.Tests.Security.Audit; @@ -160,7 +161,8 @@ public sealed class ChannelAuditWriterTests : IDisposable /// /// The retention sweep deletes rows older than AuditRetentionDays, measured from the - /// injected clock, and runs once at startup after the one-time table bootstrap. + /// injected clock. The table bootstrap completes in StartAsync; the first sweep runs from + /// the background loop so a large audit table cannot delay host startup (SEC-014). /// /// A task that represents the asynchronous operation. [Fact] @@ -174,12 +176,67 @@ public sealed class ChannelAuditWriterTests : IDisposable clock); await drain.StartAsync(CancellationToken.None); + await Eventually.WaitUntilAsync(() => sink.DeleteCutoffs.Count >= 1, TimeSpan.FromSeconds(10)); await drain.StopAsync(CancellationToken.None); Assert.Equal(1, sink.EnsureInitializedCalls); Assert.Equal(new DateTimeOffset(2026, 7, 16, 12, 0, 0, TimeSpan.Zero), Assert.Single(sink.DeleteCutoffs)); } + /// SEC-014: a sweep that blocks (a big table) must not hold up StartAsync. + /// A task that represents the asynchronous operation. + [Fact] + public async Task StartAsync_WhenTheSweepBlocks_StillCompletes() + { + CountingAuditSink sink = new() { BlockDelete = new TaskCompletionSource() }; + (_, AuditDrainService drain) = CreateWriterAndDrain(sink); + + await drain.StartAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(10)); + + sink.BlockDelete.SetResult(); + await drain.StopAsync(CancellationToken.None); + } + + /// + /// SEC-014: the sweep seeks an index on the instant it compares rather than scanning the table, + /// and removes a backlog larger than one chunk. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task SqliteStore_DeleteOlderThan_UsesTheRetentionIndexAndSweepsMoreThanOneChunk() + { + (SqliteCanonicalAuditStore store, AuthSqliteConnectionFactory factory) = CreateStore(); + DateTimeOffset old = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + List backlog = []; + for (int index = 0; index < 5200; index++) + { + backlog.Add(MakeEvent("old", old)); + } + + await store.InsertBatchAsync(backlog, CancellationToken.None); + await store.InsertAsync(MakeEvent("fresh", new DateTimeOffset(2026, 6, 1, 0, 0, 0, TimeSpan.Zero)), CancellationToken.None); + + int deleted = await store.DeleteOlderThanAsync(new DateTimeOffset(2026, 3, 1, 0, 0, 0, TimeSpan.Zero), CancellationToken.None); + + Assert.Equal(5200, deleted); + Assert.Equal(["fresh"], await ListActionsAsync(factory)); + + await using SqliteConnection connection = await factory.OpenConnectionAsync(CancellationToken.None); + await using SqliteCommand plan = connection.CreateCommand(); + plan.CommandText = + "EXPLAIN QUERY PLAN SELECT rowid FROM audit_event WHERE datetime(occurred_at_utc) < datetime('2026-03-01T00:00:00.0000000+00:00') LIMIT 5000;"; + List details = []; + await using (SqliteDataReader reader = await plan.ExecuteReaderAsync(CancellationToken.None)) + { + while (await reader.ReadAsync(CancellationToken.None)) + { + details.Add(reader.GetString(3)); + } + } + + Assert.Contains(details, detail => detail.Contains("ix_audit_event_occurred_instant", StringComparison.Ordinal)); + } + /// /// The sweep compares instants, not stored text, and never deletes a row it cannot date. /// @@ -357,6 +414,9 @@ public sealed class ChannelAuditWriterTests : IDisposable /// Gets the number of accepted calls. public int InsertBatchCalls => BatchSizes.Count; + /// Gets or sets a gate the sweep waits on, to model a long-running delete. + public TaskCompletionSource? BlockDelete { get; set; } + /// Gets the number of calls. public int EnsureInitializedCalls { get; private set; } @@ -395,14 +455,19 @@ public sealed class ChannelAuditWriterTests : IDisposable } /// - public Task DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken) + public async Task DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken) { lock (_gate) { DeleteCutoffs.Add(cutoffUtc); } - return Task.FromResult(0); + if (BlockDelete is { } gate) + { + await gate.Task.WaitAsync(cancellationToken); + } + + return 0; } } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs index d0d9d513..ac8ec8e2 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authentication/CachingApiKeyVerifierTests.cs @@ -37,6 +37,39 @@ public sealed class CachingApiKeyVerifierTests Assert.Equal(1, inner.CallCount); } + /// + /// SEC-012: the cache key is hashed from a stack buffer for tokens up to 512 bytes and from a rented + /// buffer above that; both paths must key distinct tokens distinctly and the same token identically. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task VerifyAsync_LongAndShortTokens_AreCachedAndNotAliased() + { + FakeVerifier inner = new(Success("operator01")); + using MemoryCache cache = NewCache(); + CachingApiKeyVerifier verifier = new(inner, cache, TimeSpan.FromSeconds(15)); + string longA = "Bearer mxgw_operator01_" + new string('a', 2000); + string longB = "Bearer mxgw_operator01_" + new string('a', 1999) + "b"; + + await verifier.VerifyAsync(longA, CancellationToken.None); + await verifier.VerifyAsync(longA, CancellationToken.None); + Assert.Equal(1, inner.CallCount); + + await verifier.VerifyAsync(longB, CancellationToken.None); + Assert.Equal(2, inner.CallCount); + } + + /// SEC-012: one mapped gateway identity per cached library identity, not one per RPC. + [Fact] + public void ToGatewayIdentity_SameLibraryIdentity_ReturnsTheSameMappedInstance() + { + LibApiKeyIdentity library = Success("operator01").Identity!; + + Assert.Same( + GatewayApiKeyIdentityMapper.ToGatewayIdentity(library), + GatewayApiKeyIdentityMapper.ToGatewayIdentity(library)); + } + /// Different presented secrets are cached under distinct keys (no cross-secret aliasing). /// A task that represents the asynchronous operation. [Fact] diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmAckWriterTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmAckWriterTests.cs index 8c7a14a9..0a550af5 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmAckWriterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmAckWriterTests.cs @@ -388,6 +388,25 @@ public sealed class AlarmAckWriterTests Assert.Equal(1UL, cache.CurrentVersion(8, 100)); } + [Fact] + public void Dispose_UnregistersOnceWithoutPerItemTeardown() + { + RecordingAckServer server = new RecordingAckServer { AuthenticateResult = 5 }; + MxAccessWriteCompletionCache cache = new MxAccessWriteCompletionCache(); + server.OnWrite = (handle, item) => cache.Record(handle, item, Rows(MxStatusCategory.Ok, 0)); + AlarmAckWriter writer = new AlarmAckWriter(server, cache, () => { }, TimeSpan.FromSeconds(1), "MxGateway"); + writer.Acknowledge("A.X.AckMsg", "1", Alice()); + writer.Acknowledge("B.X.AckMsg", "2", Alice()); + int unAdviseBefore = server.Operations.Count(op => op == "UnAdvise"); + + writer.Dispose(); + + // MXA-010: Unregister drops every cached ack item in one call. + Assert.Equal(1, server.Operations.Count(op => op == "Unregister")); + Assert.Equal(unAdviseBefore, server.Operations.Count(op => op == "UnAdvise")); + Assert.Empty(server.RemovedItemHandles); + } + [Fact] public void Acknowledge_WhenWriteDisconnected_ForgetsServerCompletions() { diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs index 1ce78605..a72645f7 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/AlarmCommandExecutorTests.cs @@ -585,6 +585,9 @@ public sealed class AlarmCommandExecutorTests private sealed class FakeAlarmHandler : IAlarmCommandHandler { + /// + public bool IsSubscribed => LastSubscription is not null && !UnsubscribeCalled; + /// Gets the last subscription expression. public string? LastSubscription { get; private set; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs index 61ad581f..b550b104 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/LmxSubtagAlarmSourceTests.cs @@ -116,26 +116,22 @@ public sealed class LmxSubtagAlarmSourceTests } /// - /// Verifies UnAdvises and - /// removes every advised handle and unregisters the server exactly once. + /// Verifies unregisters the server exactly once and + /// makes no per-item UnAdvise/RemoveItem calls: Unregister already drops every item under + /// the handle (MXA-010). /// [Fact] - public void Dispose_UnAdvisesAndRemovesAdvisedHandles_AndUnregistersOnce() + public void Dispose_UnregistersOnceWithoutPerItemTeardown() { var server = new RecordingMxAccessServer(); var source = new LmxSubtagAlarmSource(server, FakeServerHandle); source.Advise(new[] { "Tank1.Alarm.Subtag", "Tank2.Alarm.Subtag" }); - int advised1 = server.LastItemHandleFor("Tank1.Alarm.Subtag"); - int advised2 = server.LastItemHandleFor("Tank2.Alarm.Subtag"); - source.Dispose(); - Assert.Equal(new[] { advised1, advised2 }, server.UnAdvisedItemHandles); - Assert.Equal( - new[] { advised1, advised2 }.OrderBy(h => h), - server.RemovedItemHandles.OrderBy(h => h)); + Assert.Empty(server.UnAdvisedItemHandles); + Assert.Empty(server.RemovedItemHandles); Assert.Equal(1, server.UnregisterCount); Assert.Empty(server.Writes); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs index 3b79cb3b..f0f8c265 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs @@ -357,7 +357,7 @@ public sealed class MxAccessStaSessionTests [Fact] public async Task StartAsync_WithAlarmCommandHandlerFactory_PollOnceCalledViaSta() { - FakeAlarmCommandHandler handler = new(); + FakeAlarmCommandHandler handler = new() { IsSubscribed = true }; FakeMxAccessComObjectFactory factory = new(); FakeMxAccessEventSink eventSink = new(); using StaRuntime runtime = CreateRuntime(); @@ -383,6 +383,39 @@ public sealed class MxAccessStaSessionTests Assert.Equal(runtime.StaThreadId, handler.LastPollThreadId); } + /// + /// MXA-011: while nothing is subscribed the poll loop does not hop onto the STA at all, so an + /// idle worker takes no STA wake-ups at the poll rate; once subscribed, polling starts. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAlarmPollLoop_WhileNotSubscribed_DoesNotPollThenPollsOnceSubscribed() + { + FakeAlarmCommandHandler handler = new(); + using StaRuntime runtime = CreateRuntime(); + using MxAccessStaSession session = new( + runtime, + new FakeMxAccessComObjectFactory(), + new FakeMxAccessEventSink(), + new MxAccessEventQueue(), + (_eq, _affinity, _comFactory) => handler); + session.AlarmPollInterval = TimeSpan.FromMilliseconds(10); + + await session.StartAsync("session-1", workerProcessId: 1); + + await Task.Delay(300); + Assert.Equal(0, handler.PollCount); + + handler.IsSubscribed = true; + using CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + while (handler.PollCount == 0 && !timeout.IsCancellationRequested) + { + await Task.Delay(20, CancellationToken.None); + } + + Assert.True(handler.PollCount > 0, "Polling should start once the handler is subscribed."); + } + /// /// Gap 2: Verifies that the STA poll loop stops when the session is disposed — /// no further PollOnce calls after disposal. @@ -395,7 +428,7 @@ public sealed class MxAccessStaSessionTests [Fact] public async Task Dispose_StopsAlarmPollLoop() { - FakeAlarmCommandHandler handler = new(); + FakeAlarmCommandHandler handler = new() { IsSubscribed = true }; FakeMxAccessComObjectFactory factory = new(); FakeMxAccessEventSink eventSink = new(); using StaRuntime runtime = CreateRuntime(); @@ -446,6 +479,7 @@ public sealed class MxAccessStaSessionTests { FakeAlarmCommandHandler handler = new() { + IsSubscribed = true, PollException = new System.Runtime.InteropServices.COMException( "GetXmlCurrentAlarms2 failed.", unchecked((int)0x80004005)), }; @@ -494,6 +528,7 @@ public sealed class MxAccessStaSessionTests { FakeAlarmCommandHandler handler = new() { + IsSubscribed = true, PollException = new InvalidOperationException( "Alarm consumer accessed off its owning STA thread."), }; @@ -538,7 +573,7 @@ public sealed class MxAccessStaSessionTests [Fact] public async Task CaptureHeartbeat_DuringAlarmPoll_ReportsStaCallInProgress() { - FakeAlarmCommandHandler handler = new() { BlockPoll = true }; + FakeAlarmCommandHandler handler = new() { BlockPoll = true, IsSubscribed = true }; FakeMxAccessComObjectFactory factory = new(); FakeMxAccessEventSink eventSink = new(); using StaRuntime runtime = CreateRuntime(); @@ -629,6 +664,7 @@ public sealed class MxAccessStaSessionTests { FakeAlarmCommandHandler handler = new() { + IsSubscribed = true, PollExceptionFactory = call => call % 3 == 0 ? null : new COMException("secret-tag-name GetXmlCurrentAlarms2 failed.", unchecked((int)0x80004005)), @@ -676,6 +712,7 @@ public sealed class MxAccessStaSessionTests { FakeAlarmCommandHandler handler = new() { + IsSubscribed = true, PollException = new COMException("GetXmlCurrentAlarms2 failed.", unchecked((int)0x80004005)), }; ConcurrentQueue warnings = new(); @@ -760,7 +797,7 @@ public sealed class MxAccessStaSessionTests public async Task RunAlarmPollLoop_AfterStaLoopFault_DoesNotRecordAlarmPollFault() { ControllableMessagePump pump = new(); - FakeAlarmCommandHandler handler = new(); + FakeAlarmCommandHandler handler = new() { IsSubscribed = true }; using StaRuntime runtime = new(new NoopComApartmentInitializer(), pump, TimeSpan.FromMilliseconds(25)); MxAccessEventQueue eventQueue = new(); using MxAccessStaSession session = new( @@ -831,7 +868,13 @@ public sealed class MxAccessStaSessionTests private int? lastPollThreadId; /// Gets a value indicating whether the alarm client is currently subscribed. - public bool IsSubscribed { get; private set; } + public bool IsSubscribed + { + get => Volatile.Read(ref subscribed) != 0; + set => Volatile.Write(ref subscribed, value ? 1 : 0); + } + + private int subscribed; /// Gets the last alarm subscription name. public string? LastSubscription { get; private set; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessValueCacheTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessValueCacheTests.cs index 2af99724..3e883a0b 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessValueCacheTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessValueCacheTests.cs @@ -264,6 +264,66 @@ public sealed class MxAccessValueCacheTests Assert.True(pumpCalls >= 3, $"Expected repeated pumping across the 400 ms wait, saw {pumpCalls} calls."); } + /// + /// MXA-009: with the default fallback tick a wait that nothing wakes pumps about once per 50 ms + /// (not once per 5 ms), so a 200 ms timeout costs a handful of pump steps. + /// + [Fact] + public void TryWaitForUpdate_WithDefaultInterval_PumpsAtTheFiftyMillisecondFallbackTick() + { + MxAccessValueCache cache = new(); + int pumpCalls = 0; + + bool found = cache.TryWaitForUpdate( + serverHandle: 7, + itemHandle: 21, + sinceVersion: 0, + deadlineUtc: DateTime.UtcNow.AddMilliseconds(200), + pumpStep: () => Interlocked.Increment(ref pumpCalls), + out _); + + Assert.False(found); + Assert.InRange(pumpCalls, 2, 12); + } + + /// + /// MXA-009: the bulk wait keeps only still-pending handles in its working set, and reports each + /// handle that updates (including ones that arrive in different wakes) exactly once. + /// + [Fact] + public void TryWaitForUpdates_ReportsEachHandleAsItArrivesAcrossWakes() + { + MxAccessValueCache cache = new(); + int[] handles = { 21, 22, 23 }; + ulong[] baselines = { 0UL, 0UL, 0UL }; + bool[] received = new bool[3]; + MxAccessValueCache.CachedValue[] values = new MxAccessValueCache.CachedValue[3]; + int pumpCalls = 0; + + int count = cache.TryWaitForUpdates( + serverHandle: 7, + handles, + baselines, + deadlineUtc: DateTime.UtcNow.AddMilliseconds(300), + pumpStep: () => + { + pumpCalls++; + if (pumpCalls == 2) + { + cache.Set(7, 22, BuildEvent(7, 22, 5, 192, Timestamp.FromDateTime(DateTime.UtcNow))); + } + else if (pumpCalls == 3) + { + cache.Set(7, 21, BuildEvent(7, 21, 6, 192, Timestamp.FromDateTime(DateTime.UtcNow))); + } + }, + received, + values); + + Assert.Equal(2, count); + Assert.Equal(new[] { true, true, false }, received); + } + private static MxEvent BuildEvent( int serverHandle, int itemHandle, diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlTests.cs index 555cc9ae..77ec3b32 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlTests.cs @@ -724,6 +724,31 @@ public sealed class WnWrapAlarmConsumerXmlTests // out of one call, produced under one lock acquisition. // ------------------------------------------------------------------------- + /// + /// MXA-008: an alarm document identical to the previous poll's is not parsed or diffed again and + /// emits nothing; a changed document is parsed and diffed as before. + /// + [Fact] + public void ProcessFetchedXml_WhenTheDocumentIsUnchanged_SkipsTheParseAndEmitsNothing() + { + using WnWrapAlarmConsumer consumer = new WnWrapAlarmConsumer(1024); + string xml = BuildAlarmXml(3); + + IReadOnlyList first = consumer.ProcessFetchedXml(xml); + IReadOnlyList second = consumer.ProcessFetchedXml(new string(xml.ToCharArray())); + + Assert.NotEmpty(first); + Assert.Empty(second); + Assert.Equal(1, consumer.XmlParseCount); + Assert.Equal(3, consumer.SnapshotActiveAlarms(out bool truncated).Count); + Assert.False(truncated); + + IReadOnlyList changed = consumer.ProcessFetchedXml(BuildAlarmXml(4)); + Assert.Equal(2, consumer.XmlParseCount); + Assert.NotEmpty(changed); + Assert.Equal(4, consumer.SnapshotActiveAlarms(out _).Count); + } + /// /// A capped fetch sets the truncation verdict handed out with the /// snapshot. Without this the signal never leaves the consumer and the diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs index 7f4ad4ba..71c24c04 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs @@ -320,6 +320,53 @@ public sealed class StaCommandDispatcherTests value => value?.ToString()?.Contains("provider detail") == true); } + /// + /// WIP-010: a command-log write that blocks (a slow or full stderr sink) must not hold the + /// dispatcher gate, so DispatchAsync, PendingCommandCount and + /// CancelQueuedCommand still return while it is stuck. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DispatchAsync_WhenCommandLoggerBlocks_DoesNotHoldTheGate() + { + using StaRuntime runtime = CreateRuntime(); + runtime.Start(); + using ManualResetEventSlim release = new(false); + using ManualResetEventSlim entered = new(false); + BlockingWorkerLogger logger = new(entered, release); + StaCommandDispatcher dispatcher = new(runtime, new RecordingCommandExecutor()) + { + CommandLogger = logger, + }; + + try + { + // Task.Factory.StartNew (not Task.Run) so the returned reply task is not unwrapped: the + // dispatch call itself must return promptly even though the reply cannot complete yet. + Task first = await WithTimeoutAsync( + Task.Factory.StartNew(() => dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Register)))); + Assert.True(entered.Wait(TimeSpan.FromSeconds(10)), "The command logger was never called."); + + // The first command's log line is now blocked. Everything that takes the gate must still return. + Task second = await WithTimeoutAsync( + Task.Factory.StartNew(() => dispatcher.DispatchAsync(CreateCommand("correlation-2", MxCommandKind.AddItem)))); + bool canceled = await WithTimeoutAsync( + Task.Run(() => dispatcher.CancelQueuedCommand("correlation-2"))); + int pending = await WithTimeoutAsync( + Task.Run(() => dispatcher.PendingCommandCount)); + + Assert.True(canceled); + Assert.Equal(0, pending); + Assert.Equal(ProtocolStatusCode.Canceled, (await second).ProtocolStatus.Code); + } + finally + { + release.Set(); + } + + Assert.Equal(ProtocolStatusCode.Ok, (await dispatcher.DispatchAsync(CreateCommand("correlation-3", MxCommandKind.Register))).ProtocolStatus.Code); + } + /// Verifies the opt-in environment value is parsed strictly. /// Raw environment value. /// Whether logging should be enabled. @@ -367,6 +414,40 @@ public sealed class StaCommandDispatcherTests /// /// Test executor that records executed command correlations and thread IDs. /// + // net48 has no Task.WaitAsync; a task that does not finish in time fails the test instead of hanging it. + private static async Task WithTimeoutAsync(Task task) + { + Task finished = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(10))); + if (!ReferenceEquals(finished, task)) + { + throw new TimeoutException("The operation did not complete while the command logger was blocked."); + } + + return await task; + } + + private sealed class BlockingWorkerLogger : IWorkerLogger + { + private readonly ManualResetEventSlim entered; + private readonly ManualResetEventSlim release; + + public BlockingWorkerLogger(ManualResetEventSlim entered, ManualResetEventSlim release) + { + this.entered = entered; + this.release = release; + } + + public void Information(string eventName, IReadOnlyDictionary fields) + { + entered.Set(); + release.Wait(TimeSpan.FromSeconds(30)); + } + + public void Error(string eventName, IReadOnlyDictionary fields) + { + } + } + private sealed class RecordingCommandExecutor : IStaCommandExecutor { private readonly object gate = new(); diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmAckWriter.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmAckWriter.cs index d79df700..0e20d9b1 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmAckWriter.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/AlarmAckWriter.cs @@ -318,12 +318,9 @@ public sealed class AlarmAckWriter : IAlarmAckWriter IMxAccessServer? mx = server; if (mx is not null) { - foreach (AckItem item in itemLru) - { - try { mx.UnAdvise(serverHandle, item.Handle); } catch { /* best effort */ } - try { mx.RemoveItem(serverHandle, item.Handle); } catch { /* best effort */ } - } - + // Unregister drops every cached ack item and its advice in one call (the teardown + // MxAccessSession relies on); per-item UnAdvise/RemoveItem ahead of it were redundant COM + // round trips on the STA. LRU eviction of a single item still removes it individually. try { mx.Unregister(serverHandle); } catch { /* best effort */ } } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs index 28c29ee3..bf49e213 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/IAlarmCommandHandler.cs @@ -14,6 +14,13 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess; /// public interface IAlarmCommandHandler : IDisposable { + /// + /// Gets a value indicating whether an alarm subscription is active. Safe to read from any + /// thread. The STA alarm poll loop reads it to skip the STA hop entirely while nothing is + /// subscribed, so an idle session does not wake its STA every poll interval. + /// + bool IsSubscribed { get; } + /// /// Begin an alarm subscription from the supplied command. The command's /// and diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs index 7db080fd..83c3ec7f 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/LmxSubtagAlarmSource.cs @@ -213,17 +213,10 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource IMxAccessServer? mxServer = server; if (mxServer is not null && registered) { - foreach (KeyValuePair entry in addressesByItemHandle) - { - // Only UnAdvise handles that were actually advised. - if (advisedItemHandles.Contains(entry.Key)) - { - try { mxServer.UnAdvise(serverHandle, entry.Key); } catch { /* swallow — best effort */ } - } - - try { mxServer.RemoveItem(serverHandle, entry.Key); } catch { /* swallow — best effort */ } - } - + // Unregister alone drops every item (and its advice) under the server handle — the same + // teardown MxAccessSession relies on. Walking the items first cost three COM calls per + // watched alarm on the STA (thousands for a large watch list) ahead of the one call that + // makes them redundant, with data callbacks and commands queued behind them. try { mxServer.Unregister(serverHandle); } catch { /* swallow — best effort */ } } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs index ae184433..bf220a73 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs @@ -424,6 +424,14 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession return; } + // No subscription means PollOnce would find no dispatcher and return. Skip the STA + // hop (a work item plus a message-loop wake) so a session that never subscribes, or + // has not yet, costs no STA time at the poll rate. + if (!handler.IsSubscribed) + { + continue; + } + try { await staRuntime.InvokeAsync( diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessValueCache.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessValueCache.cs index fac45456..049abad6 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessValueCache.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessValueCache.cs @@ -225,7 +225,7 @@ public sealed class MxAccessValueCache /// Absolute UTC deadline. /// Action that pumps any pending Windows messages. /// The cached value if the update was received before the deadline. - /// Upper bound on one idle wait slice — the cadence at which runs when nothing wakes the wait. Default 5 ms, itself capped at . + /// Upper bound on one idle wait slice — the cadence at which runs when nothing wakes the wait. Default 50 ms (the fallback ceiling): a message or the update signal already wakes the wait immediately, so the tick is only the safety net; capped at . /// if an update newer than arrived before the deadline; otherwise . public bool TryWaitForUpdate( int serverHandle, @@ -234,7 +234,7 @@ public sealed class MxAccessValueCache DateTime deadlineUtc, Action pumpStep, out CachedValue value, - int pollIntervalMs = 5) + int pollIntervalMs = StaWaitHelper.MaxFallbackTickMilliseconds) { if (pumpStep is null) { @@ -304,7 +304,7 @@ public sealed class MxAccessValueCache Action pumpStep, bool[] received, CachedValue[] values, - int pollIntervalMs = 5) + int pollIntervalMs = StaWaitHelper.MaxFallbackTickMilliseconds) { if (itemHandles is null) { @@ -337,6 +337,11 @@ public sealed class MxAccessValueCache throw new ArgumentException("Handle, baseline, and output arrays must have matching lengths."); } + // Indexes still waiting for an update. Each wake probes only these and drops the ones that + // arrived, so the per-wake cost shrinks as handles complete instead of rescanning all of + // them (a lock and a dictionary lookup each) for the whole timeout. + int[] pending = new int[count]; + int pendingCount = 0; int receivedCount = 0; for (int index = 0; index < count; index++) { @@ -344,27 +349,34 @@ public sealed class MxAccessValueCache { receivedCount++; } + else + { + pending[pendingCount++] = index; + } } while (true) { pumpStep(); - for (int index = 0; index < count; index++) + int stillPending = 0; + for (int slot = 0; slot < pendingCount; slot++) { - if (received[index]) - { - continue; - } - + int index = pending[slot]; if (TryGet(serverHandle, itemHandles[index], out CachedValue value) && value.Version > sinceVersions[index]) { received[index] = true; values[index] = value; receivedCount++; } + else + { + pending[stillPending++] = index; + } } + pendingCount = stillPending; + if (receivedCount >= count) { return receivedCount; diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessWriteCompletionCache.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessWriteCompletionCache.cs index 54ed9559..e137fef2 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessWriteCompletionCache.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessWriteCompletionCache.cs @@ -133,7 +133,7 @@ public sealed class MxAccessWriteCompletionCache /// Absolute UTC deadline. /// Action that pumps any pending Windows messages. /// The recorded status rows if a completion arrived before the deadline; empty otherwise. - /// Upper bound on one idle wait slice — the cadence at which runs when nothing wakes the wait. Default 5 ms, itself capped at . + /// Upper bound on one idle wait slice — the cadence at which runs when nothing wakes the wait. Default 50 ms (the fallback ceiling): a message or the completion signal already wakes the wait immediately, so the tick is only the safety net; capped at . /// if a completion newer than arrived before the deadline; otherwise . public bool TryWaitForCompletion( int serverHandle, @@ -142,7 +142,7 @@ public sealed class MxAccessWriteCompletionCache DateTime deadlineUtc, Action pumpStep, out RepeatedField statuses, - int pollIntervalMs = 5) + int pollIntervalMs = StaWaitHelper.MaxFallbackTickMilliseconds) { if (pumpStep is null) { diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs index bb589a8b..9f645662 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs @@ -104,6 +104,9 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer private long lastTruncationWarningMilliseconds = -TruncationWarningIntervalMilliseconds; private long truncatedFetchCount; private bool lastSnapshotTruncated; + private string? lastFetchedXml; + private int lastFetchedRecordCount; + private int lastParsedRecordCount; private wwAlarmConsumerClass? client; private bool subscribed; private bool disposed; @@ -351,6 +354,9 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer /// internal Action? TruncationWarningSink { get; set; } + /// Gets how many fetched documents were actually parsed (diagnostic, for tests). + internal int XmlParseCount { get; private set; } + /// public void PollOnce() { @@ -367,7 +373,55 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer string xml = xmlObj?.ToString() ?? string.Empty; if (xml.Length == 0) return; - Dictionary next = ParseSnapshotXml(xml, out int fetchedRecordCount); + IReadOnlyList transitions = ProcessFetchedXml(xml); + + if (transitions.Count == 0) return; + EventHandler? handler = AlarmTransitionEmitted; + if (handler is null) return; + foreach (MxAlarmTransitionEvent transition in transitions) + { + handler.Invoke(this, transition); + } + } + + /// + /// Folds one fetched alarm XML document into the retained snapshot and returns the + /// transitions it implies. Split out of so the fetch-to-fold step is + /// testable without the wnwrap COM object. + /// + /// A document identical to the previous one cannot change the snapshot, the transitions + /// or the truncation verdict, so the parse (about 19 strings and a record per alarm) and + /// the diff are skipped; only the rate-limited truncation warning is still counted, so a + /// galaxy parked above the cap keeps being reported. The BSTR copy itself cannot be + /// avoided. + /// + /// + /// The non-empty GetXmlCurrentAlarms2 reply. + /// The transitions the fetch implies; empty when the document is unchanged. + internal IReadOnlyList ProcessFetchedXml(string xml) + { + int fetchedRecordCount; + int parsedCount; + bool truncated; + lock (syncRoot) + { + if (lastFetchedXml is not null && string.Equals(lastFetchedXml, xml, StringComparison.Ordinal)) + { + fetchedRecordCount = lastFetchedRecordCount; + parsedCount = lastParsedRecordCount; + truncated = lastSnapshotTruncated; + int retained = latestSnapshot.Count; + if (truncated) + { + WarnTruncatedFetch(fetchedRecordCount, parsedCount, retained); + } + + return Array.Empty(); + } + } + + Dictionary next = ParseSnapshotXml(xml, out fetchedRecordCount); + XmlParseCount++; // TRUNCATION CLIFF. GetXmlCurrentAlarms2 caps its reply at maxAlmCnt // and gives no *verified* "there is more" flag, so a reply holding @@ -381,7 +435,7 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer // matching the records in the reply every time. It reports the reply, // not the total, so it cannot tell a capped fetch from a complete one. // See docs/AlarmProbeFindings.md.) - bool truncated = IsTruncatedFetch(fetchedRecordCount, maxAlarmsPerFetch); + truncated = IsTruncatedFetch(fetchedRecordCount, maxAlarmsPerFetch); IReadOnlyList transitions = FoldFetch(next, truncated, out int retainedCount); @@ -391,13 +445,14 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer WarnTruncatedFetch(fetchedRecordCount, next.Count, retainedCount); } - if (transitions.Count == 0) return; - EventHandler? handler = AlarmTransitionEmitted; - if (handler is null) return; - foreach (MxAlarmTransitionEvent transition in transitions) + lock (syncRoot) { - handler.Invoke(this, transition); + lastFetchedXml = xml; + lastFetchedRecordCount = fetchedRecordCount; + lastParsedRecordCount = next.Count; } + + return transitions; } /// diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs index 1a6eb2d6..33e33c22 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs @@ -122,6 +122,8 @@ public sealed class StaCommandDispatcher throw new ArgumentNullException(nameof(command)); } + QueuedStaCommand queuedCommand; + bool startDrain = false; lock (gate) { if (shutdownRequested) @@ -140,17 +142,27 @@ public sealed class StaCommandDispatcher $"The STA command dispatcher already has {maxPendingCommands} pending command(s).")); } - QueuedStaCommand queuedCommand = new(command); + queuedCommand = new QueuedStaCommand(command); commandQueue.Enqueue(queuedCommand); if (!drainActive) { drainActive = true; - _ = DrainAsync(); + startDrain = true; } - - return queuedCommand.Task; } + + // Started after the gate is released. An async method runs synchronously to its first + // incomplete await, so starting it under the lock ran the dequeue, the optional command-log + // console write and the STA enqueue under the same lock the heartbeat, PendingCommandCount + // and CancelQueuedCommand take: a slow stderr sink stalled the pipe read loop and those + // callers together. + if (startDrain) + { + _ = DrainAsync(); + } + + return queuedCommand.Task; } /// @@ -242,6 +254,14 @@ public sealed class StaCommandDispatcher private async Task DrainAsync() { + // With command logging on, the first step writes to the console. Yield so that write runs on + // a pool thread instead of the pipe read loop that called DispatchAsync. Not done when logging + // is off: the extra pool hop would cost a wake-up per idle-to-busy transition for nothing. + if (CommandLogger is not null) + { + await Task.Yield(); + } + while (true) { QueuedStaCommand queuedCommand;