fix(opcuaclient): RefreshEnd signals initial alarm state only for a lossless refresh bracket (#926)
Track RefreshStart..RefreshEnd per alarm subscription. EventQueueOverflow (matched by EventType before the source filter - it comes from the Server object), RefreshRequired, a publish-sequence gap the SDK skipped (EventFieldList.Message.SequenceNumber; SDK 2.0.1's Republish publish-state never fires for a gap that blocks delivery) or a missing RefreshStart suppress the A1 signal and re-run ConditionRefresh, bounded (3, 2/4/8 s); exhausted = conditions stay unknown (Uncertain), never Unsignalable. Alarm event queue 1000 -> 10000; new counters alarm_event_queue_overflow / alarm_refresh_lossy. Unit + real-SDK gap tests, live overflow gate on opc-plc --alm; plan G2 text corrected.
This commit is contained in:
@@ -294,6 +294,11 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
|
||||
AFTER configured ones; more than one discovered server without `discoveryServerUri` fails the connect. Session
|
||||
events are the OTel counter `otopcua.driver.opcuaclient.events`. `HistoryAggregateType` carries the full Part 13
|
||||
set; an aggregate the gateway can't serve is `BadAggregateNotSupported` per node.
|
||||
- **OpcUaClient RefreshEnd = A1 known-state signal, lossless brackets only (#926):** no RefreshStart, an
|
||||
`EventQueueOverflowEventType` (matched by EventType BEFORE the source filter — it comes from the Server object), a
|
||||
RefreshRequired, or a publish-sequence gap (`EventFieldList.Message.SequenceNumber`; SDK 2.0.1's `Republish` publish-state
|
||||
never fires for a gap that blocks delivery — do not rely on it) inside the bracket ⇒ no signal + bounded re-refresh
|
||||
(3, 2/4/8 s). Exhausted ⇒ stays unknown; never fall back to `Unsignalable` (that starts the backstop that marks known).
|
||||
- **OpcUaClient server host-name check (#816):** the SDK checks the server certificate's host only with
|
||||
`checkDomain: true`; its 8-arg `DefaultSessionFactory.CreateAsync` hard-codes `false`, so driver, AdminUI browser and
|
||||
Client.Shared never checked before #816. Now `certificateValidation.validateServerHostName` (tri-state, unset = off =
|
||||
|
||||
@@ -479,8 +479,12 @@ refresh, EventIds) is documented in [Alarm tracking § Imported conditions](Alar
|
||||
is raised on the hub.
|
||||
- `DataConnections:ConditionKnownSettle:OpcUaClient` (default 60 s) is the only backstop timer. It exists for upstreams
|
||||
without ConditionRefresh.
|
||||
- Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD), #925 (Galaxy deploy-added conditions stay
|
||||
unknown) and #926 (an OpcUaClient RefreshEnd can signal known over lost events).
|
||||
- Open gaps: #924 (L4 latency for Galaxy, Heidenhain and real Logix ALMD) and #925 (Galaxy deploy-added conditions stay
|
||||
unknown).
|
||||
- An OpcUaClient RefreshEnd signals only for a lossless refresh bracket (#926). Loss inside the bracket — queue
|
||||
overflow, RefreshRequired, a skipped publish gap, or a missing RefreshStart — suppresses the signal and re-runs
|
||||
ConditionRefresh, at most 3 times. If every retry is lossy, the conditions stay unknown and the timeout diagnostic
|
||||
reports them. See `docs/drivers/OpcUaClient.md`.
|
||||
|
||||
### Condition key (`DataConnections:ConditionKeySecret`)
|
||||
|
||||
|
||||
@@ -449,8 +449,26 @@ initialise (the AdminUI form drops them on the next save). Pinned by
|
||||
> `Unspecified` the host wrote as "Activated", and a retained-Active host condition stayed Active). So the host writes no
|
||||
> duplicate row when its condition already shows that state (see `docs/AlarmTracking.md`). Condition **branch** events (non-null `BranchId`) are ignored.
|
||||
> **`ConditionRefresh`** is called after the event item is created, after a keep-alive outage the session survived, and on a
|
||||
> `RefreshRequired` event, so a condition already active upstream is reported at subscribe; `RefreshStart`/`RefreshEnd`
|
||||
> markers are dropped. A server without it (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated.
|
||||
> `RefreshRequired` event, so a condition already active upstream is reported at subscribe. The `RefreshStart`/`RefreshEnd`
|
||||
> markers are never projected as alarms. A server without ConditionRefresh (`BadNotSupported`/`BadMethodInvalid`/…) is logged once and tolerated.
|
||||
>
|
||||
> **A RefreshEnd signals "initial alarm state delivered" only for a lossless bracket (#926).** That signal is grpc-data
|
||||
> A1's known-state signal. The driver tracks RefreshStart…RefreshEnd per alarm subscription, and the RefreshEnd does
|
||||
> not signal when any of these happened:
|
||||
>
|
||||
> - no RefreshStart was seen;
|
||||
> - the server sent an `EventQueueOverflowEventType`. That notice comes from the Server object, so it is matched before
|
||||
> the source filter, and it is never projected as an alarm;
|
||||
> - a `RefreshRequired` arrived;
|
||||
> - a delivered publish message skipped a sequence number. This catches the gap the SDK gives up on after a failed
|
||||
> republish, which the SDK reports nowhere else.
|
||||
>
|
||||
> A lossy bracket logs a Warning and re-runs ConditionRefresh on that subscription. At most 3 re-refreshes run per
|
||||
> episode, backing off 2 s, 4 s and 8 s, and a clean RefreshEnd resets the budget. When it is spent, nothing signals:
|
||||
> the conditions stay unknown (`Uncertain`) and the host's `ConditionKnownSignalTimeout` diagnostic reports them.
|
||||
> An overflow outside a bracket (lost live transitions) also requests a re-refresh. The alarm event item asks for a
|
||||
> queue of 10,000 (previously 1,000); the server may revise it down. Counters on `otopcua.driver.opcuaclient.events`:
|
||||
> `alarm_event_queue_overflow` and `alarm_refresh_lossy`.
|
||||
> Last-told state survives a re-initialise (the host re-subscribes the same set over nodes it did not rebuild) and is
|
||||
> forgotten when the subscribed set changes (the host rebuilt, recreating the nodes inactive). Index keys are server-stable (`nsu=`), so a namespace reorder across a re-initialise keeps
|
||||
> matching. docker-dev seeds an opc-plc driver (`MAIN-opcua`); the alarm tag is
|
||||
|
||||
@@ -88,7 +88,7 @@ found while verifying M1 (row M1).
|
||||
| Galaxy one-shot signal per feed instance | Accepted (verified `GatewayGalaxyAlarmFeed.cs:69,140-152,168`) | §5.1: signal raised on **every** sentinel (not the one-shot task), and drivers re-signal each complete cycle, so conditions become known again after a reopen or a deploy that adds them; A1 test (vii) |
|
||||
| **Fifth pass (revision 7)** | | |
|
||||
| G1 driver-wide signal scope | Accepted (verified `FocasAlarmProjection.cs:253-276`, `AbCipAlarmProjection.cs:211`, `HeidenhainAlarmProjection.cs:214`) | §5.1: `AlarmInitialStateEventArgs.ConditionIds`; `MarkConditionsKnown` takes a condition-id set; per-host / per-node hooks in the driver table; MTConnect excludes `Unavailable`; A1 test (viii) |
|
||||
| G2 RefreshEnd ordering across publish responses | Accepted; **settled by decompiling** `Opc.Ua.Client` 2.0.1: not ordered by default (`SequentialPublishing` false; parallel workers) | §5.1: `SequentialPublishing = true` on the alarm subscription (`OpcUaClientDriver.cs:2445`); gap ⇒ no signal; A1 test (ix) |
|
||||
| G2 RefreshEnd ordering across publish responses | Accepted; **settled by decompiling** `Opc.Ua.Client` 2.0.1: not ordered by default (`SequentialPublishing` false; parallel workers) | §5.1: `SequentialPublishing = true` on the alarm subscription (`OpcUaClientDriver.cs:2445`); A1 test (ix). Loss inside the refresh bracket (EventQueueOverflow, RefreshRequired, a publish-sequence gap the SDK skipped, or a missing RefreshStart) ⇒ that RefreshEnd does not signal and ConditionRefresh is re-run, bounded (#926) |
|
||||
| G3 deferred signal outliving a dropped alarm | Accepted (verified `OpcUaPublishActor.cs:1048-1051`, `:1106-1112`) | §5.1 loss rule: a drop or skip discards that source's deferred `MarkConditionsKnown`; A1 test (x) |
|
||||
| G4 re-bind rarely holds across failover | Accepted | §5.6 step 3: client-visible behaviour stated (`BadEventIdUnknown` → `RefreshRequired` → ConditionRefresh → Good); A03 corrected |
|
||||
| G5 suppression gate | Accepted (verified `DriverInstanceActor.cs:184-188,1144-1148,2536-2541`) | §5.1: signal attached/gated with `OnAlarmEvent`; A1 test (xi) |
|
||||
@@ -492,11 +492,28 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event
|
||||
- So the RefreshEnd of a multi-response replay could be processed before an earlier response. A1 therefore sets
|
||||
**`SequentialPublishing = true` on the alarm subscription** (`OpcUaClientDriver.cs:2445`). The data subscriptions
|
||||
are unchanged.
|
||||
- **As implemented (A1):** there is no gap-based suppression. The SDK 2.0.1 surface the driver sees (the per-item
|
||||
`Notification` callback) exposes no per-message gap or republish failure. With `SequentialPublishing` the worker
|
||||
waits for a missing sequence number (republish) before it delivers later ones, so an ordinary gap still orders the
|
||||
RefreshEnd last. **Residual:** a gap the SDK gives up on could let a RefreshEnd signal over a lost refreshed event.
|
||||
The mitigation for notification-queue overflow and abandoned gaps is tracked in #926.
|
||||
- With `SequentialPublishing` the worker waits for a missing sequence number (republish) before it delivers later
|
||||
ones, so an ordinary (recovered) gap still orders the RefreshEnd last.
|
||||
- **As implemented (#926): a RefreshEnd signals only for a lossless RefreshStart…RefreshEnd bracket.** The driver
|
||||
tracks the bracket per alarm subscription. It does **not** signal when:
|
||||
- no RefreshStart opened the bracket (the head of the replay was discarded);
|
||||
- an `EventQueueOverflowEventType` arrived since the RefreshStart. That notice comes from the Server object, so it
|
||||
is matched by EventType **before** the source filter;
|
||||
- a `RefreshRequired` arrived since the RefreshStart;
|
||||
- a **publish-sequence gap** was seen inside the bracket. That is a delivered message whose sequence number is
|
||||
neither the previous one nor its successor; the SDK sets `EventFieldList.Message`, and the alarm subscription has
|
||||
one monitored item. This is how a gap the SDK gave up on is detected. SDK 2.0.1 reports that skip to nothing
|
||||
else: its `PublishStateChangedMask.Republish` callback fires only in a worker pass that also delivers a message,
|
||||
which the blocking gap prevents (verified by decompiling, and pinned by a real-SDK test).
|
||||
- A lossy bracket re-runs ConditionRefresh on that subscription. This is bounded: at most 3 re-refreshes per lossy
|
||||
episode, backing off 2 s, 4 s and 8 s, and a clean RefreshEnd resets the budget. A RefreshRequired keeps its own
|
||||
sweep. When the budget is spent, nothing signals. The conditions stay unknown (`Uncertain`) and F5's
|
||||
`ConditionKnownSignalTimeout` diagnostic reports them. They are never declared known-inactive, and the
|
||||
`Unsignalable` backstop is not used for this.
|
||||
- The alarm event item's queue is now 10,000 (it was 1,000), so overflow is rarer. The detection above is the fix.
|
||||
- Live on `opc-plc --alm` with a test-sized queue: the overflow notices reach the driver. With `DiscardOldest`
|
||||
false the RefreshEnd is itself dropped. With `DiscardOldest` true the RefreshEnd arrives over a lossy replay and
|
||||
is refused. Before the fix it signalled. Evidence: `docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md`.
|
||||
- **OpcUaClient upstream without ConditionRefresh** (`:2887-2893`, "conditions already active are reported only on their
|
||||
next transition"). This is the one case with no signal at all. The driver reports `InitialStateUnsignalable` for that
|
||||
subscription, and the per-driver-type **backstop timer** (`DataConnections:ConditionKnownSettle:OpcUaClient`, default
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
# #926 — OpcUaClient RefreshEnd signals only for a lossless refresh bracket
|
||||
|
||||
2026-11-28. Follow-up to A1 (plan §5.1, OpcUaClient row, G2).
|
||||
|
||||
## Defect
|
||||
|
||||
A1 takes the alarm subscription's `RefreshEndEventType` as `InitialAlarmStateDelivered`. That signal declares the
|
||||
conditions it covers state-known. The driver raised it on every RefreshEnd, including one that closed a replay that had
|
||||
lost events. A condition that was active upstream could then be declared known-inactive.
|
||||
|
||||
## Ways a replay can lose events
|
||||
|
||||
- **Event-queue overflow.** The upstream inserts an `EventQueueOverflowEventType` notice. Its SourceNode is the Server
|
||||
object, so the driver's source filter dropped it, and in pass-through mode it would have been projected as an alarm.
|
||||
Where the notice lands depends on `DiscardOldest`:
|
||||
- With `DiscardOldest` false (production), the newest events, often the RefreshEnd itself, are dropped.
|
||||
- With `DiscardOldest` true, or on a server that refreshes asynchronously, the RefreshStart and the head of the
|
||||
replay are dropped, but the RefreshEnd still arrives.
|
||||
- **RefreshRequired** arriving during the replay.
|
||||
- **A publish gap the SDK gives up on.** With `SequentialPublishing` the SDK holds later messages while it republishes
|
||||
the missing one. If that republish fails (`BadMessageNotAvailable`), it skips the gap and delivers the next message.
|
||||
- Decompiling SDK 2.0.1 (`Subscription` message worker) shows that `PublishStateChangedMask.Republish` is raised only
|
||||
inside `if (messagesToDeliver != null)`.
|
||||
- So when the gap is holding every later message back, which is exactly this case, no callback fires. Verified with a
|
||||
real `Subscription`: the order was `live:1, start:2, end:4` and no Republish state was raised.
|
||||
|
||||
## Fix (`OpcUaClientDriver`)
|
||||
|
||||
**Per-subscription bracket state.** Each `RemoteAlarmSubscription` has an `AlarmRefreshBracket`, guarded by
|
||||
`_alarmStateLock`.
|
||||
|
||||
**Bracket events are matched by EventType before projection** (`RouteBracketEvent`):
|
||||
- RefreshStart opens the bracket.
|
||||
- EventQueueOverflow records a loss and requests a re-refresh.
|
||||
- RefreshRequired records a loss; its existing sweep is the re-refresh.
|
||||
- RefreshEnd signals only if the bracket was opened and saw no loss. Otherwise it logs a Warning, increments
|
||||
`alarm_refresh_lossy`, and requests a re-refresh unless one was already requested.
|
||||
|
||||
**Publish-sequence check.** `RouteAlarmEventFieldList` reads `NoteAlarmMessageSequence(efl.Message.SequenceNumber)`
|
||||
before it routes the event. The alarm subscription has one monitored item, so every message that carries data
|
||||
consumes one sequence number. Inside a bracket, a number that is neither the same as the last nor its successor
|
||||
(wrap-aware) is a loss.
|
||||
|
||||
**Bounded re-refresh.** `ScheduleAlarmRefreshRetryLocked` → `RetryAlarmRefreshAsync`:
|
||||
- At most 3 re-refreshes per episode, backing off 2 s, 4 s, then 8 s. A clean RefreshEnd resets the budget.
|
||||
- Requests are coalesced while one is pending.
|
||||
- The retry is cancelled with the session's work token, and skipped if the subscription is no longer the one
|
||||
registered.
|
||||
- When the budget is spent, one Warning is logged (it includes the revised queue size) and nothing signals. The
|
||||
conditions stay unknown (`Uncertain`) and F5's `ConditionKnownSignalTimeout` diagnostic reports them.
|
||||
`Unsignalable` is deliberately not used: it starts the backstop that marks the conditions known.
|
||||
|
||||
**Queue size.** The alarm event item's queue is now 10,000 (it was 1,000), so overflow is rarer. The detection above is
|
||||
the actual fix.
|
||||
|
||||
**New counters.** `otopcua.driver.opcuaclient.events{event=alarm_event_queue_overflow|alarm_refresh_lossy}`.
|
||||
|
||||
## Tests
|
||||
|
||||
### Unit: `OpcUaClientRefreshBracketLossTests`
|
||||
|
||||
11 tests:
|
||||
|
||||
- an overflow inside the bracket, a RefreshEnd with no RefreshStart, and a RefreshRequired inside the bracket each
|
||||
suppress the signal, and each has a positive control;
|
||||
- an overflow outside a bracket requests a re-refresh;
|
||||
- the retry bound, and the budget reset after a clean bracket;
|
||||
- a re-refresh whose own RefreshStart is lost can request the next one;
|
||||
- sequence gap, repeat, wrap and gap-outside-bracket;
|
||||
- the overflow notice is never projected;
|
||||
- queue-size pin;
|
||||
- the real-SDK abandoned gap, plus a lossless real-SDK positive control.
|
||||
|
||||
`OpcUaClientInitialAlarmStateSignalTests`: the two tests that routed a RefreshEnd with no RefreshStart now route the
|
||||
RefreshStart first. A real server always sends one, and the live latency test below passes with the new requirement.
|
||||
|
||||
### Red
|
||||
|
||||
These mutations were run as red checks:
|
||||
|
||||
- **RefreshEnd always signals:** 6 of 10 bracket tests fail.
|
||||
- **Sequence check removed:** the real-SDK gap test fails.
|
||||
- **Live:** the same always-signal mutation gives `signals=3` over lossy replays (run `discardOldest=True`, below).
|
||||
|
||||
### Live: `OpcUaClientRefreshOverflowLiveTests`
|
||||
|
||||
Run against the shared `opc-plc --alm` at `opc.tcp://10.100.0.35:50000`, read-only, using test seams for the item's queue
|
||||
size and `DiscardOldest`. No local docker, so the rig lock was not needed.
|
||||
|
||||
| Case | Overflow notices seen | Lossy RefreshEnds refused | Signals |
|
||||
|---|---|---|---|
|
||||
| `DiscardOldest=false`, queue 1 | 25 | 0 (the RefreshEnd was dropped by the server) | 0 |
|
||||
| `DiscardOldest=true`, queue 2 | 11–20 across runs | 1–3 across runs (≤ 1 + 3, bounded) | 0 |
|
||||
| Production queue (control) | 0 | 0 | signalled |
|
||||
| Mutation (always signal), `DiscardOldest=true` | 15 | — | **3** |
|
||||
|
||||
The lossy-RefreshEnd count varies because opc-plc keeps firing live alarms, which can push a RefreshEnd out of a
|
||||
2-entry queue.
|
||||
|
||||
Two observations from the runs:
|
||||
|
||||
- `DiscardOldest=false` with queue 2 produced no overflow notice and no RefreshEnd on this opc-plc. It still never
|
||||
signalled, so the outcome was safe.
|
||||
- A `MeterListener` filtered by `ReferenceEquals` on `OtOpcUaTelemetry.OpcUaClientEvents` never enabled the counter
|
||||
when that class ran alone. The instrument is published inside the type's static initializer, where the field still
|
||||
reads null. The test now reads the field before calling `Start()`.
|
||||
|
||||
`OpcUaClientAlarmSignalLatencyTests` (L4) still passes 20 out of 20 samples, which means opc-plc sends RefreshStart.
|
||||
|
||||
## Residuals
|
||||
|
||||
- **False positives.** A StatusChange-only message on the alarm subscription consumes a sequence number and reads as a
|
||||
gap. So can an SDK sequence resync after a transfer. Either costs one bounded re-refresh and is never a wrong signal.
|
||||
- **Stale RefreshEnd.** If the previous replay's lossy RefreshEnd is still in flight when a re-refresh starts, it can
|
||||
request one extra refresh. That stays inside the bound.
|
||||
- **Live losses after the conditions are known.** An overflow outside a bracket is repaired by a re-refresh. A gap
|
||||
outside a bracket is not detected, but the next bracket replays the full state. In both cases conditions that are
|
||||
already known are not taken back to unknown.
|
||||
@@ -222,6 +222,9 @@ Heidenhain legs are **blocked**: Galaxy needs the VPN and mxaccessgw, and Heiden
|
||||
- With `SequentialPublishing` the worker waits for the missing sequence number (republish) before delivering later ones.
|
||||
- Residual: a gap the SDK gives up on could let a `RefreshEnd` signal over a lost refreshed event. **Resolved in review
|
||||
round 2:** the plan's G2 text now states what is implemented, and the overflow and gap mitigation is tracked in #926.
|
||||
- **#926 (2026-11-28) closes the residual.** The driver now detects the skipped gap itself, from the delivered message's
|
||||
sequence number. It also detects queue overflow, RefreshRequired and a missing RefreshStart inside the refresh
|
||||
bracket, and re-runs ConditionRefresh, bounded. See `926-refresh-bracket.md`.
|
||||
- **MTConnect also signals on a mid-stream `/current` re-baseline** (OUT_OF_RANGE / Agent restart), not only on the subscribe
|
||||
resync and the pump's first act. A re-baseline is a complete re-read, and without the signal a restarted Agent's
|
||||
conditions would wait for the next reconnect.
|
||||
|
||||
@@ -26,6 +26,10 @@ internal sealed class OpcUaClientDiagnostics
|
||||
public const string KeepAliveRecovered = "keepalive_recovered";
|
||||
/// <summary>A late replayed notification (source time at or below the ref's high-water mark) was dropped inside the post-recovery replay window.</summary>
|
||||
public const string StaleNotificationDropped = "stale_notification_dropped";
|
||||
/// <summary>#926: the upstream reported an <c>EventQueueOverflowEventType</c> on an alarm event item (events lost).</summary>
|
||||
public const string AlarmEventQueueOverflow = "alarm_event_queue_overflow";
|
||||
/// <summary>#926: a RefreshEnd was NOT taken as "initial alarm state delivered" because its replay was lossy.</summary>
|
||||
public const string AlarmRefreshLossy = "alarm_refresh_lossy";
|
||||
|
||||
private readonly string _driverInstanceId;
|
||||
|
||||
|
||||
@@ -2434,6 +2434,16 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
private const int AlarmFieldAckedState = 8;
|
||||
private const int AlarmFieldBranchId = 9;
|
||||
|
||||
/// <summary>#926: the requested queue size of the alarm event item (was 1000). See its use.</summary>
|
||||
internal const uint AlarmEventQueueSize = 10_000;
|
||||
|
||||
/// <summary>#926 test seam (the live overflow gate shrinks it): the queue size the alarm event item requests.</summary>
|
||||
internal uint AlarmEventItemQueueSize { get; set; } = AlarmEventQueueSize;
|
||||
|
||||
/// <summary>#926 test seam (the live gate flips it to make a lossy replay KEEP its RefreshEnd): the alarm event
|
||||
/// item's DiscardOldest. Production: false (the newest events are dropped on overflow).</summary>
|
||||
internal bool AlarmEventItemDiscardOldest { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
|
||||
IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
|
||||
@@ -2574,8 +2584,12 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
StartNodeId = ObjectIds.Server,
|
||||
AttributeId = Attributes.EventNotifier,
|
||||
MonitoringMode = MonitoringMode.Reporting,
|
||||
QueueSize = 1000, // deep queue — a server can fire many alarms in bursts
|
||||
DiscardOldest = false,
|
||||
// #926: deep queue — a ConditionRefresh replays EVERY retained upstream condition in one burst, and a
|
||||
// server can fire many alarms at once. An overflow is still detected (EventQueueOverflowEventType ⇒ the
|
||||
// refresh's RefreshEnd does not signal and it is re-run); the depth only makes it rarer. The server
|
||||
// may revise it down (logged with the retry budget's exhaustion).
|
||||
QueueSize = AlarmEventItemQueueSize,
|
||||
DiscardOldest = AlarmEventItemDiscardOldest,
|
||||
Filter = filter,
|
||||
})
|
||||
{
|
||||
@@ -2790,6 +2804,21 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
// without this it would feed RouteAlarmEvent alongside the real one.
|
||||
if (!_alarmSubscriptions.ContainsKey(handle.Id)) return;
|
||||
RecordLivenessEvidence();
|
||||
RouteAlarmEventFieldList(efl, sourceFilter, handle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Route one delivered event: first #926's publish-sequence check (a gap inside a refresh bracket makes it
|
||||
/// lossy — checked BEFORE the event, so a RefreshEnd in the first message after the gap is already suppressed),
|
||||
/// then <see cref="RouteAlarmEvent"/>.
|
||||
/// </summary>
|
||||
/// <param name="efl">The delivered event (the SDK sets <c>Message</c> to its notification message).</param>
|
||||
/// <param name="sourceFilter">The subscription's upstream-key → RawPath index.</param>
|
||||
/// <param name="handle">The subscription handle.</param>
|
||||
internal void RouteAlarmEventFieldList(
|
||||
EventFieldList efl, IReadOnlyDictionary<string, string> sourceFilter, IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
NoteAlarmMessageSequence(handle, efl.Message?.SequenceNumber ?? 0);
|
||||
RouteAlarmEvent(efl.EventFields.ToList(), sourceFilter, handle);
|
||||
}
|
||||
|
||||
@@ -2826,25 +2855,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
internal void RouteAlarmEvent(
|
||||
IReadOnlyList<Variant> fields, IReadOnlyDictionary<string, string> sourceFilter, IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
if (IsRefreshRequired(fields))
|
||||
if (fields.Count > AlarmFieldEventType && UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId markerType
|
||||
&& IsBracketEventType(markerType))
|
||||
{
|
||||
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
|
||||
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
|
||||
var sessionWork = _sessionWorkCts.Token;
|
||||
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork));
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsRefreshEnd(fields))
|
||||
{
|
||||
// grpc-data A1 (F1): the refresh replay this subscription requested is complete and every refreshed event
|
||||
// before it was routed (sequential publishing, G2). Under the emission lock, so the signal is ordered
|
||||
// behind every emission. Covers the subscription's alarm RawPaths.
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
if (handle is OpcUaAlarmSubscriptionHandle h && _alarmSubscriptions.TryGetValue(h.Id, out var ras))
|
||||
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
|
||||
}
|
||||
RouteBracketEvent(markerType, handle);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2893,6 +2907,235 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
/// <param name="Severity">Exact severity last told (null before any event).</param>
|
||||
private readonly record struct AlarmToldState(bool Active, bool Acked, string? Message, int? Severity);
|
||||
|
||||
/// <summary>#926: the event types that drive the refresh bracket (never alarms): the three ConditionRefresh
|
||||
/// markers and the server's <c>EventQueueOverflowEventType</c>.</summary>
|
||||
/// <param name="t">The event's EventType.</param>
|
||||
/// <returns>Whether it is a bracket event.</returns>
|
||||
private static bool IsBracketEventType(NodeId t) =>
|
||||
t == ObjectTypeIds.RefreshStartEventType || t == ObjectTypeIds.RefreshEndEventType
|
||||
|| t == ObjectTypeIds.RefreshRequiredEventType || t == ObjectTypeIds.EventQueueOverflowEventType;
|
||||
|
||||
/// <summary>
|
||||
/// #926 — route one bracket event. Matched by EventType BEFORE any source filtering: an
|
||||
/// <c>EventQueueOverflowEventType</c> (Part 4) and the refresh markers come from the Server object, never
|
||||
/// from an authored condition source, so the projector's source filter would drop them.
|
||||
/// <list type="bullet">
|
||||
/// <item>RefreshStart opens a bracket and clears the loss record.</item>
|
||||
/// <item>EventQueueOverflow is a definite loss: the bracket's RefreshEnd will not signal, and a bounded driver
|
||||
/// re-refresh is requested (also outside a bracket — a lost live transition is repaired by a replay).</item>
|
||||
/// <item>RefreshRequired is a loss too; it keeps its existing sweep, which IS the re-refresh.</item>
|
||||
/// <item>RefreshEnd signals (grpc-data A1) only for a bracket that was opened and saw no loss; otherwise it
|
||||
/// stays silent — the conditions stay unknown (Uncertain), the safe invariant — and requests the
|
||||
/// re-refresh if none was yet.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
/// <param name="type">The bracket event's EventType.</param>
|
||||
/// <param name="handle">The subscription the event arrived on.</param>
|
||||
private void RouteBracketEvent(NodeId type, IAlarmSubscriptionHandle handle)
|
||||
{
|
||||
RemoteAlarmSubscription? ras = null;
|
||||
if (handle is OpcUaAlarmSubscriptionHandle h) _alarmSubscriptions.TryGetValue(h.Id, out ras);
|
||||
|
||||
if (type == ObjectTypeIds.RefreshRequiredEventType)
|
||||
{
|
||||
if (ras is not null)
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
// The sweep below re-refreshes this subscription, so no driver retry is requested for it.
|
||||
NoteBracketLoss(ras, "RefreshRequired", requestRetry: false);
|
||||
ras.Bracket.RetryRequestedSinceStart = true;
|
||||
}
|
||||
// Part 9 §5.11.7: the server lost events (queue overflow / restart) and asks for a refresh.
|
||||
// r2 R2-1: bound to the session's work token, which a shutdown cancels first thing.
|
||||
var sessionWork = _sessionWorkCts.Token;
|
||||
_ = Task.Run(() => RefreshAllAlarmSubscriptionsAsync(sessionWork));
|
||||
return;
|
||||
}
|
||||
|
||||
if (ras is null) return; // a released / stray subscription: no bracket, no signal (G5)
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
if (type == ObjectTypeIds.RefreshStartEventType)
|
||||
{
|
||||
b.Open = true;
|
||||
b.LossSinceStart = null;
|
||||
b.RetryRequestedSinceStart = false;
|
||||
}
|
||||
else if (type == ObjectTypeIds.EventQueueOverflowEventType)
|
||||
{
|
||||
_diag.Record(OpcUaClientDiagnostics.AlarmEventQueueOverflow);
|
||||
NoteBracketLoss(ras, "EventQueueOverflow (the upstream discarded events of this subscription)",
|
||||
requestRetry: true);
|
||||
}
|
||||
else if (type == ObjectTypeIds.RefreshEndEventType)
|
||||
{
|
||||
var opened = b.Open;
|
||||
b.Open = false;
|
||||
if (opened && b.LossSinceStart is null)
|
||||
{
|
||||
// grpc-data A1 (F1): the refresh replay this subscription requested is complete, lossless, and every
|
||||
// refreshed event before it was routed (sequential publishing, G2). Under the emission lock, so the
|
||||
// signal is ordered behind every emission. Covers the subscription's alarm RawPaths.
|
||||
b.Retries = 0;
|
||||
b.ExhaustedLogged = false;
|
||||
RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false);
|
||||
return;
|
||||
}
|
||||
|
||||
var reason = b.LossSinceStart ?? "RefreshEnd without its RefreshStart (the bracket start was lost)";
|
||||
_diag.Record(OpcUaClientDiagnostics.AlarmRefreshLossy);
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': RefreshEnd on alarm subscription {SubscriptionId} NOT taken " +
|
||||
"as 'initial alarm state delivered' — {Reason}; its conditions stay unknown until a lossless refresh.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, reason);
|
||||
if (!b.RetryRequestedSinceStart)
|
||||
{
|
||||
b.RetryRequestedSinceStart = true;
|
||||
ScheduleAlarmRefreshRetryLocked(ras, reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>#926: record a loss against <paramref name="ras"/>'s bracket and (once per bracket) request a
|
||||
/// bounded re-refresh. Caller holds <c>_alarmStateLock</c>.</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="reason">What was lost (logged).</param>
|
||||
/// <param name="requestRetry">Whether the driver itself should re-run ConditionRefresh.</param>
|
||||
private void NoteBracketLoss(RemoteAlarmSubscription ras, string reason, bool requestRetry)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
b.LossSinceStart ??= reason;
|
||||
if (!requestRetry || b.RetryRequestedSinceStart) return;
|
||||
b.RetryRequestedSinceStart = true;
|
||||
ScheduleAlarmRefreshRetryLocked(ras, reason);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #926: the publish-sequence check of alarm subscription <paramref name="handle"/>. The alarm subscription holds
|
||||
/// exactly one (event) monitored item, so every data-bearing notification message it receives carries its
|
||||
/// events and consumes one sequence number (keep-alives consume none). With <c>SequentialPublishing</c> the SDK
|
||||
/// delivers messages in order and waits for a missing one (republish); if the republish fails it SKIPS the gap
|
||||
/// and delivers the next message. That skip is reported to nothing the driver can observe — SDK 2.0.1 raises its
|
||||
/// <c>PublishStateChangedMask.Republish</c> only in a message-worker pass that also delivers a message, which a
|
||||
/// gap holding every later message prevents (pinned by the real-SDK test). So the driver compares sequence
|
||||
/// numbers itself: a message that is not the previous one or its successor means messages were lost, and
|
||||
/// inside a bracket that replay is lossy. Outside a bracket the next bracket replays the full state.
|
||||
/// A StatusChange-only message (transfer / timeout) also consumes a number and reads as a gap: a bounded
|
||||
/// extra refresh, never a wrong signal.
|
||||
/// </summary>
|
||||
/// <param name="handle">The alarm subscription handle.</param>
|
||||
/// <param name="sequenceNumber">The delivered message's sequence number (0 = unknown, ignored).</param>
|
||||
internal void NoteAlarmMessageSequence(IAlarmSubscriptionHandle handle, uint sequenceNumber)
|
||||
{
|
||||
if (sequenceNumber == 0) return;
|
||||
if (handle is not OpcUaAlarmSubscriptionHandle h || !_alarmSubscriptions.TryGetValue(h.Id, out var ras)) return;
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
var last = b.LastSequenceNumber;
|
||||
b.LastSequenceNumber = sequenceNumber;
|
||||
if (last == 0 || sequenceNumber == last) return;
|
||||
var next = last == uint.MaxValue ? 1u : last + 1;
|
||||
if (sequenceNumber == next || !b.Open) return;
|
||||
NoteBracketLoss(ras,
|
||||
$"publish message(s) of the replay were lost (sequence {last} → {sequenceNumber})", requestRetry: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>#926: the bounded number of driver-initiated re-refreshes per lossy episode (reset by a clean
|
||||
/// RefreshEnd). When spent, the conditions stay unknown (Uncertain) and the host's
|
||||
/// <c>ConditionKnownSignalTimeout</c> diagnostic reports them — never known-inactive.</summary>
|
||||
internal const int MaxAlarmRefreshRetries = 3;
|
||||
|
||||
/// <summary>#926: the first re-refresh delay; each further retry doubles it (2 s, 4 s, 8 s), giving the
|
||||
/// upstream time to drain whatever overflowed. Test seam.</summary>
|
||||
internal TimeSpan AlarmRefreshRetryBaseDelay { get; set; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>#926 test seam: replaces the ConditionRefresh call of a driver re-refresh.</summary>
|
||||
internal Func<Subscription, CancellationToken, Task>? AlarmRefreshRetryInvokerForTest { get; set; }
|
||||
|
||||
/// <summary>#926: schedule one bounded re-refresh of <paramref name="ras"/> (coalesced while one is pending).
|
||||
/// Caller holds <c>_alarmStateLock</c>.</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="reason">Why (logged).</param>
|
||||
private void ScheduleAlarmRefreshRetryLocked(RemoteAlarmSubscription ras, string reason)
|
||||
{
|
||||
var b = ras.Bracket;
|
||||
if (b.RetryPending) return;
|
||||
if (b.Retries >= MaxAlarmRefreshRetries)
|
||||
{
|
||||
if (!b.ExhaustedLogged)
|
||||
{
|
||||
b.ExhaustedLogged = true;
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost refresh events " +
|
||||
"{Retries} time(s) in a row ({Reason}); no further re-refresh. Its conditions stay unknown (Uncertain) " +
|
||||
"until a later lossless ConditionRefresh (RefreshRequired, reconnect, resubscribe). The event item's " +
|
||||
"revised queue size is {QueueSize}.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, b.Retries, reason, ras.EventItem.Status?.QueueSize);
|
||||
}
|
||||
return;
|
||||
}
|
||||
b.Retries++;
|
||||
b.RetryPending = true;
|
||||
var delay = AlarmRefreshRetryBaseDelay * (1 << (b.Retries - 1));
|
||||
_logger.LogWarning(
|
||||
"OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId}: {Reason}; re-running " +
|
||||
"ConditionRefresh in {Delay} (attempt {Attempt}/{Max}).",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId, reason, delay, b.Retries, MaxAlarmRefreshRetries);
|
||||
var sessionWork = _sessionWorkCts.Token;
|
||||
_ = Task.Run(() => RetryAlarmRefreshAsync(ras, delay, sessionWork));
|
||||
}
|
||||
|
||||
/// <summary>#926: after <paramref name="delay"/>, re-run ConditionRefresh on <paramref name="ras"/> — only while it
|
||||
/// is still the registered subscription for its handle (an unsubscribe / re-init releases it).</summary>
|
||||
/// <param name="ras">The alarm subscription.</param>
|
||||
/// <param name="delay">The back-off.</param>
|
||||
/// <param name="cancellationToken">The session's work token (cancelled by shutdown / re-init).</param>
|
||||
/// <returns>A task completing when the refresh call returned (or was skipped).</returns>
|
||||
private async Task RetryAlarmRefreshAsync(RemoteAlarmSubscription ras, TimeSpan delay, CancellationToken cancellationToken)
|
||||
{
|
||||
var gateHeld = false;
|
||||
try
|
||||
{
|
||||
if (delay > TimeSpan.Zero) await Task.Delay(delay, Clock, cancellationToken).ConfigureAwait(false);
|
||||
await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
gateHeld = true;
|
||||
if (!_alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) || !ReferenceEquals(current, ras)) return;
|
||||
// From here a further loss may request the next retry: it belongs to THIS refresh's replay. That matters
|
||||
// when the replay's own RefreshStart is lost too (queue still full) — without the reset, no bracket opens
|
||||
// and nothing could request again. A lossy RefreshEnd of the PREVIOUS replay still in flight can then
|
||||
// request one extra refresh; that is inside the bound.
|
||||
lock (_alarmStateLock)
|
||||
{
|
||||
ras.Bracket.RetryPending = false;
|
||||
ras.Bracket.RetryRequestedSinceStart = false;
|
||||
}
|
||||
if (AlarmRefreshRetryInvokerForTest is { } invoke)
|
||||
await invoke(ras.Subscription, cancellationToken).ConfigureAwait(false);
|
||||
else if (ras.Subscription.Session is not null && ras.Subscription.Created)
|
||||
await TryConditionRefreshAsync(ras.Subscription, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) { /* shutdown / re-init: the subscription is being released */ }
|
||||
catch (ObjectDisposedException) { /* driver disposed */ }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "OpcUaClientDriver '{DriverInstanceId}': alarm re-refresh of {SubscriptionId} failed; " +
|
||||
"its conditions stay unknown until a later lossless ConditionRefresh.",
|
||||
_driverInstanceId, ras.Handle.DiagnosticId);
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_alarmStateLock) ras.Bracket.RetryPending = false;
|
||||
if (gateHeld)
|
||||
{
|
||||
try { _subscriptionGate.Release(); } catch (ObjectDisposedException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for a <c>RefreshRequiredEventType</c> event (the server asks the client to ConditionRefresh).</summary>
|
||||
/// <param name="fields">The event's fields.</param>
|
||||
/// <returns>Whether the event is a RefreshRequired marker.</returns>
|
||||
@@ -3146,6 +3389,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
if (fields.Count <= AlarmFieldConditionId) return null;
|
||||
// ConditionRefresh brackets its re-delivery with RefreshStart/RefreshEnd — markers, never alarms.
|
||||
if (IsRefreshMarker(UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]))) return null;
|
||||
// #926: the server's queue-overflow notice is not an alarm either (pass-through would otherwise project it).
|
||||
if (UpstreamValueMapping.ToClr(fields[AlarmFieldEventType]) is NodeId et && et == ObjectTypeIds.EventQueueOverflowEventType)
|
||||
return null;
|
||||
// A condition BRANCH event reports a previous state with its own EventId: projecting it would flip the
|
||||
// trunk's state, remembering it would make Acknowledge ack the branch.
|
||||
if (fields.Count > AlarmFieldBranchId && UpstreamValueMapping.ToClr(fields[AlarmFieldBranchId]) is NodeId branch && !branch.IsNull)
|
||||
@@ -3238,7 +3484,44 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
|
||||
OpcUaAlarmSubscriptionHandle Handle,
|
||||
MonitoredItem EventItem,
|
||||
MonitoredItemNotificationEventHandler Handler,
|
||||
IReadOnlyList<string> AlarmRefs);
|
||||
IReadOnlyList<string> AlarmRefs)
|
||||
{
|
||||
/// <summary>#926: this subscription's ConditionRefresh bracket + bounded re-refresh state. Mutated only
|
||||
/// under <c>_alarmStateLock</c>.</summary>
|
||||
public AlarmRefreshBracket Bracket { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #926 — the RefreshStart…RefreshEnd bracket of one alarm subscription. A RefreshEnd declares the conditions it
|
||||
/// covers state-known (grpc-data A1), so it may only signal when the replay it closes is provably complete: its
|
||||
/// RefreshStart was seen and no loss (EventQueueOverflow, RefreshRequired, a publish-sequence gap) was
|
||||
/// observed since. Every field is read and written under <c>_alarmStateLock</c>.
|
||||
/// </summary>
|
||||
internal sealed class AlarmRefreshBracket
|
||||
{
|
||||
/// <summary>A RefreshStart was routed and its RefreshEnd not yet.</summary>
|
||||
public bool Open;
|
||||
|
||||
/// <summary>The first loss observed since the last RefreshStart (null = none). A RefreshEnd with a loss
|
||||
/// does not signal.</summary>
|
||||
public string? LossSinceStart;
|
||||
|
||||
/// <summary>A re-refresh was already requested for the loss since the last RefreshStart or the last re-refresh's
|
||||
/// start (so the lossy RefreshEnd that follows does not request a second one).</summary>
|
||||
public bool RetryRequestedSinceStart;
|
||||
|
||||
/// <summary>A driver re-refresh is scheduled and has not started its ConditionRefresh call yet.</summary>
|
||||
public bool RetryPending;
|
||||
|
||||
/// <summary>Driver re-refreshes spent since the last clean (signalled) RefreshEnd.</summary>
|
||||
public int Retries;
|
||||
|
||||
/// <summary>The retry budget is spent and that was logged (once per episode).</summary>
|
||||
public bool ExhaustedLogged;
|
||||
|
||||
/// <summary>Sequence number of the last delivered notification message (0 = none yet).</summary>
|
||||
public uint LastSequenceNumber;
|
||||
}
|
||||
|
||||
private sealed record OpcUaAlarmSubscriptionHandle(long Id) : IAlarmSubscriptionHandle
|
||||
{
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
using System.Diagnostics.Metrics;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// #926 live gate against <c>opc-plc --alm</c>: an alarm event item whose queue is far smaller than one
|
||||
/// ConditionRefresh replay overflows on the REAL server. The server's <c>EventQueueOverflowEventType</c> must reach
|
||||
/// the driver (it comes from the Server object, past the source filter), the RefreshEnd must NOT signal, and the
|
||||
/// driver's re-refresh is bounded. The positive control is the same driver with the production queue, which signals.
|
||||
/// Read-only against the fixture.
|
||||
/// </summary>
|
||||
[Collection(OpcPlcCollection.Name)]
|
||||
[Trait("Category", "LiveIntegration")]
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Issue", "926")]
|
||||
public sealed class OpcUaClientRefreshOverflowLiveTests(OpcPlcFixture sim, ITestOutputHelper output)
|
||||
{
|
||||
/// <summary>
|
||||
/// <c>discardOldest: false</c> (production): the overflowing replay loses its RefreshEnd too (the newest events
|
||||
/// are dropped), so nothing can signal. <c>true</c>: the RefreshEnd survives but the RefreshStart and the head of
|
||||
/// the replay do not — the case a naive RefreshEnd signal gets wrong. (Observed on the fixture's opc-plc, 2026-11-28:
|
||||
/// with discardOldest false a queue of 1 yields overflow notices; a queue of 2 yielded none at all — and no
|
||||
/// RefreshEnd either, so it still never signalled.)
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false, 1u)]
|
||||
[InlineData(true, 2u)]
|
||||
public async Task Overflowing_refresh_never_signals_and_re_refresh_is_bounded(bool discardOldest, uint queueSize)
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var id = $"opcua-926-live-{Guid.NewGuid():N}";
|
||||
using var counts = new EventCounts(id);
|
||||
|
||||
await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id)
|
||||
{
|
||||
AlarmEventItemQueueSize = queueSize, // one replay = RefreshStart + every retained condition + RefreshEnd
|
||||
AlarmEventItemDiscardOldest = discardOldest,
|
||||
AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(250),
|
||||
};
|
||||
var signals = 0;
|
||||
drv.InitialAlarmStateDelivered += (_, _) => Interlocked.Increment(ref signals);
|
||||
drv.OnAlarmEvent += (_, _) => { };
|
||||
await drv.InitializeAsync("{}", ct);
|
||||
await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
|
||||
|
||||
// 1 + 3 retries, back-off 0.25 + 0.5 + 1 s; allow the replays to arrive.
|
||||
var until = DateTime.UtcNow.AddSeconds(20);
|
||||
while (counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy) < 1 + OpcUaClientDriver.MaxAlarmRefreshRetries
|
||||
&& DateTime.UtcNow < until)
|
||||
await Task.Delay(100, ct);
|
||||
await Task.Delay(3000, ct); // quiet window: nothing further may arrive
|
||||
output.WriteLine($"discardOldest={discardOldest} overflows={counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow)} " +
|
||||
$"lossyRefreshEnds={counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy)} signals={signals}");
|
||||
|
||||
counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBeGreaterThan(0,
|
||||
"the server's EventQueueOverflowEventType reached the driver past the source filter");
|
||||
Volatile.Read(ref signals).ShouldBe(0, "a lossy replay must never declare its conditions known");
|
||||
if (discardOldest)
|
||||
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeGreaterThan(0,
|
||||
"the RefreshEnd arrived and was refused as lossy (its RefreshStart was discarded)");
|
||||
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeLessThanOrEqualTo(
|
||||
1 + OpcUaClientDriver.MaxAlarmRefreshRetries, "re-refresh is bounded — no refresh storm");
|
||||
await drv.ShutdownAsync(ct);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Production_queue_refresh_signals()
|
||||
{
|
||||
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var id = $"opcua-926-live-ctl-{Guid.NewGuid():N}";
|
||||
using var counts = new EventCounts(id);
|
||||
await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id);
|
||||
var signalled = new TaskCompletionSource<AlarmInitialStateEventArgs>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
drv.InitialAlarmStateDelivered += (_, e) => signalled.TrySetResult(e);
|
||||
drv.OnAlarmEvent += (_, _) => { };
|
||||
await drv.InitializeAsync("{}", ct);
|
||||
await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
|
||||
|
||||
(await signalled.Task.WaitAsync(TimeSpan.FromSeconds(30), ct)).Unsignalable.ShouldBeFalse();
|
||||
counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBe(0);
|
||||
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBe(0);
|
||||
await drv.ShutdownAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Counts <c>otopcua.driver.opcuaclient.events</c> for ONE driver instance (the instance tag filters out
|
||||
/// parallel tests' measurements).</summary>
|
||||
private sealed class EventCounts : IDisposable
|
||||
{
|
||||
private readonly MeterListener _listener = new();
|
||||
private readonly Dictionary<string, long> _counts = new();
|
||||
|
||||
public EventCounts(string driverInstanceId)
|
||||
{
|
||||
// Run the telemetry type's static initializer FIRST: if the counter is created while this listener is
|
||||
// live, InstrumentPublished runs inside that initializer, where the field still reads null — the counter
|
||||
// would never be enabled and every count would read 0 (seen when this class ran alone).
|
||||
var counter = OtOpcUaTelemetry.OpcUaClientEvents;
|
||||
_listener.InstrumentPublished = (inst, l) =>
|
||||
{
|
||||
if (ReferenceEquals(inst, counter)) l.EnableMeasurementEvents(inst);
|
||||
};
|
||||
_listener.SetMeasurementEventCallback<long>((_, value, tags, _) =>
|
||||
{
|
||||
string? instance = null, evt = null;
|
||||
foreach (var t in tags)
|
||||
{
|
||||
if (t.Key == OtOpcUaTelemetry.PollOverrunDriverInstanceTag) instance = t.Value as string;
|
||||
else if (t.Key == "event") evt = t.Value as string;
|
||||
}
|
||||
if (instance != driverInstanceId || evt is null) return;
|
||||
lock (_counts) _counts[evt] = _counts.GetValueOrDefault(evt) + value;
|
||||
});
|
||||
_listener.Start();
|
||||
}
|
||||
|
||||
public long Get(string evt) { lock (_counts) return _counts.GetValueOrDefault(evt); }
|
||||
|
||||
public void Dispose() => _listener.Dispose();
|
||||
}
|
||||
}
|
||||
+8
-5
@@ -53,7 +53,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
|
||||
|
||||
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, new StrayHandle());
|
||||
trace.ShouldBeEmpty();
|
||||
// Positive control: the live subscription's RefreshEnd does signal.
|
||||
// Positive control: the live subscription's bracket does signal.
|
||||
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, live);
|
||||
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshEndEventType), index, live);
|
||||
trace.ShouldBe(["signal:" + Trip1]);
|
||||
}
|
||||
@@ -97,6 +98,8 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
|
||||
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
|
||||
var index = new Dictionary<string, string> { ["ns=3;s=Alarms.Trip1"] = Trip1 };
|
||||
|
||||
// #926: the bracket's RefreshStart was routed in an earlier publish response.
|
||||
drv.RouteAlarmEvent(Marker(ObjectTypeIds.RefreshStartEventType), index, handle);
|
||||
var replay = await SdkReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1),
|
||||
[(2u, Marker(ObjectTypeIds.RefreshEndEventType)), (1u, Condition(active: true, acked: false))],
|
||||
fields => drv.RouteAlarmEvent(fields, index, handle));
|
||||
@@ -105,7 +108,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
|
||||
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
|
||||
}
|
||||
|
||||
private static List<string> Record(OpcUaClientDriver drv)
|
||||
internal static List<string> Record(OpcUaClientDriver drv)
|
||||
{
|
||||
var trace = new List<string>();
|
||||
drv.OnAlarmEvent += (_, e) => { lock (trace) trace.Add($"event:{e.ConditionId}:{e.Kind}"); };
|
||||
@@ -116,7 +119,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
|
||||
return trace;
|
||||
}
|
||||
|
||||
private static List<Variant> Marker(NodeId type) =>
|
||||
internal static List<Variant> Marker(NodeId type) =>
|
||||
[
|
||||
Variant.From(new byte[] { 9 }.ToByteString()),
|
||||
new Variant(type),
|
||||
@@ -130,7 +133,7 @@ public sealed class OpcUaClientInitialAlarmStateSignalTests
|
||||
Variant.Null,
|
||||
];
|
||||
|
||||
private static List<Variant> Condition(bool active, bool acked) =>
|
||||
internal static List<Variant> Condition(bool active, bool acked) =>
|
||||
[
|
||||
Variant.From(new byte[] { 1 }.ToByteString()),
|
||||
new Variant(new NodeId("TripAlarmType", 3)),
|
||||
@@ -227,7 +230,7 @@ internal static class SdkReplay
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private static object ToParam(System.Reflection.MethodInfo save, uint[] available)
|
||||
internal static object ToParam(System.Reflection.MethodInfo save, uint[] available)
|
||||
{
|
||||
var t = save.GetParameters()[0].ParameterType;
|
||||
if (t.IsInstanceOfType(available)) return available;
|
||||
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using static ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests.OpcUaClientInitialAlarmStateSignalTests;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #926 — a RefreshEnd declares the conditions it covers state-known (grpc-data A1), so it may signal only for a
|
||||
/// LOSSLESS RefreshStart…RefreshEnd bracket. A loss inside the bracket (the server's EventQueueOverflowEventType, a
|
||||
/// RefreshRequired, a publish-sequence gap the SDK skipped) or a missing RefreshStart suppresses the signal
|
||||
/// and re-runs ConditionRefresh, bounded; a never-signal outcome leaves the conditions unknown (Uncertain).
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Issue", "926")]
|
||||
public sealed class OpcUaClientRefreshBracketLossTests
|
||||
{
|
||||
private const string Trip1 = "Plant/opc/plc/Trip1";
|
||||
|
||||
/// <summary>The authored source index: the overflow notice (SourceNode = Server) is NOT in it, so this also proves
|
||||
/// the notice is seen before the source filter.</summary>
|
||||
private static readonly Dictionary<string, string> Index = new() { ["ns=3;s=Alarms.Trip1"] = Trip1 };
|
||||
|
||||
private static (OpcUaClientDriver Drv, List<string> Trace, IAlarmSubscriptionHandle Handle, RetryProbe Retries) NewDriver(string id)
|
||||
{
|
||||
var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), id)
|
||||
{
|
||||
// Long enough that a replay's own (lossy) RefreshEnd is routed before its re-refresh starts, as in production
|
||||
// (2 s back-off vs. a 500 ms publishing interval); short enough to keep the suite fast.
|
||||
AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(100),
|
||||
};
|
||||
var trace = Record(drv);
|
||||
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
|
||||
var retries = new RetryProbe();
|
||||
drv.AlarmRefreshRetryInvokerForTest = (_, _) => { retries.Hit(); return Task.CompletedTask; };
|
||||
return (drv, trace, handle, retries);
|
||||
}
|
||||
|
||||
private static void Route(OpcUaClientDriver drv, IAlarmSubscriptionHandle h, NodeId type) =>
|
||||
drv.RouteAlarmEvent(Marker(type), Index, h);
|
||||
|
||||
/// <summary>The issue's scenario: refreshed events overflowed the upstream queue, RefreshEnd still arrived. No signal
|
||||
/// (the condition stays unknown), a re-refresh is run, and ITS clean bracket signals.</summary>
|
||||
[Fact]
|
||||
public async Task Overflow_inside_the_bracket_suppresses_the_signal_and_re_refreshes()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-overflow");
|
||||
using var _ = drv;
|
||||
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
drv.RouteAlarmEvent(Condition(active: false, acked: true), Index, h); // what survived; the active one was lost
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
|
||||
trace.ShouldNotContain(t => t.StartsWith("signal:"), "a lossy replay must never declare its conditions known");
|
||||
await retries.WaitForAsync(1);
|
||||
|
||||
// The re-refresh's replay is lossless ⇒ signalled (positive control: the bracket CAN signal).
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
drv.RouteAlarmEvent(Condition(active: true, acked: false), Index, h);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.Last().ShouldBe("signal:" + Trip1);
|
||||
trace.Count(t => t.StartsWith("signal:")).ShouldBe(1);
|
||||
retries.Count.ShouldBe(1, "one loss ⇒ one re-refresh (the lossy RefreshEnd does not request a second)");
|
||||
}
|
||||
|
||||
/// <summary>A bracket whose RefreshStart never arrived (lost with the head of the replay) does not signal.</summary>
|
||||
[Fact]
|
||||
public async Task RefreshEnd_without_its_RefreshStart_does_not_signal()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-nostart");
|
||||
using var _ = drv;
|
||||
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.ShouldBeEmpty();
|
||||
await retries.WaitForAsync(1);
|
||||
}
|
||||
|
||||
/// <summary>A RefreshRequired inside the bracket is a loss; its own sweep is the re-refresh, so the driver adds none.</summary>
|
||||
[Fact]
|
||||
public async Task RefreshRequired_inside_the_bracket_suppresses_the_signal()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-required");
|
||||
using var _ = drv;
|
||||
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshRequiredEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.ShouldBeEmpty();
|
||||
await Task.Delay(200, TestContext.Current.CancellationToken);
|
||||
retries.Count.ShouldBe(0);
|
||||
|
||||
// Positive control: the next clean bracket signals.
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.ShouldBe(["signal:" + Trip1]);
|
||||
}
|
||||
|
||||
/// <summary>An overflow OUTSIDE a bracket lost live events: a re-refresh repairs them (and its bracket signals).</summary>
|
||||
[Fact]
|
||||
public async Task Overflow_outside_a_bracket_requests_a_re_refresh()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-live-overflow");
|
||||
using var _ = drv;
|
||||
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
||||
await retries.WaitForAsync(1);
|
||||
trace.ShouldBeEmpty("the overflow notice is never projected as an alarm");
|
||||
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.ShouldBe(["signal:" + Trip1]);
|
||||
}
|
||||
|
||||
/// <summary>Liveness: a re-refresh whose own RefreshStart is lost (the queue is still full, so only overflow notices
|
||||
/// arrive and no bracket ever opens) can still request the next one, up to the bound.</summary>
|
||||
[Fact]
|
||||
public async Task A_re_refresh_whose_RefreshStart_is_lost_can_request_the_next()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-start-lost");
|
||||
using var _ = drv;
|
||||
|
||||
for (var n = 1; n <= OpcUaClientDriver.MaxAlarmRefreshRetries; n++)
|
||||
{
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); // coalesced into the same request
|
||||
await retries.WaitForAsync(n);
|
||||
}
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
||||
await Task.Delay(500, TestContext.Current.CancellationToken);
|
||||
retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries);
|
||||
trace.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>A structurally lossy upstream (every replay overflows) costs at most <see cref="OpcUaClientDriver.MaxAlarmRefreshRetries"/>
|
||||
/// re-refreshes, then never signals — the conditions stay unknown. A later clean bracket signals and resets the budget.</summary>
|
||||
[Fact]
|
||||
public async Task Re_refresh_is_bounded_and_the_budget_resets_on_a_clean_bracket()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-bounded");
|
||||
using var _ = drv;
|
||||
|
||||
for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 3; i++)
|
||||
{
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries));
|
||||
}
|
||||
await Task.Delay(200, TestContext.Current.CancellationToken);
|
||||
retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "no refresh storm");
|
||||
trace.ShouldBeEmpty("never-signal is the safe outcome: Uncertain, not known-inactive");
|
||||
|
||||
// A lossless bracket (a RefreshRequired sweep, a reconnect) signals and gives the budget back.
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.ShouldBe(["signal:" + Trip1]);
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
||||
await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1);
|
||||
}
|
||||
|
||||
/// <summary>A publish-sequence gap inside a bracket (a message the SDK gave up on) suppresses its signal; contiguous
|
||||
/// numbers, a repeat (several events in one message), the wrap and a gap outside a bracket are no loss.</summary>
|
||||
[Fact]
|
||||
public async Task Sequence_gap_inside_the_bracket_suppresses_outside_is_ignored()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap");
|
||||
using var _ = drv;
|
||||
|
||||
drv.NoteAlarmMessageSequence(h, 5);
|
||||
drv.NoteAlarmMessageSequence(h, 9); // gap outside a bracket: the next bracket replays everything
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
drv.NoteAlarmMessageSequence(h, 10);
|
||||
drv.NoteAlarmMessageSequence(h, 10); // a second event of the same message
|
||||
drv.NoteAlarmMessageSequence(h, 0); // unknown (no message): ignored
|
||||
drv.NoteAlarmMessageSequence(h, 11);
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.ShouldBe(["signal:" + Trip1], "no loss inside that bracket");
|
||||
|
||||
drv.NoteAlarmMessageSequence(h, uint.MaxValue);
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
drv.NoteAlarmMessageSequence(h, 1); // the wrap is contiguous
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.Count(t => t.StartsWith("signal:")).ShouldBe(2);
|
||||
retries.Count.ShouldBe(0);
|
||||
|
||||
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
||||
drv.NoteAlarmMessageSequence(h, 3); // message 2 lost
|
||||
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
||||
trace.Count(t => t.StartsWith("signal:")).ShouldBe(2, "the replay with a lost message did not signal");
|
||||
await retries.WaitForAsync(1);
|
||||
}
|
||||
|
||||
/// <summary>The overflow notice is never an alarm, even pass-through (no authored refs).</summary>
|
||||
[Fact]
|
||||
public void Overflow_notice_is_never_projected()
|
||||
{
|
||||
OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.EventQueueOverflowEventType), new Dictionary<string, string>(),
|
||||
new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldBeNull();
|
||||
// Positive control: a non-marker event from the same source projects pass-through.
|
||||
OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.BaseEventType), new Dictionary<string, string>(),
|
||||
new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldNotBeNull();
|
||||
}
|
||||
|
||||
/// <summary>The alarm event item asks for the deeper queue.</summary>
|
||||
[Fact]
|
||||
public void Alarm_event_queue_is_deep() => OpcUaClientDriver.AlarmEventQueueSize.ShouldBeGreaterThanOrEqualTo(10_000u);
|
||||
|
||||
/// <summary>
|
||||
/// Through a REAL SDK subscription with the driver's alarm options: the publish message carrying a refreshed
|
||||
/// event (seq 3) is lost and its republish fails (not available). The SDK skips the gap and delivers the
|
||||
/// RefreshEnd (seq 4) — reporting the skip to nothing observable: its <c>Republish</c> publish-state is raised
|
||||
/// only in a worker pass that also delivers a message, which the gap prevents. The driver's own sequence check
|
||||
/// (<see cref="OpcUaClientDriver.RouteAlarmEventFieldList"/>) suppresses that RefreshEnd.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Abandoned_publish_gap_suppresses_the_RefreshEnd_through_the_real_SDK()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-gap");
|
||||
using var _ = drv;
|
||||
|
||||
var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: 3);
|
||||
|
||||
order.ShouldBe(["live:1", "start:2", "end:4"], "the SDK skipped the lost message and delivered the RefreshEnd");
|
||||
trace.ShouldNotContain(t => t.StartsWith("signal:"), "a replay with a lost message must not declare its conditions known");
|
||||
await retries.WaitForAsync(1);
|
||||
}
|
||||
|
||||
/// <summary>Positive control for the real-SDK test: the same replay with nothing lost signals.</summary>
|
||||
[Fact]
|
||||
public async Task Lossless_publish_sequence_signals_through_the_real_SDK()
|
||||
{
|
||||
var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-nogap");
|
||||
using var _ = drv;
|
||||
|
||||
var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: null);
|
||||
|
||||
order.ShouldBe(["live:1", "start:2", "refreshed:3", "end:4"]);
|
||||
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
|
||||
retries.Count.ShouldBe(0);
|
||||
}
|
||||
|
||||
private sealed class StrayHandle : IAlarmSubscriptionHandle
|
||||
{
|
||||
public string DiagnosticId => "stray";
|
||||
}
|
||||
|
||||
private sealed class RetryProbe
|
||||
{
|
||||
private int _count;
|
||||
public int Count => Volatile.Read(ref _count);
|
||||
public void Hit() => Interlocked.Increment(ref _count);
|
||||
|
||||
public async Task WaitForAsync(int n)
|
||||
{
|
||||
var until = DateTime.UtcNow.AddSeconds(10);
|
||||
while (Count < n && DateTime.UtcNow < until) await Task.Delay(10);
|
||||
Count.ShouldBeGreaterThanOrEqualTo(n);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Feeds publish responses 1 (a live event), 2 (RefreshStart), 3 (a refreshed Active event), 4 (RefreshEnd) and
|
||||
/// 5..8 (unrelated events) into a real SDK <see cref="Subscription"/>, routing every delivered event through the
|
||||
/// driver's production entry. <c>skip</c>: a sequence number that never arrives and is not available for
|
||||
/// republish. Returns the order of what was delivered (kind:sequence) up to the RefreshEnd.
|
||||
/// </summary>
|
||||
private static class GapReplay
|
||||
{
|
||||
public static async Task<List<string>> DeliverAsync(SubscriptionOptions options, OpcUaClientDriver drv,
|
||||
IAlarmSubscriptionHandle handle, Dictionary<string, string> index, uint? skip)
|
||||
{
|
||||
var order = new List<string>();
|
||||
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var subscription = new Subscription(telemetry: null!, options);
|
||||
var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions
|
||||
{
|
||||
DisplayName = "Server/Events",
|
||||
StartNodeId = ObjectIds.Server,
|
||||
AttributeId = Attributes.EventNotifier,
|
||||
Filter = new EventFilter(),
|
||||
});
|
||||
item.Notification += (_, args) =>
|
||||
{
|
||||
if (args.NotificationValue is not EventFieldList efl) return;
|
||||
lock (order)
|
||||
{
|
||||
if (ended.Task.IsCompleted) return;
|
||||
var seq = efl.Message?.SequenceNumber ?? 0;
|
||||
var kind = UpstreamValueMapping.ToClr(efl.EventFields[1]) is NodeId t
|
||||
? t == ObjectTypeIds.RefreshStartEventType ? "start"
|
||||
: t == ObjectTypeIds.RefreshEndEventType ? "end"
|
||||
: seq == 3 ? "refreshed" : "live"
|
||||
: "?";
|
||||
order.Add($"{kind}:{seq}");
|
||||
drv.RouteAlarmEventFieldList(efl, index, handle);
|
||||
if (kind == "end") ended.TrySetResult();
|
||||
}
|
||||
};
|
||||
subscription.AddItem(item);
|
||||
subscription.AddItem(item);
|
||||
|
||||
const System.Reflection.BindingFlags all = System.Reflection.BindingFlags.Instance
|
||||
| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
|
||||
var save = typeof(Subscription).GetMethods(all)
|
||||
.First(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2);
|
||||
typeof(Subscription).GetMethod("StartKeepAliveTimer", all)!.Invoke(subscription, null);
|
||||
|
||||
var available = new uint[] { 1, 2, 3, 4, 5, 6, 7, 8 }.Where(n => n != skip).ToArray();
|
||||
async Task Send(uint seq, List<Variant> fields, int pauseMs)
|
||||
{
|
||||
var message = new NotificationMessage
|
||||
{
|
||||
SequenceNumber = seq,
|
||||
PublishTime = DateTime.UtcNow,
|
||||
NotificationData =
|
||||
[
|
||||
new ExtensionObject(new EventNotificationList
|
||||
{
|
||||
Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }],
|
||||
}),
|
||||
],
|
||||
};
|
||||
save.Invoke(subscription, [SdkReplay.ToParam(save, available), message]);
|
||||
await Task.Delay(pauseMs);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// seq 1 is a live event before the refresh: the SDK's first message only re-syncs its sequence.
|
||||
await Send(1, Unrelated(), 300);
|
||||
await Send(2, Marker(ObjectTypeIds.RefreshStartEventType), 300);
|
||||
if (skip != 3) await Send(3, Condition(active: true, acked: false), 300);
|
||||
await Send(4, Marker(ObjectTypeIds.RefreshEndEventType), 300);
|
||||
await Send(5, Unrelated(), 300);
|
||||
// The SDK republishes a gap once it is > 2.5 s old with later messages behind it, then skips it once
|
||||
// the republish has failed; each step runs on a later arrival.
|
||||
for (uint seq = 6; seq <= 8 && !ended.Task.IsCompleted; seq++)
|
||||
await Send(seq, Unrelated(), 2700);
|
||||
await ended.Task.WaitAsync(TimeSpan.FromSeconds(15));
|
||||
}
|
||||
finally
|
||||
{
|
||||
subscription.Dispose();
|
||||
}
|
||||
|
||||
lock (order) return order.ToList();
|
||||
}
|
||||
|
||||
private static List<Variant> Unrelated()
|
||||
{
|
||||
var f = Marker(ObjectTypeIds.BaseEventType);
|
||||
f[2] = new Variant(NodeId.Parse("ns=9;s=Elsewhere")); // not an authored source ⇒ dropped by the filter
|
||||
return f;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user