Merge fix/review-2026-12-phase5 (2026-12-02 review fix plan)
Conflicts resolved: - WorkerClient: keep the WRK-003 deadline-bound enqueue and carry the WRK-010 pre-computed envelope size through both the TryWrite fast path and the slow path. - AlarmsHub: prime each connection (DSH-005) and then count it for the idle-gated publisher (DSH-009); a connection that fails priming is never counted, so never decremented. - GatewayDashboardDesign.md: describe both.
This commit is contained in:
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
+33
-10
@@ -142,9 +142,10 @@ else
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (MxEvent evt in _recentEvents)
|
||||
@foreach (EventRow row in _recentEvents)
|
||||
{
|
||||
<tr>
|
||||
MxEvent evt = row.Event;
|
||||
<tr @key="row.Id">
|
||||
<td class="num mono">@evt.WorkerSequence</td>
|
||||
<td>@evt.Family</td>
|
||||
<td class="num mono">@evt.ServerHandle</td>
|
||||
@@ -162,6 +163,20 @@ else
|
||||
@code {
|
||||
private const int MaxRecentEvents = 50;
|
||||
|
||||
/// <summary>
|
||||
/// Minimum spacing between event-driven renders. A busy session emits hundreds of events a
|
||||
/// second; the page shows only the newest <see cref="MaxRecentEvents"/>, so rendering more
|
||||
/// often than a few times a second only costs circuit bandwidth and gateway CPU.
|
||||
/// </summary>
|
||||
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<MxEvent> _recentEvents = new();
|
||||
private readonly LinkedList<EventRow> _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<MxEvent> 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<MxEvent> 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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Whether the parent requests an interactive native modal.</summary>
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -43,6 +43,22 @@ public sealed class DashboardAlarmView
|
||||
/// <summary>Gets how many times the area list was actually computed (diagnostic, for tests).</summary>
|
||||
internal int AreaComputations { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="current">The list the page currently holds.</param>
|
||||
/// <param name="incoming">The latest poll result.</param>
|
||||
/// <returns><see langword="true"/> when every alarm row is value-equal, in order.</returns>
|
||||
public static bool AreSame(IReadOnlyList<DashboardActiveAlarm> current, IReadOnlyList<DashboardActiveAlarm> incoming)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(current);
|
||||
ArgumentNullException.ThrowIfNull(incoming);
|
||||
|
||||
// DashboardActiveAlarm is a record, so Equals compares every displayed field.
|
||||
return current.SequenceEqual(incoming);
|
||||
}
|
||||
|
||||
/// <summary>Returns the alarms matching <paramref name="criteria"/>, highest severity then newest first.</summary>
|
||||
/// <param name="generation">
|
||||
/// Version of <paramref name="alarms"/>; the caller bumps it whenever it replaces the list's contents.
|
||||
|
||||
@@ -107,6 +107,7 @@ public static class DashboardServiceCollectionExtensions
|
||||
static provider => provider.GetRequiredService<Hubs.DashboardEventBroadcaster>());
|
||||
services.AddSingleton<Hubs.DashboardSnapshotHubConnectionCounter>();
|
||||
services.AddHostedService<Hubs.DashboardSnapshotPublisher>();
|
||||
services.AddSingleton<Hubs.AlarmsHubConnectionCounter>();
|
||||
services.AddHostedService<Hubs.AlarmsHubPublisher>();
|
||||
services.AddHttpContextAccessor();
|
||||
services.AddSingleton<IAuditActorAccessor, HttpAuditActorAccessor>();
|
||||
|
||||
@@ -23,8 +23,20 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
|
||||
/// </summary>
|
||||
internal const string UnknownStatus = "Unknown";
|
||||
|
||||
/// <summary>Upper bound on one health evaluation, so a hung check cannot stall the snapshot tick.</summary>
|
||||
private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(2);
|
||||
/// <summary>
|
||||
/// Upper bound on one health evaluation. Longer than the slowest per-check timeout
|
||||
/// (Galaxy SQL, 5 s) so a slow check reports its own <c>Unhealthy</c> result instead of
|
||||
/// being cancelled into <see cref="UnknownStatus"/>. The evaluation runs off the snapshot
|
||||
/// tick, so the bound no longer affects snapshot cadence.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan GatewayStatusRefreshTimeout = TimeSpan.FromSeconds(8);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan GatewayStatusRefreshInterval = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// 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<DashboardApiKeySummary> _apiKeySummaries = Array.Empty<DashboardApiKeySummary>();
|
||||
private long _apiKeySummariesRefreshedAtTicks = NeverRefreshedTicks;
|
||||
// The effective configuration is built from IOptions<GatewayOptions> and is startup-static:
|
||||
@@ -80,7 +93,7 @@ public sealed class DashboardSnapshotService : IDashboardSnapshotService
|
||||
/// <param name="logger">Optional logger for the dashboard snapshot service.</param>
|
||||
/// <param name="healthCheckService">
|
||||
/// The gateway's registered health checks. <see cref="DashboardSnapshot.GatewayStatus"/>
|
||||
/// 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 <see cref="UnknownStatus"/>.
|
||||
/// </param>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="GatewayStatusRefreshInterval"/>. 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.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates the registered health checks and caches the aggregate status
|
||||
/// for <see cref="GetSnapshot"/>, which is synchronous and also serves page seeds
|
||||
/// and hub connects between ticks. One evaluation per tick, not per
|
||||
/// <see cref="GetSnapshot"/> 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
|
||||
/// <see cref="GatewayStatusRefreshInterval"/> is reused: the checks include an auth-store
|
||||
/// query and a Galaxy SQL round trip.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Token to cancel the evaluation.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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
|
||||
|
||||
@@ -31,12 +31,19 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
|
||||
/// </remarks>
|
||||
/// <param name="alarmService">The gateway's central alarm feed.</param>
|
||||
/// <param name="options">Gateway options supplying <c>Dashboard:ShowTagValues</c>.</param>
|
||||
/// <param name="connectionCounter">Live-connection count that idle-gates <see cref="AlarmsHubPublisher"/>.</param>
|
||||
[Authorize(Policy = DashboardAuthenticationDefaults.AlarmsPolicy)]
|
||||
public sealed class AlarmsHub(IGatewayAlarmService alarmService, IOptions<GatewayOptions> options) : Hub
|
||||
public sealed class AlarmsHub(
|
||||
IGatewayAlarmService alarmService,
|
||||
IOptions<GatewayOptions> options,
|
||||
AlarmsHubConnectionCounter connectionCounter) : Hub
|
||||
{
|
||||
/// <summary>Group every admitted connection joins on connect.</summary>
|
||||
public const string AllAlarmsGroup = "__alarms__";
|
||||
|
||||
/// <summary><c>Context.Items</c> key marking a connection that was added to the live count.</summary>
|
||||
private const string CountedItemKey = "mxgw.alarms.counted";
|
||||
|
||||
/// <summary>Method name used to push <c>AlarmFeedMessage</c> values to clients.</summary>
|
||||
public const string AlarmMessage = "AlarmFeed";
|
||||
|
||||
@@ -59,6 +66,25 @@ public sealed class AlarmsHub(IGatewayAlarmService alarmService, IOptions<Gatewa
|
||||
options.Value.Dashboard.ShowTagValues,
|
||||
Context.ConnectionAborted)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Counted only after the client is primed: the publisher subscribes to the monitor once the
|
||||
// count goes non-zero and broadcasts its own reset + snapshot to the group, which then lands
|
||||
// after (never interleaved with) this connection's priming frames.
|
||||
connectionCounter.Increment();
|
||||
Context.Items[CountedItemKey] = true;
|
||||
await base.OnConnectedAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
|
||||
|
||||
/// <summary>
|
||||
/// Process-wide count of live <see cref="AlarmsHub"/> connections. Read by
|
||||
/// <see cref="AlarmsHubPublisher"/> 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.
|
||||
/// </summary>
|
||||
public sealed class AlarmsHubConnectionCounter
|
||||
{
|
||||
private int _count;
|
||||
|
||||
/// <summary>Gets the number of live alarms hub connections.</summary>
|
||||
public int Count => Volatile.Read(ref _count);
|
||||
|
||||
/// <summary>Records a new alarms hub connection.</summary>
|
||||
/// <returns>The connection count after the increment.</returns>
|
||||
public int Increment() => Interlocked.Increment(ref _count);
|
||||
|
||||
/// <summary>
|
||||
/// Records an alarms hub disconnection, clamped at zero inside the compare-and-swap for the
|
||||
/// same reason as <see cref="DashboardSnapshotHubConnectionCounter.Decrement"/>: 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.
|
||||
/// </summary>
|
||||
/// <returns>The connection count after the decrement.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,13 @@ namespace ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
|
||||
/// per-caller scope the feed does not carry.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The loop is idle-gated on <see cref="AlarmsHubConnectionCounter"/>. 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Each broadcast is time-bounded (<see cref="DefaultSendTimeout"/>). 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
|
||||
/// <summary>Upper bound on one alarm broadcast before it is abandoned.</summary>
|
||||
internal static readonly TimeSpan DefaultSendTimeout = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>How often the idle publisher re-checks for a connected client, and the live one for none.</summary>
|
||||
internal static readonly TimeSpan DefaultIdlePollInterval = TimeSpan.FromSeconds(1);
|
||||
|
||||
private readonly IGatewayAlarmService _alarmService;
|
||||
private readonly IHubContext<AlarmsHub> _hubContext;
|
||||
private readonly ILogger<AlarmsHubPublisher> _logger;
|
||||
private readonly TimeSpan _sendTimeout;
|
||||
private readonly AlarmsHubConnectionCounter _connectionCounter;
|
||||
private readonly TimeSpan _idlePollInterval;
|
||||
private readonly bool _showTagValues;
|
||||
private long _subscriptionGeneration;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="AlarmsHubPublisher"/> class.</summary>
|
||||
/// <param name="alarmService">The gateway's central alarm feed.</param>
|
||||
/// <param name="hubContext">Hub context used to broadcast to the alarms group.</param>
|
||||
/// <param name="connectionCounter">Live alarms hub connection count used to idle-gate the subscription.</param>
|
||||
/// <param name="options">Gateway options supplying <c>Dashboard:ShowTagValues</c>.</param>
|
||||
/// <param name="logger">Logger for best-effort broadcast failures.</param>
|
||||
public AlarmsHubPublisher(
|
||||
IGatewayAlarmService alarmService,
|
||||
IHubContext<AlarmsHub> hubContext,
|
||||
AlarmsHubConnectionCounter connectionCounter,
|
||||
IOptions<GatewayOptions> options,
|
||||
ILogger<AlarmsHubPublisher> logger)
|
||||
: this(alarmService, hubContext, options, logger, DefaultSendTimeout)
|
||||
: this(alarmService, hubContext, connectionCounter, options, logger, DefaultSendTimeout, DefaultIdlePollInterval)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Initializes a new instance with a custom send timeout (test hook).</summary>
|
||||
/// <param name="alarmService">The gateway's central alarm feed.</param>
|
||||
/// <param name="hubContext">Hub context used to broadcast to the alarms group.</param>
|
||||
/// <param name="connectionCounter">Live alarms hub connection count used to idle-gate the subscription.</param>
|
||||
/// <param name="options">Gateway options supplying <c>Dashboard:ShowTagValues</c>.</param>
|
||||
/// <param name="logger">Logger for best-effort broadcast failures.</param>
|
||||
/// <param name="sendTimeout">Upper bound on one broadcast.</param>
|
||||
/// <param name="idlePollInterval">How often the connection count is re-checked.</param>
|
||||
internal AlarmsHubPublisher(
|
||||
IGatewayAlarmService alarmService,
|
||||
IHubContext<AlarmsHub> hubContext,
|
||||
AlarmsHubConnectionCounter connectionCounter,
|
||||
IOptions<GatewayOptions> options,
|
||||
ILogger<AlarmsHubPublisher> 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.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Primes one newly connected client with the feed's current state: a
|
||||
/// <see cref="AlarmsHub.ResetMessage"/> marker with generation 0, then the provider
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>0 until the retention index has been created at least once by this instance.</summary>
|
||||
private int _retentionIndexEnsured;
|
||||
|
||||
/// <summary>0 until the <c>audit_event</c> table has been created at least once by this instance.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Returns the most recent canonical audit events, newest first.</summary>
|
||||
@@ -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)
|
||||
|
||||
@@ -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<byte> utf8 = byteCount <= StackLimit
|
||||
? stackalloc byte[StackLimit]
|
||||
: (rented = ArrayPool<byte>.Shared.Rent(byteCount));
|
||||
try
|
||||
{
|
||||
int written = Encoding.UTF8.GetBytes(token, utf8);
|
||||
Span<byte> hash = stackalloc byte[SHA256.HashSizeInBytes];
|
||||
SHA256.HashData(utf8[..written], hash);
|
||||
|
||||
Span<char> 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<byte>.Shared.Return(rented);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
-1
@@ -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<string> InsertionOrder = new();
|
||||
private static readonly object EvictionLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static readonly ConditionalWeakTable<LibApiKeyIdentity, ApiKeyIdentity> MappedIdentities = new();
|
||||
|
||||
/// <summary>Current cache size, exposed for tests asserting the cap is honoured.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<MxEvent> newer = [];
|
||||
ulong highestReplayed = afterSequence;
|
||||
|
||||
|
||||
@@ -25,4 +25,12 @@ public enum SessionManagerErrorCode
|
||||
/// against the restarted gateway.
|
||||
/// </summary>
|
||||
GatewayStopping,
|
||||
|
||||
/// <summary>
|
||||
/// A <c>StreamEvents</c> resume cursor (<c>after_worker_sequence</c>) 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 <c>InvalidArgument</c>.
|
||||
/// </summary>
|
||||
InvalidResumeCursor,
|
||||
}
|
||||
|
||||
@@ -26,6 +26,10 @@ namespace ZB.MOM.WW.MxGateway.Server.Sessions;
|
||||
/// </remarks>
|
||||
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 };
|
||||
|
||||
/// <summary>
|
||||
/// Replaces <paramref name="value"/>'s <see cref="MxValue.SparseArrayValue"/> with an
|
||||
/// equivalent full <see cref="MxValue.ArrayValue"/>. If <paramref name="value"/> 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)
|
||||
|
||||
@@ -24,7 +24,7 @@ public sealed class WorkerClient : IWorkerClient
|
||||
private readonly ILogger<WorkerClient> _logger;
|
||||
private readonly WorkerFrameReader _reader;
|
||||
private readonly WorkerFrameWriter _writer;
|
||||
private readonly Channel<WorkerEnvelope> _outboundEnvelopes;
|
||||
private readonly Channel<OutboundEnvelope> _outboundEnvelopes;
|
||||
private readonly Channel<WorkerEvent> _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<WorkerEnvelope>(
|
||||
_outboundEnvelopes = Channel.CreateBounded<OutboundEnvelope>(
|
||||
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
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Manages writing envelopes to the worker pipe.</summary>
|
||||
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
|
||||
/// <summary>Enqueues an envelope for writing to the worker.</summary>
|
||||
/// <param name="envelope">Envelope to enqueue.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <param name="sizeBeforeSequence">
|
||||
/// The envelope's <c>CalculateSize()</c> while its sequence was still unset, or -1 when not measured.
|
||||
/// </param>
|
||||
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.
|
||||
/// </summary>
|
||||
/// <param name="commandEnvelope">Command envelope to enqueue.</param>
|
||||
/// <param name="envelopeSize">The envelope's size before its sequence is stamped.</param>
|
||||
/// <param name="correlationId">Command correlation id.</param>
|
||||
/// <param name="pendingCommand">The command's pending entry.</param>
|
||||
/// <param name="method">Command method name for metrics and messages.</param>
|
||||
@@ -1442,6 +1471,7 @@ public sealed class WorkerClient : IWorkerClient
|
||||
/// <returns>The part of <paramref name="timeout"/> left for the reply wait.</returns>
|
||||
private async Task<TimeSpan> 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)
|
||||
{
|
||||
|
||||
@@ -32,14 +32,36 @@ public sealed class WorkerFrameWriter
|
||||
/// <param name="envelope">Worker envelope message to write.</param>
|
||||
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public ValueTask WriteAsync(
|
||||
WorkerEnvelope envelope,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
WriteAsync(envelope, sizeBeforeSequence: -1, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="envelope">Worker envelope message to write.</param>
|
||||
/// <param name="sizeBeforeSequence">
|
||||
/// <c>envelope.CalculateSize()</c> as measured while <see cref="WorkerEnvelope.Sequence"/> 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 <c>Sequence</c> changed after the
|
||||
/// measurement; <c>WriteTo</c> fails loudly (it checks the buffer is filled exactly) rather than
|
||||
/// emitting a wrong length prefix if that is ever violated.
|
||||
/// </param>
|
||||
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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<byte>.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);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,37 @@ public sealed class DashboardAlarmViewTests
|
||||
Assert.Equal(["B", "A"], first.Select(alarm => alarm.Reference));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AreSame_DetectsUnchangedPollsSoTheGenerationIsNotBumped()
|
||||
{
|
||||
DashboardAlarmView view = new();
|
||||
List<DashboardActiveAlarm> 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)]));
|
||||
}
|
||||
|
||||
/// <summary>A changed filter input or a new alarm generation recomputes.</summary>
|
||||
[Fact]
|
||||
public void Filtered_WhenCriteriaOrGenerationChange_Recomputes()
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>DSH-008: a dismissed <see cref="NativeDialog"/> must not cost JS interop on every parent render.</summary>
|
||||
public sealed class NativeDialogInteropTests
|
||||
{
|
||||
/// <summary>Open then close, then ten parent re-renders: only the one close call reaches JS.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ClosedDialog_WhenParentRerenders_DoesNotCallCloseAgain()
|
||||
{
|
||||
RecordingJsRuntime js = new();
|
||||
ServiceCollection services = new();
|
||||
services.AddLogging();
|
||||
services.AddSingleton<IJSRuntime>(js);
|
||||
await using ServiceProvider provider = services.BuildServiceProvider();
|
||||
await using TestRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
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)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault();
|
||||
|
||||
/// <summary>Mounts the host component and renders it.</summary>
|
||||
/// <param name="handle">Handle the host publishes itself through.</param>
|
||||
/// <returns>A task that completes once the first render has been dispatched.</returns>
|
||||
public Task MountAsync(HostHandle handle) => Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
DialogHost host = (DialogHost)InstantiateComponent(typeof(DialogHost));
|
||||
host.Handle = handle;
|
||||
int id = AssignRootComponentId(host);
|
||||
return RenderRootComponentAsync(id);
|
||||
});
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void HandleException(Exception exception) => throw new InvalidOperationException("render fault", exception);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) => Task.CompletedTask;
|
||||
}
|
||||
#pragma warning restore BL0006
|
||||
|
||||
private sealed class HostHandle
|
||||
{
|
||||
/// <summary>Gets or sets the mounted host.</summary>
|
||||
public DialogHost? Host { get; set; }
|
||||
}
|
||||
|
||||
private sealed class DialogHost : ComponentBase
|
||||
{
|
||||
/// <summary>Gets or sets the handle the test uses to reach this instance.</summary>
|
||||
public HostHandle Handle { get; set; } = null!;
|
||||
|
||||
/// <summary>Gets or sets a value indicating whether the dialog is open.</summary>
|
||||
public bool Open { get; set; }
|
||||
|
||||
/// <summary>Requests a render, as a snapshot tick does for the host pages.</summary>
|
||||
public void Rerender() => StateHasChanged();
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnInitialized() => Handle.Host = this;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void BuildRenderTree(RenderTreeBuilder builder)
|
||||
{
|
||||
builder.OpenComponent<NativeDialog>(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();
|
||||
|
||||
/// <summary>Gets the module-level calls made, in order.</summary>
|
||||
public List<string> ModuleCalls => _module.Calls;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args) =>
|
||||
new((TValue)(object)_module);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args) =>
|
||||
InvokeAsync<TValue>(identifier, args);
|
||||
}
|
||||
|
||||
private sealed class RecordingModule : IJSObjectReference
|
||||
{
|
||||
/// <summary>Gets the calls made, in order.</summary>
|
||||
public List<string> Calls { get; } = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
|
||||
{
|
||||
lock (Calls)
|
||||
{
|
||||
Calls.Add(identifier);
|
||||
}
|
||||
|
||||
return new(typeof(TValue) == typeof(bool) ? (TValue)(object)true : default!);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object?[]? args) =>
|
||||
InvokeAsync<TValue>(identifier, args);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<AlarmsHubPublisher>.Instance,
|
||||
sendTimeout);
|
||||
sendTimeout,
|
||||
TimeSpan.FromMilliseconds(20));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -337,6 +383,13 @@ public sealed class AlarmsHubPublisherTests
|
||||
private sealed class ScriptedAlarmService(params IReadOnlyList<AlarmFeedMessage>[] batches) : IGatewayAlarmService
|
||||
{
|
||||
private int _subscriptions;
|
||||
private int _active;
|
||||
|
||||
/// <summary>Gets how many times a subscription was opened.</summary>
|
||||
public int SubscriptionCount => Volatile.Read(ref _subscriptions);
|
||||
|
||||
/// <summary>Gets how many subscriptions are currently open.</summary>
|
||||
public int ActiveSubscriptions => Volatile.Read(ref _active);
|
||||
|
||||
/// <inheritdoc />
|
||||
public GatewayAlarmMonitorState State => GatewayAlarmMonitorState.Monitoring;
|
||||
@@ -359,29 +412,37 @@ public sealed class AlarmsHubPublisherTests
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
int index = Interlocked.Increment(ref _subscriptions) - 1;
|
||||
IReadOnlyList<AlarmFeedMessage> 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<AlarmFeedMessage> 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,54 @@ public sealed class DashboardSnapshotServiceTests
|
||||
Assert.Equal(1, health.CheckCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<DashboardSnapshot> 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();
|
||||
}
|
||||
|
||||
/// <summary>A health evaluation that throws is reported as Unknown, never as Healthy.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
@@ -756,11 +804,14 @@ public sealed class DashboardSnapshotServiceTests
|
||||
/// <summary>Gets or sets a value indicating whether the evaluation throws.</summary>
|
||||
public bool Throw { get; set; }
|
||||
|
||||
/// <summary>Gets or sets a gate the evaluation awaits before reporting, to model a slow check.</summary>
|
||||
public TaskCompletionSource? Gate { get; set; }
|
||||
|
||||
/// <summary>Gets the number of evaluations requested.</summary>
|
||||
public int CheckCount => Volatile.Read(ref _checkCount);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Task<HealthReport> CheckHealthAsync(
|
||||
public override async Task<HealthReport> CheckHealthAsync(
|
||||
Func<HealthCheckRegistration, bool>? 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<string, HealthReportEntry>
|
||||
{
|
||||
["stub"] = new(status, null, TimeSpan.Zero, null, null),
|
||||
|
||||
@@ -134,6 +134,56 @@ public sealed class SessionDetailsPageEventAclTests
|
||||
Assert.Empty(subscriber.UndisposedAfterReplacement);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DSH-004: a session emitting hundreds of events a second renders a bounded number of times,
|
||||
/// and the retained rows are the newest ones.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<ILoggerFactory>());
|
||||
|
||||
SessionDetailsPage page = await renderer.MountAsync<SessionDetailsPage>();
|
||||
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<IdleSubscription> UndisposedAfterReplacement =>
|
||||
[.. _handedOut.SkipLast(1).Where(subscription => !subscription.IsDisposed)];
|
||||
|
||||
/// <summary>Gets the most recently handed-out subscription.</summary>
|
||||
internal IdleSubscription Latest => _handedOut[^1];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IDashboardEventSubscription Subscribe(string sessionId)
|
||||
{
|
||||
@@ -214,6 +267,10 @@ public sealed class SessionDetailsPageEventAclTests
|
||||
/// <inheritdoc />
|
||||
public ChannelReader<MxEvent> Reader => _channel.Reader;
|
||||
|
||||
/// <summary>Queues an event for the page's pump to read.</summary>
|
||||
/// <param name="mxEvent">The event to queue.</param>
|
||||
public void Write(MxEvent mxEvent) => _channel.Writer.TryWrite(mxEvent);
|
||||
|
||||
/// <summary>Marks the subscription as released and completes its channel.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
@@ -271,6 +328,11 @@ public sealed class SessionDetailsPageEventAclTests
|
||||
/// <summary>Gets exceptions the renderer surfaced, so a test never passes over a swallowed fault.</summary>
|
||||
public List<Exception> Exceptions { get; } = [];
|
||||
|
||||
/// <summary>Gets the number of render batches the renderer produced.</summary>
|
||||
public int RenderBatches => Volatile.Read(ref _renderBatches);
|
||||
|
||||
private int _renderBatches;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault();
|
||||
|
||||
@@ -306,7 +368,11 @@ public sealed class SessionDetailsPageEventAclTests
|
||||
protected override void HandleException(Exception exception) => Exceptions.Add(exception);
|
||||
|
||||
/// <inheritdoc />
|
||||
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
|
||||
|
||||
|
||||
@@ -234,6 +234,41 @@ public sealed class GatewayEndToEndReconnectReplayTests(ITestOutputHelper output
|
||||
Assert.Equal(expectedTail, tail.Select(e => e.WorkerSequence).ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SES-006, end to end: a resume cursor ahead of every event the session has produced is
|
||||
/// rejected with <c>InvalidArgument</c> 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<RpcException>(async () =>
|
||||
await fixture.Service.StreamEvents(
|
||||
new StreamEventsRequest { SessionId = sessionId, AfterWorkerSequence = 50_000 },
|
||||
new RecordingServerStreamWriter<MxEvent>(),
|
||||
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<MxEvent>(),
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Regression, end to end: when age eviction has emptied the replay ring, the
|
||||
/// <c>ReplayGap</c> sentinel carries the next deliverable sequence (highest observed + 1),
|
||||
|
||||
@@ -144,6 +144,53 @@ public sealed class GatewayArrayWriteWiringTests
|
||||
Assert.Equal(new[] { 0, 7, 0, 0 }, forwarded.ArrayValue.Int32Values.Values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<SessionManagerException>(
|
||||
() => session.InvokeAsync(command, CancellationToken.None));
|
||||
|
||||
Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode);
|
||||
Assert.Equal(MxValue.KindOneofCase.SparseArrayValue, value.KindCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A bare array <c>AddItem2</c> address is normalized to its writable array form on the wire,
|
||||
/// and the normalized address lands in the tracked <see cref="SessionItemRegistration"/>.
|
||||
|
||||
@@ -881,6 +881,55 @@ public sealed class SessionEventDistributorTests
|
||||
Assert.Equal(5ul, liveResume);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RegisterWithReplay_CursorAheadOfStream_IsRejectedAndRegistersNothing()
|
||||
{
|
||||
Channel<MxEvent> source = Channel.CreateUnbounded<MxEvent>();
|
||||
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<SessionManagerException>(() => distributor.RegisterWithReplay(
|
||||
1000,
|
||||
out _,
|
||||
out _,
|
||||
out _,
|
||||
out _));
|
||||
Assert.Equal(SessionManagerErrorCode.InvalidResumeCursor, exception.ErrorCode);
|
||||
Assert.Throws<SessionManagerException>(() => 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<MxEvent> replay,
|
||||
out bool gap,
|
||||
out _,
|
||||
out ulong liveResume);
|
||||
Assert.Empty(replay);
|
||||
Assert.False(gap);
|
||||
Assert.Equal(10ul, liveResume);
|
||||
}
|
||||
|
||||
/// <summary>When nothing retained is newer than the requested sequence, the live resume watermark equals the requested sequence and no gap is reported.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -143,6 +143,24 @@ public sealed class SparseArrayExpanderTests
|
||||
Assert.Equal(5, value.ArrayValue.TimestampValues.Values[1].Seconds);
|
||||
}
|
||||
|
||||
/// <summary>SES-008: unspecified Time slots share one default instance instead of allocating one each.</summary>
|
||||
[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<Timestamp> 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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that expanding a Double sparse array fills defaults and applies the given element.</summary>
|
||||
[Fact]
|
||||
public void Expand_Double_HappyPath()
|
||||
|
||||
@@ -162,6 +162,83 @@ public sealed class WorkerClientTests
|
||||
Assert.Equal(WorkerClientState.Ready, client.State);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WRK-007: a command rejected before it reaches the worker (here <c>CommandTooLarge</c>) is counted
|
||||
/// as started and as failed, so <c>commands.started</c> does not climb without a terminal counter.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<WorkerClientException>(
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<WorkerCommandReply> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that InvokeAsync ignores late replies and keeps the client ready.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -29,6 +29,34 @@ public sealed class WorkerFrameProtocolTests
|
||||
Assert.Equal(original, parsed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="sequence">The sequence stamped after the pre-stamp size was measured.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a large payload near the message cap round-trips through the pooled write/read path.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>
|
||||
/// The retention sweep deletes rows older than <c>AuditRetentionDays</c>, measured from the
|
||||
/// injected clock, and runs once at startup after the one-time table bootstrap.
|
||||
/// injected clock. The table bootstrap completes in <c>StartAsync</c>; the first sweep runs from
|
||||
/// the background loop so a large audit table cannot delay host startup (SEC-014).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>SEC-014: a sweep that blocks (a big table) must not hold up <c>StartAsync</c>.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SqliteStore_DeleteOlderThan_UsesTheRetentionIndexAndSweepsMoreThanOneChunk()
|
||||
{
|
||||
(SqliteCanonicalAuditStore store, AuthSqliteConnectionFactory factory) = CreateStore();
|
||||
DateTimeOffset old = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
List<AuditEvent> 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<string> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sweep compares instants, not stored text, and never deletes a row it cannot date.
|
||||
/// </summary>
|
||||
@@ -357,6 +414,9 @@ public sealed class ChannelAuditWriterTests : IDisposable
|
||||
/// <summary>Gets the number of accepted <see cref="InsertBatchAsync"/> calls.</summary>
|
||||
public int InsertBatchCalls => BatchSizes.Count;
|
||||
|
||||
/// <summary>Gets or sets a gate the sweep waits on, to model a long-running delete.</summary>
|
||||
public TaskCompletionSource? BlockDelete { get; set; }
|
||||
|
||||
/// <summary>Gets the number of <see cref="EnsureInitializedAsync"/> calls.</summary>
|
||||
public int EnsureInitializedCalls { get; private set; }
|
||||
|
||||
@@ -395,14 +455,19 @@ public sealed class ChannelAuditWriterTests : IDisposable
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<int> DeleteOlderThanAsync(DateTimeOffset cutoffUtc, CancellationToken cancellationToken)
|
||||
public async Task<int> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,39 @@ public sealed class CachingApiKeyVerifierTests
|
||||
Assert.Equal(1, inner.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>SEC-012: one mapped gateway identity per cached library identity, not one per RPC.</summary>
|
||||
[Fact]
|
||||
public void ToGatewayIdentity_SameLibraryIdentity_ReturnsTheSameMappedInstance()
|
||||
{
|
||||
LibApiKeyIdentity library = Success("operator01").Identity!;
|
||||
|
||||
Assert.Same(
|
||||
GatewayApiKeyIdentityMapper.ToGatewayIdentity(library),
|
||||
GatewayApiKeyIdentityMapper.ToGatewayIdentity(library));
|
||||
}
|
||||
|
||||
/// <summary>Different presented secrets are cached under distinct keys (no cross-secret aliasing).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -585,6 +585,9 @@ public sealed class AlarmCommandExecutorTests
|
||||
|
||||
private sealed class FakeAlarmHandler : IAlarmCommandHandler
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public bool IsSubscribed => LastSubscription is not null && !UnsubscribeCalled;
|
||||
|
||||
/// <summary>Gets the last subscription expression.</summary>
|
||||
public string? LastSubscription { get; private set; }
|
||||
|
||||
|
||||
@@ -116,26 +116,22 @@ public sealed class LmxSubtagAlarmSourceTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies <see cref="LmxSubtagAlarmSource.Dispose"/> UnAdvises and
|
||||
/// removes every advised handle and unregisters the server exactly once.
|
||||
/// Verifies <see cref="LmxSubtagAlarmSource.Dispose"/> unregisters the server exactly once and
|
||||
/// makes no per-item UnAdvise/RemoveItem calls: <c>Unregister</c> already drops every item under
|
||||
/// the handle (MXA-010).
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gap 2: Verifies that the STA poll loop stops when the session is disposed —
|
||||
/// no further PollOnce calls after disposal. <see cref="MxAccessStaSession.Dispose"/>
|
||||
@@ -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<string> 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;
|
||||
|
||||
/// <summary>Gets a value indicating whether the alarm client is currently subscribed.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Gets the last alarm subscription name.</summary>
|
||||
public string? LastSubscription { get; private set; }
|
||||
|
||||
@@ -264,6 +264,66 @@ public sealed class MxAccessValueCacheTests
|
||||
Assert.True(pumpCalls >= 3, $"Expected repeated pumping across the 400 ms wait, saw {pumpCalls} calls.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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,
|
||||
|
||||
@@ -724,6 +724,31 @@ public sealed class WnWrapAlarmConsumerXmlTests
|
||||
// out of one call, produced under one lock acquisition.
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ProcessFetchedXml_WhenTheDocumentIsUnchanged_SkipsTheParseAndEmitsNothing()
|
||||
{
|
||||
using WnWrapAlarmConsumer consumer = new WnWrapAlarmConsumer(1024);
|
||||
string xml = BuildAlarmXml(3);
|
||||
|
||||
IReadOnlyList<MxAlarmTransitionEvent> first = consumer.ProcessFetchedXml(xml);
|
||||
IReadOnlyList<MxAlarmTransitionEvent> 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<MxAlarmTransitionEvent> changed = consumer.ProcessFetchedXml(BuildAlarmXml(4));
|
||||
Assert.Equal(2, consumer.XmlParseCount);
|
||||
Assert.NotEmpty(changed);
|
||||
Assert.Equal(4, consumer.SnapshotActiveAlarms(out _).Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A capped fetch sets the truncation verdict handed out with the
|
||||
/// snapshot. Without this the signal never leaves the consumer and the
|
||||
|
||||
@@ -320,6 +320,53 @@ public sealed class StaCommandDispatcherTests
|
||||
value => value?.ToString()?.Contains("provider detail") == true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WIP-010: a command-log write that blocks (a slow or full stderr sink) must not hold the
|
||||
/// dispatcher gate, so <c>DispatchAsync</c>, <c>PendingCommandCount</c> and
|
||||
/// <c>CancelQueuedCommand</c> still return while it is stuck.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<MxCommandReply> 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<MxCommandReply> 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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies the opt-in environment value is parsed strictly.</summary>
|
||||
/// <param name="value">Raw environment value.</param>
|
||||
/// <param name="expected">Whether logging should be enabled.</param>
|
||||
@@ -367,6 +414,40 @@ public sealed class StaCommandDispatcherTests
|
||||
/// <summary>
|
||||
/// Test executor that records executed command correlations and thread IDs.
|
||||
/// </summary>
|
||||
// net48 has no Task.WaitAsync; a task that does not finish in time fails the test instead of hanging it.
|
||||
private static async Task<T> WithTimeoutAsync<T>(Task<T> 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<string, object?> fields)
|
||||
{
|
||||
entered.Set();
|
||||
release.Wait(TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
public void Error(string eventName, IReadOnlyDictionary<string, object?> fields)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingCommandExecutor : IStaCommandExecutor
|
||||
{
|
||||
private readonly object gate = new();
|
||||
|
||||
@@ -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 */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,13 @@ namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
|
||||
/// </summary>
|
||||
public interface IAlarmCommandHandler : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
bool IsSubscribed { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Begin an alarm subscription from the supplied command. The command's
|
||||
/// <see cref="SubscribeAlarmsCommand.ForcedMode"/> and
|
||||
|
||||
@@ -213,17 +213,10 @@ public sealed class LmxSubtagAlarmSource : ISubtagAlarmSource
|
||||
IMxAccessServer? mxServer = server;
|
||||
if (mxServer is not null && registered)
|
||||
{
|
||||
foreach (KeyValuePair<int, string> 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 */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -225,7 +225,7 @@ public sealed class MxAccessValueCache
|
||||
/// <param name="deadlineUtc">Absolute UTC deadline.</param>
|
||||
/// <param name="pumpStep">Action that pumps any pending Windows messages.</param>
|
||||
/// <param name="value">The cached value if the update was received before the deadline.</param>
|
||||
/// <param name="pollIntervalMs">Upper bound on one idle wait slice — the cadence at which <paramref name="pumpStep"/> runs when nothing wakes the wait. Default 5 ms, itself capped at <see cref="StaWaitHelper.MaxFallbackTickMilliseconds"/>.</param>
|
||||
/// <param name="pollIntervalMs">Upper bound on one idle wait slice — the cadence at which <paramref name="pumpStep"/> 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 <see cref="StaWaitHelper.MaxFallbackTickMilliseconds"/>.</param>
|
||||
/// <returns><see langword="true"/> if an update newer than <paramref name="sinceVersion"/> arrived before the deadline; otherwise <see langword="false"/>.</returns>
|
||||
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;
|
||||
|
||||
@@ -133,7 +133,7 @@ public sealed class MxAccessWriteCompletionCache
|
||||
/// <param name="deadlineUtc">Absolute UTC deadline.</param>
|
||||
/// <param name="pumpStep">Action that pumps any pending Windows messages.</param>
|
||||
/// <param name="statuses">The recorded status rows if a completion arrived before the deadline; empty otherwise.</param>
|
||||
/// <param name="pollIntervalMs">Upper bound on one idle wait slice — the cadence at which <paramref name="pumpStep"/> runs when nothing wakes the wait. Default 5 ms, itself capped at <see cref="StaWaitHelper.MaxFallbackTickMilliseconds"/>.</param>
|
||||
/// <param name="pollIntervalMs">Upper bound on one idle wait slice — the cadence at which <paramref name="pumpStep"/> 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 <see cref="StaWaitHelper.MaxFallbackTickMilliseconds"/>.</param>
|
||||
/// <returns><see langword="true"/> if a completion newer than <paramref name="sinceVersion"/> arrived before the deadline; otherwise <see langword="false"/>.</returns>
|
||||
public bool TryWaitForCompletion(
|
||||
int serverHandle,
|
||||
@@ -142,7 +142,7 @@ public sealed class MxAccessWriteCompletionCache
|
||||
DateTime deadlineUtc,
|
||||
Action pumpStep,
|
||||
out RepeatedField<MxStatusProxy> statuses,
|
||||
int pollIntervalMs = 5)
|
||||
int pollIntervalMs = StaWaitHelper.MaxFallbackTickMilliseconds)
|
||||
{
|
||||
if (pumpStep is null)
|
||||
{
|
||||
|
||||
@@ -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
|
||||
/// </summary>
|
||||
internal Action<string>? TruncationWarningSink { get; set; }
|
||||
|
||||
/// <summary>Gets how many fetched documents were actually parsed (diagnostic, for tests).</summary>
|
||||
internal int XmlParseCount { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void PollOnce()
|
||||
{
|
||||
@@ -367,7 +373,55 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer
|
||||
string xml = xmlObj?.ToString() ?? string.Empty;
|
||||
if (xml.Length == 0) return;
|
||||
|
||||
Dictionary<Guid, MxAlarmSnapshotRecord> next = ParseSnapshotXml(xml, out int fetchedRecordCount);
|
||||
IReadOnlyList<MxAlarmTransitionEvent> transitions = ProcessFetchedXml(xml);
|
||||
|
||||
if (transitions.Count == 0) return;
|
||||
EventHandler<MxAlarmTransitionEvent>? handler = AlarmTransitionEmitted;
|
||||
if (handler is null) return;
|
||||
foreach (MxAlarmTransitionEvent transition in transitions)
|
||||
{
|
||||
handler.Invoke(this, transition);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Folds one fetched alarm XML document into the retained snapshot and returns the
|
||||
/// transitions it implies. Split out of <see cref="PollOnce"/> so the fetch-to-fold step is
|
||||
/// testable without the wnwrap COM object.
|
||||
/// <para>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="xml">The non-empty <c>GetXmlCurrentAlarms2</c> reply.</param>
|
||||
/// <returns>The transitions the fetch implies; empty when the document is unchanged.</returns>
|
||||
internal IReadOnlyList<MxAlarmTransitionEvent> 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<MxAlarmTransitionEvent>();
|
||||
}
|
||||
}
|
||||
|
||||
Dictionary<Guid, MxAlarmSnapshotRecord> 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<MxAlarmTransitionEvent> 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<MxAlarmTransitionEvent>? 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user