Merge A3: consumer imported-condition registry, visibility, event delivery and lock-free remote condition methods (L2/L3 pass, live conditions_a3_smoke PASS)
v2-ci / unit-tests (push) Failing after 3h13m48s

This commit is contained in:
Joseph Doherty
2026-11-24 22:47:04 -05:00
32 changed files with 6780 additions and 189 deletions
+748
View File
@@ -0,0 +1,748 @@
# A3 evidence — consumer condition registry, visibility, event delivery (A3a) and remote methods (A3b)
Phase A3 (first half) of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md`, 2026-11-24, branch
`a3-consumer` (from master `83c7e586`). A3b (§5.6 remote methods: `ICallAsyncNodeManager`, claim / `base.Call` / await,
lock-freedom, `BadEventIdUnknown`, native Confirm) is a separate agent's work on top of this.
## Progress log
1. Contracts (`e15bd7c9`): `OpcUaServer/IProjectedConditionAccess.cs` — `IProjectedConditionAccess` (gate, generation,
demand), `IProjectedConditionSink` (apply / remove / stale / RefreshRequired), `ImportedConditionPlacement`,
`ImportedConditionUpdate`. SDK-free except the identity type (as `IProjectedHistoryAccess`).
2. Shared helpers (`a75ea95e`, §5.3 "one refactored helper"): `CreateConditionNode` (type, optional children before
`Create()`, child ids via `New`, initial fields) is now the body of `MaterialiseAlarmCondition` AND the imported factory;
`ApplyConditionState` (state projection + the T20/#656 delta gate) is now the body of `WriteAlarmCondition` AND the
imported apply. `ApplicationAlarmConditions.Create` accepts a null parent (an imported condition has no folder parent).
3. Registry (`1ff18caa`): `OpcUaServer/ProjectedConditionRegistry.cs` (registry class + NM partial implementing
`IProjectedConditionSink`).
4. Runtime (`4f6e26dd`): `Runtime/DataConnections/ProjectedConditionAccess.cs`.
5. Host wiring (`8d6c94a3`): DI singleton + `IProjectedConditionAccess`; `OtOpcUaServerHostedService` sets
`NodeManager.ProjectedConditionAccess` and binds the node manager as the runtime's sink; host caps
`DataConnections:MaxImportedConditionNodes` (122,500) / `MaxImportedConditionBytes` (400 MiB).
6. Tests (`de381157`, `4b74ac9c`, `855f7256`, `bdc29ac2`) and the `A3` manifest entry (`762b0fa1`).
## What is implemented (A3a)
- **Namespace + classification (§5.2 N4).** `https://zb.com/otopcua/mapped/conditions` is the node manager's FIFTH
registered namespace. `IsImportedConditionId` is asked before `RealmOf` by `Permits` (read / browse / subscribe) and by
`DataPlaneAuthorizer.TryAuthorizeMapped`, which every authorizer entry point (`Authorize`, `AuthorizeIfRequired`,
`IsAllowedCached`, the alarm-command gate, history) reaches first — so the realm a caller computed with `RealmOf` (which
folds the index into Uns) is never consulted. Imported ids: Browse / Read / CreateMonitoredItems via the condition's
mapping gate; HistoryRead, writes, Call and the alarm operations refused (Call = A3b). ⚠️ **Defect found while testing:**
`OwnsNamespace` listed only indexes 0–3, so condition children kept their ns=0 TYPE ids AND `Permits` treated an
imported id as "not ours to gate" (ungated Read). Fixed; pinned by the child-Read wire test.
- **Registry (§5.3).** Keyed by full NodeId (`c1.` + base64url JSON{ConnectionId, ConditionKey}); never `_alarmConditions` /
`_eventNotifierSources` / `_nativeAlarmNodeIds`. Conditions are parentless predefined nodes with instance-scoped children
(#629). SourceNode = ConditionId = the imported id; SourceName = primary placement path; Severity verbatim (1..1000);
ConditionName / Message / Comment / ClientUserId / ConditionClass / Quality from the record. All Part 9 methods on an
imported condition answer `BadNotSupported` before the SDK touches state (no local apply; A3b replaces this).
- **Notifier wiring (N7).** Lazy and symmetric: a placement's folder (projected folder or mapping anchor, matched on
`(mappingId, local subject)`) is wired when it is materialised — at apply time, or later from `TryEnsureProjectedVariable`
/ `TryEnsureProjectedAnchor` — with `AddNotifier` both ways + `EventNotifier |= SubscribeToEvents` + `AddRootNotifier`;
unwired (`RemoveNotifier(bidirectional)`, root notifier removed, `SubscribeToEvents` cleared when the last condition
leaves) at every projected removal site (anchor removal, capacity eviction, page removal, page rollback). A folder holding
an admitted event item is **pinned**: eviction and page removal skip it; a mapping (anchor) removal still removes it,
unwiring first. The Server object is always the delivery point (`OnConditionReportEvent`).
- **Delivery + gate (§5.4).** Delivery reuses the node manager's report walk (`ReportConditionEvent` → condition's
`OnReportEvent` → Server-object items; inverse notifiers → wired folder items), so exactly-once, the #838 deferral queue
and the #854 cuts apply unchanged. The imported branch: the mapping gate per item **regardless of `AclEnforced`**
(Server object, folder hop, refresh), cached per (identity, condition, authority generation, placement version); the
folder hop also requires the folder to be currently wired. `RaiseConditionRecord` is a no-op for imported conditions
(they are not in `_alarmConditions`), so an imported condition never re-enters the origin hub.
- **`ProjectedEventFieldList : EventFieldList` + rewriter (§5.4).** Imported events ALWAYS take the marked projected path
(`EventDeliveryCache.QueueMarked`), whatever `UseProjectedEventDelivery` says; an item the projected path cannot serve
gets nothing (fail closed, counted). The marker carries identity, condition id, generation and a re-check (live condition
∧ gate). `ProjectedNotificationRewriter.Project` now also walks `EventNotificationList`: a marked list whose re-check
fails is dropped (counted); an UNMARKED list whose `Handle` is an imported-condition snapshot (a select-clause modify
rebuilt it) is re-gated for the publishing session (identity from the Publish/Republish request header's session) and
dropped only on deny (counted); anything else passes as before (v1 messages return the same instance).
- **Event items on projected notifiers.** Admitted (instead of the mapped blanket deny, which still applies to data items)
when the caller passes the gate of at least one condition wired at that folder; delivery and publish re-check per event.
- **Demand / barrier / budget (§5.5)** in `ProjectedConditionAccess`: the first admitted Server-object or projected-notifier
event item opens, per condition-bearing connection (mapping enabled ∧ Subscribe ∧ AlarmSubscribe), ONE stream under the
connection's service principal with one root-scoped item per mapping (Raw first, then mapping id ordinal); all close
together after the last item plus a 30 s linger (and the linger removes what they materialised). Snapshot begin
`total > MaxConditions` ⇒ `ConditionCapacity`, the item is REMOVED (`RemoveSubscriptionItems`), counted
(`otopcua.dataconn.conditions.capacity_rejections`); host caps (`total × 49` nodes, `total × 160,997` bytes) reject the
mappings that would cross them, in deployed order; 80% warning. Nothing is materialised until every mapping completed or
`ConditionSnapshotTimeoutMilliseconds` expired (incomplete ⇒ `Unavailable`, the rest proceed, then `RefreshRequired`).
Conditions never consume `MaxProjectionNodes`.
- **Version rule (A2 N2).** Per key per epoch; `removed` and snapshot begin bypass; a removal is applied unconditionally and
forgets the key's version.
- **Lifetime rule (A2 S1).** A stream end is re-snapshot, never removal; staleness after `ConditionStaleTimeoutMilliseconds`
⇒ `MarkConnectionStale` (Quality `BadNoCommunication` through the shared delta gate: one event each, Active/Acked
unchanged). Only a COMPLETE re-snapshot that no longer lists a key removes it (an incomplete mapping removes nothing).
T2: a `state_known = false` record never changes state; a never-known condition is `UncertainInitialValue`.
- **Primary placement / SourceName (§5.2).** From deployed config only: Raw mappings before UNS, mapping id ordinal,
placement address ordinal. SourceName = `<anchor local subject>/<placement address relative to the remote root>` (root
subject learned once per stream with `GetMetadataAsync`). ConditionId depends on (connection, key) only (N4): disabling
the primary mapping moves notifiers and SourceName, nothing else.
- **EventId re-binding seam (N6) for A3b.** `ReportImported` records each consumer-minted EventId with the activation marker
it described (32 per condition); `OtOpcUaNodeManager.TryResolveImportedEvent(conditionId, eventId, out
ImportedConditionBinding)` returns connection, condition_key, primary placement, all placements, activation marker,
native flag — everything §5.6 dispatch needs.
- **RefreshRequired.** `IProjectedConditionSink.RequireRefresh` queues `RefreshRequiredEventType` to every Server-object and
wired-folder item that may see a condition of the connection.
- **ConditionRefresh.** Imported conditions are excluded from the local replay paths (plain + cut, Server object + direct)
and replayed once by `ReplayImportedConditions` through the gated marked path, ACLs on or off.
- **§5.7.** No `alerts` publication / no consumer alarm history (imported conditions are not in `_alarmConditions`, the
condition-state sink never sees them, they are not fed to `NativeAlarmProjector`), no local shelving timers
(`OnTimedUnshelve` no-op, shelve refused).
## Tests
| Project | Class | What |
|---|---|---|
| OI | `ImportedConditionEventWireTests` (7, Phase=A3) | real SDK server + real client sessions: exactly one event per transition at a projected device folder, the mapping anchor (second placement) and `i=2253`, after a sentinel; §5.2 identity fields (SourceNode = ConditionId = `c1.` id in mapped/conditions, SourceName, Severity 777 verbatim, ConditionName); **A3-SEC** with ACLs off (no grant ⇒ folder item refused, zero events live and on ConditionRefresh, positive control + RefreshEnd sentinel; a revocation drops a queued event at publish); child Read authorized through the condition (granted Good / ungranted `BadUserAccessDenied`), Acknowledge refused and unapplied; disabling the primary mapping keeps the ConditionId and the instance (notifiers + SourceName move), a later mapping changes no NodeId; folder with an event item not retired, retirement unwires; resync of unchanged state reports nothing, then a must-arrive transition exactly once; staleness = one `BadNoCommunication` event per condition, still Active, unknown records change nothing, never-known = Uncertain |
| Runtime | `GrpcDataProjectedConditionAccessTests` (8, Phase=A3) | scripted origin stream: `total > MaxConditions` ⇒ `ConditionCapacity` + item removed before anything materialises, other mapping unaffected; 2,000 conditions with `MaxProjectionNodes = 10`; host node cap rejects at begin; version gate, removal bypass + forgotten version; stream end ⇒ no removal, staleness, complete re-snapshot removes only the missing key, incomplete removes nothing; snapshot timeout ⇒ Unavailable + RefreshRequired; primary placement Raw-first/ordinal independent of stream order + SourceName + folder subject; the gate with a REAL `DataOperationPolicy` (Subscribe grant on the folder scope; not AlarmRead; mapping needs AlarmSubscribe); demand opens, linger closes and removes |
| OpcUaServer | `ImportedConditionClassifierTests` (4, Phase=A3) | **guard test**: a condition-namespace id fed to `Authorize` / `AuthorizeIfRequired` / `IsAllowedCached` / `TryAuthorizeMapped` × {Raw, Uns} × {Read, Browse, HistoryRead, Call, CreateMonitoredItems, AlarmAcknowledge}, ACL on and off, under a Cluster-wide grant — the classifier is asked every time (48), never the realm walk; positive control on a Raw id; the node manager's classifier: Read/Subscribe through the condition, HistoryRead/Call/Ack refused, invisible ⇒ denied despite the Cluster grant; rewriter drops failed / throwing markers, re-gates unmarked, empties payloads, passes v1 messages through as the same instance |
| Host | `GrpcDataV1CompatibilityTests.A3_consumer_condition_shapes_…` (Phase=A3) | recorded-v1-client gate: the fake origin now also emits begin+`total`, an info/placement record + `snapshot_complete`, a `removed` delta; header-less (scoped or not) still the golden bytes; negotiated decodes all three. `git diff master -- '*Goldens.cs'` empty |
**Mutation record (A3-SEC, OI).** Removing only the Server-object delivery gate leaves A3-SEC green: the publish-time
marker re-check drops the event (the second layer works). Removing the delivery gate AND making the marker re-check
`true` turns it red (`deniedEvents … Count` 1). Both layers are real; no single-layer test isolates the delivery gate.
## Deviations / decisions (no questions asked; reasoning recorded)
1. **Delivery reuses the node manager's report walk** instead of a separate fan-out: imported conditions are not in the
realm-keyed maps (as the plan requires), but `ReportConditionEvent`/`DeliverConditionEventAsync`/`OnConditionReportEvent`/
`DeliverToNotifierItems`/`QueueToItem` gained an imported branch. This keeps exactly-once, #838/#854/#855 semantics
without a second implementation.
2. **Demand is global, not "per connection the caller could see"**: the first admitted event item opens every
condition-bearing connection. The per-event gate still decides visibility; the cost is opening streams a caller might not
see. Simpler and fail-safe; A4 diagnostics can reconsider.
3. **Folder event-item admission** uses the imported gate of a condition wired at that folder (not the folder's mapped
Browse proof). A folder is a notifier only while a condition is wired there (N7), so a folder-only client cannot open
demand by itself — a Server-object item (or an already-wired folder) is needed. Recorded for A4.
4. **RefreshRequired** is sent on an INCOMPLETE barrier (snapshot timeout); "a ConditionRefresh before the barrier ⇒
RefreshRequired when it completes" is not tracked separately (the timeout path covers incomplete resyncs). An UNMARKED
list dropped by the rewriter is counted but the item does NOT get a RefreshRequired (the rewriter has no item handle) —
follow-up for A3b/A4.
5. **Verdict cache** keys on `AuthorityGeneration` = (mapping-set version ≪ 32) ⊕ the policy's authority epoch, plus the
condition's placement version; the policy's own decision cache sits under it. Bounded (65,536 entries, then cleared).
6. **Removal of an imported condition emits no event** (no NodeDeleted model change for the condition namespace); clients
key on ConditionId and see it no longer refreshed. The linger close removes materialised conditions (no stale state left
when no one watches).
7. **Root-leaf replacement** of a mapping anchor (`TryApplyRootLeaf`) does not unwire an imported condition wired at that
anchor (a root-leaf mapping is a variable root; conditions there have a folder parent elsewhere). Edge case, recorded.
8. **ConditionRefresh replay of imported conditions** runs under one `Lock` hold (consistent with the synchronous events it
races); at the host cap (2,500 conditions) × items this is the longest hold A3a adds — L2/L3 live measurements should
include it. Apply is chunked at 128 updates per hold; the folder index is one scan of projected nodes per apply batch.
9. **Primary endpoint** for condition items (A2 N7: a Secondary advertises but refuses) is left to the connection source's
existing endpoint selection; a Secondary answers the item `Unavailable`, the mapping is `Unavailable` and retried on the
next stream. A3b/A4 should prefer the Primary explicitly.
10. **A3 OI tests** run outside the unit-phase runner (it accepts unit projects only), as for H1/H3.
## Gates
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` (Runtime + OpcUaServer + Host) | passed (`20261124T214213…`) |
| `run-unit-phase.py A2` | passed |
| `run-unit-phase.py A1`, `X0` | passed, passed |
| Host.Tests DataConnections (both v1 gates) | 207 passed |
| OI `ImportedConditionEventWireTests` | 7 passed |
| OpcUaServer.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 1455 passed, 1 skipped |
| Runtime.Tests full (same filter) | 2030 passed, 3 skipped (no #920 rerun needed) |
| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 116 passed |
| `git diff master -- '*Goldens.cs'` | empty |
Live rig: not run for A3a (no consumer-side condition demand exists until a client subscribes, and A3b + the exit gate
own the live leg); the unit + OI wire tests above use a real SDK server and real client sessions.
## Left for A3b
- §5.6: `ICallAsyncNodeManager` on the node manager (claim / `base.Call` / await, never under `Lock`), dispatch through
`TryResolveImportedEvent` → `IDataConditionMethodService` on the connection, no local apply before the origin record,
unknown EventId ⇒ `BadEventIdUnknown` unsent, native Confirm ⇒ `BadNotSupported` unsent, lock-freedom (L3), binding the
mapping's `ConditionMethodTimeoutMilliseconds`. Today every Part 9 method on an imported condition is refused
(`BadNotSupported` handlers; the classifier also refuses `Call` / alarm operations).
- RefreshRequired to an item whose UNMARKED list the rewriter dropped (deviation 4); explicit Primary endpoint for
condition items (deviation 9); the mapping-change runner hand-over (an old runner's in-flight batch can still reach the
sink until its cancellation is observed — bounded by one frame).
---
# A3 — PART 2 (A3b): methods on imported conditions, no `Lock` waits; A3 exit (L2, L3, live)
2026-11-24, branch `a3-consumer`, on top of A3a (`b5ab6e7c`). Not merged, not pushed.
## Progress log
1. `c1be5725` NM: `ICallAsyncNodeManager` (`OpcUaServer/ImportedConditionMethods.cs`), EventId registry gate, N6 re-binding.
2. `28098a8d` Runtime/Host: `ProjectedConditionAccess : IProjectedConditionMethods` (`ProjectedConditionAccess.Methods.cs`), the
runner's stream serving identity, `DataConnectionDeploymentLease : IDataConditionMethodService`, host wiring.
3. `de51886d` OI wire tests; `2d0147f9` Runtime tests + `A3` manifest; `fecb178e` L2 harness + byte cap.
4. `4e6535ee` live smoke (`conditions_a3_smoke.py`, seeder conditions profile makes the CONSUMER condition-bearing).
5. Live `a3b-cond-1` / `-2` FAILED and found two A3a integration defects, fixed in `404a664c` (logger) and `82ecc116` (root view);
live `a3b-cond-3` PASS.
## What is implemented (A3b, plan §5.6)
- **Interception (step 1).** Verified against the pinned SDK 2.0.1 (ilspy): `CustomNodeManager2` has a public virtual
`CallAsync(OperationContext, ArrayOf<CallMethodRequest>, IList<CallMethodResult>, IList<ServiceResult>, CancellationToken)` but
does NOT declare `ICallAsyncNodeManager`, so `AsyncNodeManagerAdapter.CallAsync` ran the synchronous `Call`. NM now declares
`ICallAsyncNodeManager` and overrides `CallAsync`: (a) claims every unprocessed request whose ObjectId is in the
`mapped/conditions` namespace — a namespace-index test, **no lock at all** — and marks it `Processed`; (b) calls
`base.Call(...)` unchanged (it skips the claimed ones; local behaviour incl. `ReportAfterMethod` under `Lock` is unchanged),
completed before any remote await; (c) runs the claimed calls concurrently and awaits them. No `Lock` is held at any point;
the SDK pre-validation `FindMethodState` takes `Lock` only for its lookup (plan's residual).
- **Local checks (step 2), no I/O, no NM `Lock`:** condition resolved from the ObjectId (`TryParse`, lock-free registry
`Find`) else `BadNodeIdUnknown`; method from the MethodId — the type declarations (`AcknowledgeableConditionType_Acknowledge`
/ `_Confirm`, `ConditionType_AddComment`) or this condition's instance child (`c1.…/Acknowledge` etc.); anything else
(shelve, enable/disable) `BadNotSupported`; no port ⇒ `BadNotSupported`; **per-caller mapping gate**
`IProjectedConditionMethods.AuthorizeMethod(local caller, placements, method)` ⇒ `BadUserAccessDenied` unsent; native
Confirm ⇒ `BadNotSupported`; the origin's `supported_methods` (kept from the listing) lacks the method ⇒ `BadNotSupported`;
Warm Standby ⇒ the standby refusal; argument shape (`BadArgumentsMissing` / `BadTooManyArguments` / `BadTypeMismatch`);
**EventId**: must be one this consumer minted for that condition AND bound to the CURRENT marker, else `BadEventIdUnknown`
unsent. The EventId registry (`RecentEvents`, 32 per condition) and `Activation` are now read/written under a per-condition
`MethodGate` (the plan's "small registry with its own lock"); `TryResolveImportedEvent` also uses it instead of `Lock`.
- **The gate** (`ProjectedConditionAccess.AuthorizeMethod`, real `DataOperationPolicy`): for a placement in primary order whose
mapping is current, condition-bearing, of the placement's realm and itself grants the method's bit (AlarmAcknowledge for
Acknowledge/AddComment, AlarmConfirm for Confirm): `AuthorizeLocal(caller, AlarmAcknowledge|AlarmConfirm, folder scope)`,
which re-checks the caller's key (#563); regardless of `Security:Acl:Enabled` (as the A3a visibility gate). Returns the
placement to dispatch through and that mapping's `ConditionMethodTimeoutMilliseconds`.
- **Dispatch (steps 4–5).** Bounded by a per-node semaphore (8; waiting counts against the budget, exhausted ⇒
`BadTooManyOperations` unsent). Budget = min(request `OperationDeadline`, the mapping's method timeout). A fresh operation id
(`a3-<guid>`) per dispatch; **an identical call already in flight** (same caller, condition, EventId, method, comment) **joins**
it — one dispatch, the same answer. The port call is bounded by budget + 250 ms (`WaitAsync` + `CancelAfter`). The Runtime
addresses the origin with the placement, `expected_activation` = the latest applied marker, `expected_serving_incarnation` =
the serving identity of the CURRENT condition stream (`IDataSubscriptionProvenance`), `on_behalf_of` = the local principal,
through the deployed lease (`DataConnectionDeploymentLease` now implements `IDataConditionMethodService`: the row's
AlarmAcknowledge/AlarmConfirm bit else `UnauthorizedAccessException` ⇒ `BadUserAccessDenied`, unsent). No open condition stream
(connection down / never opened) ⇒ `BadNoCommunication`, nothing leased or sent.
- **No local apply.** Imported conditions keep their A3a `BadNotSupported` SDK handlers; nothing in the claimed path touches
node state. The node changes only when the origin's record arrives on the condition stream.
- **Outcome mapping (documented choice).** `DriverConfirmedSuccess` (scripted) / `AcceptedUnconfirmed` (native) ⇒ `Good` (the
client may see Good before the confirming event); `RejectedBeforeDispatch` ⇒ the origin's status (+ its diagnostic);
**`OutcomeUnknown` ⇒ `BadTimeout` when the budget elapsed, otherwise `BadCommunicationError`**, always with
"OutcomeUnknown: …" in the diagnostic and a Warning log. Chosen over an Uncertain code: Part 4 gives a Call result no
"maybe applied" Uncertain meaning, and an Uncertain-family status reads as success to most clients; a Bad status plus the
confirming (or absent) condition event is the honest answer. Never retried.
- **N6 re-binding** (`RebindImportedEventIds`). After a record that changed no state: a moved marker re-binds retained EventIds
only when the record's `time` equals the time they were bound under (F6); otherwise a fresh EventId bound to the new marker is
stamped on the node (what a ConditionRefresh now returns) and `RequireRefresh(connection)` is queued after the apply
(outside `Lock`). A condition whose first record reported no event gets one bound EventId.
## A3a defects found by the live gate (fixed)
1. **`ProjectedConditionAccess` logged to `NullLogger` in production** (DI passed no logger): the first live failure
(`a3b-cond-1`, nothing imported) left no trace. Now the host logger; plus Information logs for stream open (serving), a
refused item (Warning, status + diagnostic) and each snapshot barrier (statuses, record count, timeout).
2. **The UNS root item was refused `Denied`** (`a3b-cond-2`: `map-uns item refused by the origin (Denied)`, `map-raw` Complete,
0 records). The item view was built from the anchor address with subject = the address identifier (an opaque EquipmentId);
the origin requires its own subject (`area/line/plc`). Now metadata is asked exactly as `RemoteNamespaceResolver` asks it
(subject = `RemoteRootEntityId`) and the item carries the origin's canonical view from the metadata answer. Pinned by
`The_condition_item_carries_the_origins_canonical_root_view_learned_from_metadata` (red with the item view reverted).
The A3a unit tests could not see either: their fake origin accepted any view.
## Tests (A3b)
| Project | Class | What |
|---|---|---|
| OI | `ImportedConditionMethodWireTests` (7, Phase=A3) | real SDK server + client sessions; the port fakes the origin: **once + join** (duplicate in-flight call joins, one dispatch, both Good; still unacked until the origin record; record ⇒ acked; a later call = new dispatch, fresh op id); **child Call** via the instance method id, denied caller `BadUserAccessDenied` unsent, re-gated per local caller, Acknowledge grant ≠ Confirm; **unknown / superseded EventId** `BadEventIdUnknown`, native Confirm + OneShotShelve `BadNotSupported`, all unsent, positive control carries the current marker; **N6** same-time resync re-binds, other-time resync ⇒ old EventId unknown + fresh ackable EventId; **L3 lock-freedom**; **mixed batch** (local native Ack through `base.Call` = Good + routed once + one local ack event, imported Ack dispatched, imported unchanged); **timeout** (300 ms mapping timeout ⇒ `BadTimeout` < 3 s, port cancelled, one dispatch), OutcomeUnknown ⇒ `BadCommunicationError`, refusal statuses passed through (`BadInvalidState`, `BadNoCommunication`), nothing applied |
| Runtime | `GrpcDataProjectedConditionMethodTests` (5, Phase=A3, manifest `A3`) | gate with a real `DataOperationPolicy` (AlarmAcknowledge ⇒ Ack/AddComment not Confirm; Subscribe-only ⇒ denied; mapping lacking the bit ⇒ denied; mapping timeout 4321 ms carried; unknown mapping/caller/null denied); no open stream ⇒ `BadNoCommunication`, never leased, nothing sent; call carries the stream's serving incarnation, placement, marker, op id, budget, on-behalf-of; OutcomeUnknown passed through; connection down after a stream end ⇒ `BadNoCommunication`, nothing sent; lease refusal ⇒ `BadUserAccessDenied` unsent; canonical root view |
| OI | `ImportedConditionMemoryMeasurementTests` (opt-in `OTOPCUA_A3_L2=1`, Category=Perf) | L2 harness |
OI suites run outside the unit-phase runner (it accepts unit projects only), as for A3a.
**Red-on-revert (each mutation built, run, restored; `git status` clean after):**
| Mutation | Test | Result |
|---|---|---|
| M1: port call waited synchronously under `lock (Lock)` | L3 lock-freedom | **red** (the first Read/Browse waited out the 5 s stall: `ack.IsCompleted` already true) |
| M2: in-flight join disabled | once + join | **red** (joined count never 1) |
| M3: `AuthorizeMethod` verdict ignored | child Call gate | **red** (denied caller got Good) |
| M4: EventId marker check ignored | unknown/superseded EventId | **red** (superseded EventId accepted) |
| M5: mapping timeout ignored (30 s budget) | timeout | **red** (elapsed > 3 s) |
| M6: N6 re-bind disabled | re-binding | **red** (same-time resync EventId refused) |
| M7: `base.Call` skipped when anything is claimed | mixed batch | **red** (local Ack not Good) |
| R1: no-stream check removed (Runtime) | connection down | **red** |
| R2: mapping-bit check removed (Runtime) | gate | **red** |
| R3: item view reverted to the address-only view | canonical root view | **red** |
| native-Confirm check removed (not run) | — | expected **masked**: `supported_methods` of a native condition (Native = 3) lacks Confirm, a second layer refusing the same call `BadNotSupported` unsent |
## L3 — lock-freedom (§9.3, hard gate) — PASS
Measured by the OI wire test (in-process, real SDK server; the origin's method handler is stalled 5 s at the consumer's
`IProjectedConditionMethods` port — the consumer-side boundary, below which everything is the remote origin). 10 rounds of
concurrent Read (raw variable), Browse (Plant folder) and a data Publish (value write → client notification, publishing interval
20 ms) while the call is in flight, plus `Monitor.TryEnter(Lock)` from the test thread; `AckedState` asserted false after every
round; the origin record applied after release flips it (positive control). Three runs:
| Run | Stall | Read max | Browse max | Data Publish max | `Lock` acquire max | Baseline (no stall) read / browse / publish |
|---|---|---|---|---|---|---|
| 1 | 5003 ms | 1.8 ms | 1.2 ms | 99.7 ms | 0.01 ms | 1.3 / 5.0 / 105.8 ms |
| 2 | 5003 ms | 1.9 ms | 6.3 ms | 98.6 ms | 0.01 ms | 1.3 / 4.6 / 107.7 ms |
| 3 | 5002 ms | 2.6 ms | 1.1 ms | 99.7 ms | 0.01 ms | 1.2 / 5.4 / 105.9 ms |
All < 200 ms. The ~100 ms publish figure is the server's minimum publishing interval (identical without a stall), not a delay.
Deviation: the plan lists L3 as a docker-dev measurement; the live rig has no hook to stall the origin's handler, so the gate is
this deterministic in-process measurement (its mutation M1 proves it detects a `Lock` wait).
## L2 — consumer memory, 1,000 imported conditions in one mapping (§9.3) — PASS
In-process harness (`ImportedConditionMemoryMeasurementTests`, opt-in): a running SDK server, 1,000 conditions materialised through
the real `IProjectedConditionSink` (nodes + instance-scoped children, ids, registry + folder/notifier indexes, one more transition
each so every N6 EventId slot is used, the verdict cache exercised once per condition) plus the update records the runtime keeps per
key. Forced compacting GCs before/after. Three runs:
| Run | Working-set growth | Managed heap growth | per condition (heap) | materialise / transition |
|---|---|---|---|---|
| 1 | +107.1 MiB | +197.4 MiB | 207,036 B | 605 / 80 ms |
| 2 | +106.2 MiB | +197.4 MiB | 207,029 B | 704 / 91 ms |
| 3 | +112.2 MiB | +197.4 MiB | 207,029 B | 747 / 77 ms |
| 4 (after-materialise split) | +106.8 MiB | +196.1 MiB | 205,665 B (204,612 after materialise alone) | 602 / 83 ms |
Working-set growth ≤ 200 MiB: **PASS** (the heap grows more than the working set because the process had already committed GC
regions at baseline). Per the plan, `MaxImportedConditionBytes` is now set from the measurement: `BytesPerCondition` 160,997 →
**205,665** (the managed-heap figure, the larger of the two) and the default `DataConnections:MaxImportedConditionBytes` =
205,665 × 2,500 = **514,162,500 B (≈ 490 MiB)** (was 400 MiB). `MaxConditions` (1,000 per mapping) needs no lowering.
Nearly all of it is the SDK condition node + children (X0's node-only figure was 160,997); the A3b EventId registry adds ~1 KB.
## Live — run `a3b-cond-3` (build `82ecc116`, clean tree) — PASS
```bash
python3 scripts/validation/grpc-data/rig.py up --run-id a3b-cond-3 --conditions --timeout 1200
python3 scripts/validation/grpc-data/rig.py seed --run-id a3b-cond-3
# ~90 s for CONTROL's ClusterNode contact refresh
python3 scripts/validation/grpc-data/rig.py deploy --run-id a3b-cond-3 --timeout 300
python3 scripts/validation/grpc-data/conditions_a3_smoke.py --run-id a3b-cond-3
python3 scripts/validation/grpc-data/rig.py down --run-id a3b-cond-3
```
The conditions profile now also makes the CONSUMER condition-bearing (connection + both mappings carry 64|128|256; ConfigDb
showed 479 on both). `conditions_a3_smoke.py` raises ScalarHigh, runs CLI `alarms --refresh` on the SOURCE Primary (origin's own
subscriber) and the CONSUMER Primary, acks through the consumer with CLI `ack`, then clears.
| Item | Observed | Result |
|---|---|---|
| Consumer import | `stream 1 … opened (2 mapping(s), serving source-1:4053)`; barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`; consumer CLI shows ScalarHigh Active/Unacknowledged with ConditionNodeId `ns=6;s=c1.…` (mapped/conditions) and a consumer EventId | PASS |
| Bogus EventId via the consumer | `Acknowledge failed: BadEventIdUnknown [0x809A0000]`; origin shows no ack | PASS |
| Ack via the consumer (CLI `ack`) | `Acknowledge successful` in 580 ms | PASS |
| Origin audit (source-1) | `Data-connection condition method Acknowledge by fixture-consumer (key …) on Uns:…:source-scalar-high op a3-1eabf280…: DriverConfirmedSuccess 0x00000000; on behalf of fixture-cli` — the service principal, the consumer's fresh op id, the local caller as on-behalf-of | PASS |
| Origin's own subscriber | ScalarHigh: Active/Unacknowledged, **exactly one Active/Acknowledged** | PASS |
| Consumer subscriber | Active/Unacknowledged, **exactly one Active/Acknowledged** (the origin's record re-imported) | PASS |
| Teardown | no run-labelled containers / networks left | — |
Failed attempts (history): `a3b-cond-1` — nothing imported, no log (A3a defect 1); `a3b-cond-2` — map-uns Denied (A3a defect 2).
Each fix changed the image inputs, so each run was torn down and a fresh run id brought up.
## Deviations / decisions (A3b)
1. **EventIds retained: 32** (A3a's `RecentEventIds`), not the plan's "last N (default 8)"; validity is "minted for this condition
under the current marker", as §5.6 step 3 specifies.
2. **Consumer-side join of identical in-flight calls** (the brief's "duplicate call joins"): each dispatch has a fresh operation id
(the origin's own registry joins duplicates of an id); two identical local calls in flight share one dispatch. A repeat after
completion is a new dispatch (no retry, no stale join).
3. **Dispatch placement** = the first placement (primary order) the CALLER passes the method gate on, not unconditionally the
primary placement: a caller authorized only via a second mapping is addressed through that mapping's placement.
4. **`expected_serving_incarnation`** = the serving identity of the condition stream the records arrived on (no stream ⇒
`BadNoCommunication`, unsent). A stream that does not expose provenance cannot be called through (production streams do).
5. **OutcomeUnknown ⇒ Bad** (`BadTimeout` / `BadCommunicationError`), see "Outcome mapping".
6. **The node manager enforces the mapping timeout itself** (budget + 250 ms grace around the port), so a port that never answers
cannot hold a request past it; the Runtime passes the budget to `GrpcDataConnection`, whose own ceiling still applies.
7. **L3 measured in-process** (see L3). **L2 measured in-process** (allowed by the brief).
8. Defaults changed at the A3 exit: `BytesPerCondition` 205,665, `MaxImportedConditionBytes` ≈ 490 MiB (L2).
9. Two A3a files were edited beyond A3b's seams because the live gate required it: the ProjectedConditionAccess DI logger and the
condition item root view (defects above); plus the per-condition `MethodGate` and N6 re-binding hook in `ApplyImported` /
`ReportImported` / `TryResolveImportedEvent`.
## Open / follow-ups
- RefreshRequired after an un-re-bindable resync goes to every item that may see the connection's conditions (A3a's
`RequireRefresh`), not only the affected mapping's notifiers.
- The A3a deviation 9 (explicit Primary endpoint for condition items) is still open; the live run happened to stream from the
Primary (source-1).
## Gates (A3b, at `82ecc116`)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` (Runtime + OpcUaServer + Host) | passed (`20261124T225624…`) |
| `run-unit-phase.py A2` | passed (`20261124T225724…`) |
| `run-unit-phase.py A1` | passed (`20261124T225845…`) |
| `run-unit-phase.py X0` | passed (`20261124T230234…`) |
| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2035 passed, 3 skipped (no #920 rerun needed) |
| OpcUaServer.Tests full (same filter) | 1455 passed, 1 skipped |
| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 123 passed, 1 skipped (the opt-in L2 harness) |
| OI `ImportedConditionMethodWireTests` ×3 | 7/7 each |
| `git diff master -- '*Goldens.cs'` | empty |
| Live `a3b-cond-3` | PASS (above) |
---
# A3 — Review round 1 (A3a adversarial review, `a3a-review-round1.md`, written against `b5ab6e7c`)
2026-11-24, branch `a3-consumer`, on top of A3b (`3c941458`). Not merged, not pushed. Commits: `69aeeb77` (runner + NM fixes,
Runtime tests), `14343bf0` (folder promotion for folder-only demand, NM tests).
"Red on revert": the test was run with the fix removed (Runtime: the whole HEAD runner restored with interface stubs; NM: the
single fix line(s) removed by a scripted mutation) and failed; the fix was then restored and the test passed.
| Finding | Resolution | Test(s) | Red on revert |
|---|---|---|---|
| **B1** in-stream re-snapshot removes conditions | `ProjectedConditionAccess.Runner.cs`: a begin opens a per-mapping `Buffer`; snapshot records fill it; the committed `Live` set (and every node) is untouched until `snapshot_complete`, which swaps and re-merges old ∪ new keys — only a key the complete set no longer lists (and no other mapping lists) is removed. Deltas apply to `Live` and the buffer. An in-stream capacity refusal removes the mapping's keys once (keys another mapping lists survive) and requires refresh | `B1_an_in_stream_multi_frame_re_snapshot…` (begin + 2 record frames + positive control on map-b, then complete); `B1_an_in_stream_re_snapshot_over_capacity…` | yes / yes (refresh assertion; the removal shape itself was already right) |
| **B2** timed-out / non-Good mapping frozen Good | frames of a timed-out mapping keep being processed: a late `snapshot_complete` swaps in and re-runs the merge (full re-diff); at an incomplete barrier the keys no contributing mapping lists are `MarkConditionsStale` (new sink method, `BadNoCommunication`, one event each, never removed); after the barrier a still-`Unavailable` mapping ends the stream after a bounded wait (`ConditionSnapshotTimeout` × 1,2,4,8 backoff), cancelled by a late completion | `B2_a_snapshot_completing_after_the_timeout…`; `B2_an_incomplete_barrier_marks…`; `B2_S7_a_refused_item…` (new stream within 5 s) | yes / yes / yes |
| **Deviation 9** Primary endpoint | new `IDataPrimarySubscriptionSource.SubscribePrimaryAsync` (Abstractions) on `GrpcDataConnection` (skips a non-Primary endpoint; a role-only miss is not a discovery failure, no probe backoff) and the deployment lease; the runner uses it and also drops any stream whose provenance role is not Primary | `Deviation9_a_condition_stream_served_by_a_Secondary…` | yes (hangs: the old runner keeps the Secondary stream) |
| **B3** revalidation stands down folder items; demand leak | `RevalidateEventItems` asks `ImportedNotifierAdmits` for a projected notifier; the unsubscribe arm releases demand before both early returns; `_authorizer?.LogFiltered` (a rig without an authorizer NRE'd once an item was stood down) | `B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand` (real `RevalidateMonitoredItems()`, lease counter) | yes (revalidation mutation) / yes (demand-order mutation) |
| **B4** host caps per connection / order / trust `total` | one node-wide `ConditionLedger`: connection charge = max(materialised keys, Σ mapping claims); a claim is the admitted `total` while snapshotting, the record count after (growth is charged); admission is against everything charged or claimed, order-independent. Records past `total`, `Live` past `MaxConditions`, or growth past the node caps ⇒ `ConditionCapacity` (item removed, keys removed, refresh). `ChargedConditions` observation | `B4_the_host_caps_are_node_wide_across_connections`; `B4_admission_is_order_independent…`; `B4_records_past_the_snapshot_total…`; `B4_post_snapshot_delta_growth…` | yes ×4 |
| **S1** rebuild leaves stale wiring | `RebuildAddressSpace` calls `UnwireAllImportedFolders()` before clearing; `WiredByFolder` keeps the promoted folder INSTANCE — a re-created folder with the same NodeId unwires the dead instance and is promoted afresh | `S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again` | yes (rebuild-unwire removed), yes (both removed) |
| **S2** verdict cache outlives expiry / IsActive | `Verdict` stores `ValidUntil` = min(credential expiry, now + 5 s) for a positive verdict; `AuthorityGeneration` folds every current mapping's `Authority.IsActive` | `S2_a_cached_positive_verdict_is_re_proved…` (OpcUaServer.Tests); `S2_an_authority_deactivation_moves_the_authority_generation…` (Runtime) | yes / yes (by construction: the old formula ignores IsActive) |
| **S3** removal races a new runner | a new runner of a connection awaits its predecessor's `Stopped` (loop end + removal) before opening a stream; stopped runners are kept per connection in `_stopping` | `S3_a_new_runner_waits_for_the_old_runners_removal…` (the sink holds the old removal open 400 ms) | yes |
| **S4** `TakeMaterialised` cross-thread | the materialised set is handed over inside the new runner's loop after the predecessor stopped (no concurrent mutation, no orphaned key) | `S4_a_mapping_change_hands_the_materialised_set_over…` | **no** — the race window is one in-flight frame; the test pins the hand-over, it cannot force the interleaving |
| **S5** Lock-hold bounds | `ProjectedFolderIndex()` scan replaced by the incremental `FolderIds`/`FolderKeys` index (maintained in `OnProjectedFolderMaterialised`/`Removing`, cleared on rebuild, resolved against the live projected maps); refresh targets gathered 128 conditions per hold, visibility decided off Lock | covered by every OI wiring test (index correctness); no timing test | n/a (not behaviour-observable) |
| **S6** metadata failure swallowed | a root whose metadata is not Good (or a failed call) is `Unavailable` (logged), its item is not opened; all roots failing ends the stream | `S6_a_root_whose_metadata_fails…` | yes |
| **S7** RefreshRequired only on timeout | any incomplete barrier (a mapping not `Known`: timed out, refused, metadata) requires refresh | `B2_S7_a_refused_item…` (`RefreshRequired == 1`) | yes |
| **Deviation 3** folder-only demand | event items on any projected folder are admitted through `ImportedNotifierAdmits` = a wired condition the caller sees, OR the mapping gate on the folder's own (mapping, subject) key (`IProjectedConditionAccess.CanSubscribeFolder`); projected folders of a condition-bearing mapping (`IsConditionBearingMapping`) are `SubscribeToEvents` from materialisation (the SDK answers `BadNotSupported` before `SubscribeToEvents` otherwise) and never demoted by an unwire | `Deviation3_a_folder_only_client_opens_demand…` (granted Good + demand + the condition then delivered; anonymous denied) | yes (promotion removed ⇒ `BadNotSupported`) |
| **Deviation 6** removal tells nobody | `RemoveConditions` captures the items that may see the conditions BEFORE unwiring, removes, then queues `RefreshRequired` (off Lock) to those passing the gate. `RequireRefresh`'s early return on a connection with no conditions stays: nothing of it can be held any more — the removal itself now notifies | `Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it` (Server + folder get it; a map-b folder item does not, after a must-arrive control) | yes |
| **Deviation 8** one-hold replay | `ReplayImportedConditions` runs 128 conditions per Lock hold; each condition's snapshot and its queueing share a hold (ordering vs. live events kept) and one `EventDeliveryCache` per snapshot is shared across items | `Deviation8_ConditionRefresh_replays_hundreds…` (300 conditions inside RefreshStart/End) | **no** — chunking is not observable; the test guards correctness of the chunked replay |
| **A3b open item** RefreshRequired scope after an EventId-invalidating resync | `ApplyConditions` collects the un-re-bindable CONDITIONS and refreshes only the items that may see one of them (shared `QueueImportedRefresh`) | via the shared targeting in `Deviation6_…` (a folder item of another mapping is not refreshed); the A3b re-binding test still passes | not separately reverted |
| NIT `IsWiredTo` reads `Folders` off Lock | `ImportedCondition.WiredFolders` immutable array, replaced under Lock on wire/unwire | — | n/a |
| NIT `Infos` never pruned | `ConditionSet.Apply` drops the info with a removed key; a swap discards the old set | — | n/a |
| NIT stale callback after a fresh barrier | stale mark and barrier serialize on the runner's stale gate + generation | — | n/a (race) |
| Test adequacy: vacuous absence assertions | `Applied.ShouldBeEmpty` / `Removed.ShouldBeEmpty` now follow a must-arrive control (a later frame's item removal; the barrier) | the three original tests rewritten | — |
| Test adequacy: delivery gate not isolated | `ImportedConditionDeliveryGateTests` (non-parallel collection): the denied Server-object session gets nothing AND `ProjectedEventFieldList.DroppedOnPublish` does not move | `A3_SEC_the_delivery_gate_alone_withholds…` | yes — removing only the Server-object delivery gate turns it red while the original A3-SEC test stays green |
Residual / recorded:
- A projected folder materialised while its mapping was NOT condition-bearing (or before `ProjectedConditionAccess` is bound) is
not promoted until it re-materialises; the host binds access before any projection deploys.
- The B2 retry ends the whole stream (complete mappings re-snapshot too), bounded by the backoff; a per-item re-add is A4 material.
- In-stream capacity refusal removes the mapping's keys (all-or-nothing, §5.5) rather than keeping them stale.
## Gates (review round 1, at `14343bf0`)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` | passed (`20261124T234716…`) |
| `run-unit-phase.py A2` | passed (`20261124T234814…`) |
| `run-unit-phase.py A1` | passed (`20261124T234927…`) |
| `run-unit-phase.py X0` | passed (`20261124T235258…`) |
| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2049 passed, 3 skipped (no #920 rerun needed) |
| OpcUaServer.Tests full (same filter) | 1456 passed, 1 skipped |
| OI `Feature=GrpcData` + ConditionMethodEvent / NativeAlarmEventIdentityFieldDelivery / FolderConditionRefresh / ConditionRefreshDeferral | 129 passed, 1 skipped in 2 of 4 runs; the other 2 runs failed 2 and 6 of the #854 deferral stress tests (`ConditionRefreshDeferralWireTests` / `FolderConditionRefreshWireTests` `Deferred_events_older_than_a_refresh…`, `A_condition_removed_during_a_plain_refresh…`) — **pre-existing**: the same suite at the unchanged base `3c941458` failed 2 of them in 1 of 3 runs; the classes pass 3/3 in isolation on this branch; no imported-condition code is reached in those rigs (no `ProjectedConditionAccess`). Root cause not established (load-sensitive local-condition deferral) — to be filed as an issue, not closed as a flake |
| `git diff master -- '*Goldens.cs'` | empty |
## Live — run `a3r1-cond-1` (build `14343bf0` + docs) — PASS
Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, ~88 s, deploy, `conditions_a3_smoke.py`, `rig.py down`).
Consumer: `stream 1 for connection consumer-source opened (2 mapping(s), serving source-1:4053)` (the Primary, now via
`SubscribePrimaryAsync`); barrier `map-raw=Complete, map-uns=Complete; 1 record(s)`. Bogus EventId ⇒ `BadEventIdUnknown`; ack
through the consumer `Acknowledge successful` (608 ms); origin subscriber and consumer subscriber each saw exactly one
Active/Acknowledged. Teardown: no run-labelled containers or networks left.
---
# A3 — Review round 1 (A3b adversarial review, `a3b-review-round1.md`, written against `3c941458`)
2026-11-25, branch `a3-consumer`, on top of the A3a fix round (`01a4e8db`). Not merged, not pushed. Commits: `72dece7f` (fixes +
tests), `perf(grpc-data): … BytesPerCondition` (L2 re-derivation), this docs commit.
"Red on revert": the single fix was removed by a scripted mutation (`mut.py`, one mutation per build), the named test run and seen
red, the file restored (`git status` clean after the 19 mutations).
| Finding | Resolution | Test(s) | Red on revert |
|---|---|---|---|
| **S1** a throw after `base.Call` faults the batch | `CallAsync` runs each claimed item through `CallImportedGuardedAsync` (never faults, a synchronous throw included) and collects per-item results; a fault before the port is called ⇒ that item's `BadInternalError`, unsent (logged); `DispatchImportedAsync` answers every post-dispatch failure itself | `A_fault_before_dispatch_is_a_per_item_BadInternalError…` (gate throws: imported-first batch ⇒ `[BadInternalError, Good]`, local ack routed once, nothing sent; a pre-validation failure (`MethodId` null) answered per item beside a dispatched call; a port THROWING after dispatch ⇒ `BadCommunicationError`, one dispatch) | yes (both catch-alls removed ⇒ ServiceFault) |
| **S2** mapping timeout capped at 5 s; BadTimeout inferred | the mapping's `ConditionMethodTimeoutMilliseconds` is honoured (up to the validator's 3,600,000 ms): it rides `RemainingBudget`, and `GrpcDataConnection.ConditionMethodTimeout` defaults to that validator ceiling (`MaxConditionMethodTimeout`) instead of 5 s. The client maps gRPC `DeadlineExceeded` ⇒ `OutcomeUnknown` + `BadTimeout`; `MapOutcome` takes the transport's status (BadTimeout stays BadTimeout, anything else unknown ⇒ BadCommunicationError) — no clock comparison | Runtime `Without_a_connection_ceiling_the_deadline_is_the_requests_budget_not_a_hidden_5s` (8 s budget ⇒ grpc-timeout > 6 s); `A_deadline_passing_after_send_is_OutcomeUnknown_with_BadTimeout_known_not_inferred`; OI timeout test: port answers `OutcomeUnknown/BadTimeout` at once ⇒ `BadTimeout` | yes / yes / yes |
| **S3** unsent / definite failures labelled unknown | cancel while waiting for a slot ⇒ `BadRequestCancelledByClient` unsent; an invalid request is `RejectedBeforeDispatch` `BadInvalidArgument` in `ProjectedConditionAccess.CallAsync` (before the lease) and in the client (never thrown); `DriverConfirmedFailure` ⇒ the origin's status (+ diagnostic) | Runtime `An_invalid_request_is_refused_unsent_before_the_lease` (not even leased); client `An_invalid_request_is_RejectedBeforeDispatch_never_thrown`; OI timeout test (`DriverConfirmedFailure`/`BadConditionAlreadyEnabled` passes through) | yes / yes / yes. Slot-wait cancellation: **not tested** — the SDK 2.0.1 server gives no client-driven way to cancel an in-flight Call (no Cancel wiring into `OperationContext.CancellationToken` found); by inspection only |
| **S4** no fairness; dispatch with a few ms left | per-connection sub-limit `DefaultImportedMethodConcurrencyPerConnection = 4` inside the node-wide 8 (connection slot first, then node slot, both released in `finally`); a dispatch with < `ImportedMethodMinimumDispatchBudget` (250 ms) left is `BadTimeout` UNSENT (checked before the waits and again after them). Per-principal fairness not added (a principal is bounded by the per-connection limit; documented) | `One_stalled_connection_cannot_starve_another_and_its_excess_calls_are_BadTooManyOperations_unsent` (8 stalled calls on conn-a: 4 dispatched, 4 `BadTooManyOperations` unsent, a conn-b call Good < 1.5 s — slot exhaustion included); `A_request_deadline_below_the_dispatch_floor_is_BadTimeout_unsent` (TimeoutHint 450 ms ⇒ unsent; 2,000 ms ⇒ dispatched with budget ≤ 1,750 ms) | yes / yes |
| **S5 L3** stall below the port only | the L3 test is now a Theory: `realPath: true` puts a REAL `ProjectedConditionAccess` (runner, serving incarnation, lease) and a REAL `GrpcDataConnection` (capabilities, eligibility, deadline, HTTP/2 gRPC framing) between the node manager and an in-process origin whose `CallConditionMethod` handler stalls 5 s (`RealConditionMethodPath`); only the condition stream is a quiet stand-in carrying Primary provenance. The per-caller gate stays the fake (pinned by the Runtime gate tests) | L3 numbers below | yes (M1 on the real path: port awaited under `Lock` ⇒ both cases red) |
| **S5 L2** not worst case | harness now: two placements per condition (two mappings, both folders wired), all 32 EventId slots filled (asserted), three event items (Server object + both folders, publishing off, queue 1000), runner Live + Buffer record copies; max of three runs, rounded up: `BytesPerCondition` 205,665 → **230,000**, `MaxImportedConditionBytes` default = 230,000 × 2,500 = **575,000,000 B (≈ 548 MiB)** | L2 numbers below | n/a (measurement) |
| **S6** test gaps | RefreshRequired after an un-re-bindable resync asserted over the wire (Server-object item receives `RefreshRequiredEventType`); native Confirm with a listing that HAS Confirm (still refused) and scripted lacking it (refused) / having it (dispatched); real gate: first authorized placement of several, realm mismatch, unknown mapping, ungranted folder; Warm standby refusal; different principals never join; imported-first mixed batch; batch with a pre-validation failure; throwing port; slot exhaustion; the `cancelled` flag is written/read with `Volatile` | `A_resync_that_cannot_re_bind_sends_RefreshRequired…`; `Native_Confirm_is_refused_even_when_listed…`; Runtime `The_gate_routes_through_the_first_authorized_placement_and_refuses_a_realm_mismatch`; `A_warm_standby_refuses_an_imported_method_unsent`; `Identical_calls_from_different_principals_do_not_join`; S1/S4 tests above | native guard yes; supported-methods guard yes; gate (stop at first refusal) yes; standby yes; principal dropped from the join key yes. **ACL-on gate variant: not added** — `AuthorizeMethod` has no `Security:Acl:Enabled` input at all (`DataOperationPolicy.AuthorizeLocal` regardless of the flag, by design §5.6); the mixed/fault batches run with enforcement on. **Mid-call cancel: not tested** (see S3) |
| **N1** `bounded` not cancelled on TimeoutException | `bounded.Cancel()` in the `TimeoutException` catch | timeout test (`cancelled` observed) | **no** — the CancelAfter timer usually still fires first; the race the fix closes is not forceable |
| **N2** re-bind on any marker move | F6 re-binding only when the INCARNATION changed at an unchanged time; a same-incarnation sequence bump mints + RefreshRequired | `A_resync_that_cannot_re_bind…` | yes |
| **N3** null-marker transition | a marker appearing or disappearing is a marker change: mint + RefreshRequired | `A_marker_appearing_on_an_unchanged_state_mints_an_ackable_EventId` | yes |
| **N4** joiner inherits the first caller's cancel/deadline | kept (documented in code): a joiner asked for the same thing at the same moment and never dispatches twice; the key includes the principal | — | n/a |
| **N5** existence answers before the gate | kept; the comment corrected — `BadNodeIdUnknown`/`BadNotSupported` are what SDK pre-validation reveals anyway | — | n/a |
| **N6** "OutcomeUnknown" text only with diagnostics | kept: the status is always Bad (never read as done); the text reaches a client requesting diagnostics and the Warning log | — | n/a |
| **N7** grace past TimeoutHint; elapsed subtracted twice | one end instant = min(start + mapping timeout, request deadline − grace); waits and the port budget derive from it, so the answer lands inside the client's TimeoutHint | floor test positive control (budget ≤ hint − grace) | not separately reverted |
| **N8** unsynchronised reads | `ImportedCondition.Placements` volatile publication; `SupportedMethods` an atomic 64-bit word | — | n/a (memory model) |
| **N9** method gate does not require visibility | documented: Ack on placement B suffices without seeing it via A; the EventId (128-bit, minted per consumer, only delivered to items that see the condition) is the practical visibility requirement | — | n/a |
## L3 — real dispatch path (review S5)
The A3b measurement repeated with the stall behind a real `ProjectedConditionAccess` + `GrpcDataConnection` (in-process origin
handler stalling 5 s), and with the original port-level stall, 10 rounds each:
| Run | Path | Stall | Read max | Browse max | Data Publish max | `Lock` acquire max |
|---|---|---|---|---|---|---|
| 1 | port | 5002 ms | 0.4 ms | 0.3 ms | 100.0 ms | 0.01 ms |
| 1 | **real** | 5044 ms | 0.5 ms | 0.3 ms | 101.6 ms | 0.01 ms |
| 2 | port | 5003 ms | 1.5 ms | 2.2 ms | 102.1 ms | 0.01 ms |
| 2 | **real** | 5051 ms | 2.3 ms | 0.3 ms | 100.8 ms | 0.01 ms |
| 3 | port | 5002 ms | 0.7 ms | 0.3 ms | 94.6 ms | 0.00 ms |
| 3 | **real** | 5040 ms | 0.4 ms | 0.3 ms | 102.6 ms | 0.00 ms |
| 4 | port | 5002 ms | 0.5 ms | 0.3 ms | 96.7 ms | 0.01 ms |
| 4 | **real** | 5042 ms | 0.4 ms | 0.3 ms | 109.1 ms | 0.01 ms |
(Measured inside the 4 combined OI gate runs, i.e. under the whole suite's parallel load.) All < 200 ms; the ~100 ms publish
figure is the minimum publishing interval, as before. The real-path stall is ~40 ms longer (capabilities probe + channel set-up
of the first call). **L3: PASS on the real dispatch path.**
## L2 — worst case (review S5) — **FAILS the 200 MiB gate**
Two placements per condition, every EventId slot (32) filled, three event items holding up to 1,000 events each (publishing off),
Live + Buffer record copies; forced compacting GCs; three runs:
| Run | Managed heap growth | Working-set growth | heap B/condition | after materialise (heap) |
|---|---|---|---|---|
| 1 | +92.3 MiB (GC noise: below the after-materialise figure) | +125.7 MiB | 96,770 | 217,948 |
| 2 | **+217.8 MiB** | **+210.0 MiB** | 228,353 | 217,979 |
| 3 | **+217.7 MiB** | **+206.1 MiB** | 228,299 | 217,931 |
At this worst case BOTH the managed heap (≈ 218 MiB) and the working set (206–210 MiB in 2 of 3 runs) exceed the 200 MiB gate;
the A3b single-placement figure (heap 197.4 MiB, WS ≈ 107 MiB) passed it only because it was not worst case. Recorded, not
adjusted: the harness keeps asserting ≤ 200 MiB and fails when opted in. The byte cap is now derived from the worst case
(230,000 B × 2,500 ≈ 548 MiB), so admission accounting is honest; whether the §9.3 L2 gate (200 MiB for 1,000 conditions) is
re-scoped to the single-placement case or the per-condition cost is reduced (≈ 210 KB is the SDK condition node + children —
X0's node-only figure was 161 KB — plus the second wiring) is an owner decision.
## Task: the OI condition-refresh failures (`ConditionRefreshDeferralWireTests` / `FolderConditionRefreshWireTests`)
**Conclusion: reproduces only with the A3 test classes in the run; NOT reproduced on master; root cause NOT established.
Not marked flaky.** No A3 production path is reached in the failing rigs (no imported condition exists in them;
`ReplayImportedConditions` returns at `Count == 0`; every other A3 hunk on the delivery/refresh path is a namespace-index test or a
`Find` returning null).
Evidence (combined filter `Feature=GrpcData|…ConditionMethodEvent|…NativeAlarmEventIdentityFieldDelivery|…FolderConditionRefresh|
…ConditionRefreshDeferral`, `--blame-hang-timeout 120s`, one run at a time):
| Build | Runs | Failed runs | Failures |
|---|---|---|---|
| master `83c7e586` (109 tests) | 4 | **0** | — |
| master `83c7e586`, only the two deferral classes, 14 busy-loop CPU burners | 2 | 0 | — |
| A3a r1 `01a4e8db` (130 tests) | 4 | 2 | gate test `A_refresh_waits_for_a_deferred_delivery…` (`window.Count` 4, expected 2); folder `Deferred_events_older…(enforced: False, …, modify: True)` (RefreshEnd not seen in 10 s, line 93) |
| `01a4e8db` + diagnostics (window dump on failure) | 6 | 0 | — (the failure did not recur, so no window dump was captured) |
| this round `72dece7f`+ (139 tests) | 4 | 3 | folder `Deferred_events_older…(enforced: True…)` ×2 (RefreshEnd not seen, line 93); folder `A_condition_removed_during_a_plain_refresh_is_not_replayed(serverObject: False)` (RefreshEnd not seen, line 527 — **no stall, no deferral involved**) |
| same + thread-pool latency sampler (50 ms probe) | 4 | 1 | folder `Deferred_events_older…` ×2; pool dispatch latency max **11 ms** in the failing run (≤ 21 ms in all), ≤ 21 pool threads |
| same + `DOTNET_ThreadPool_ForceMinWorkerThreads=64` | 1 | 1 | `ConditionRefreshDeferralWireTests.Deferred_events_older…(enforced: True…)`; pool max 15 ms |
Ruled out:
- **A3 production code in those rigs** — not reached (above); the shared helpers (`ApplyConditionState`, `CreateConditionNode`) are
pure extractions.
- **Thread-pool starvation** (the SDK's ConditionRefresh worker blocks a pool thread in `WaitOne` per server, which made it the
first suspect) — dispatch latency stayed ≤ 21 ms in failing runs and forcing 64 minimum workers did not prevent a failure.
- **Plain CPU load** — 14 burners on master's two classes: 0 failures.
What it is: mostly **a RefreshEnd that never reaches a folder (direct) event item** within 10 s — once in the plain
(non-deferring) refresh path with no stall at all — plus, once, two extra deferred events inside a Server-object refresh window.
It needs other tests running in the same process at the same time (it scales with the size of the parallel suite: 0/4 at 109
tests, 2/4 at 130, 3/4 at 139). Process-wide shared state is the remaining lead — e.g. `ProjectedEventDelivery`'s static
`FilterGroup` registry keyed by filter text, which every rig's server shares — but no mechanism was demonstrated. Pre-existing
code (#854/#855), exposed by suite composition rather than introduced by A3 behaviour as far as the evidence goes; to be filed.
## Gates (review round 1 A3b)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` | passed (`20261125T010625…`) |
| `run-unit-phase.py A2` | passed (`20261125T010724…`) |
| `run-unit-phase.py A1` | passed (`20261125T010836…`) |
| `run-unit-phase.py X0` | passed (`20261125T011156…`) |
| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2054 passed, 3 skipped |
| OpcUaServer.Tests full (same filter) | 1456 passed, 1 skipped |
| OI combined (139) | **not 3 clean**: 1 of 4 clean; every failure is in `FolderConditionRefreshWireTests` / `ConditionRefreshDeferralWireTests` (see the investigation above); every A3/GrpcData test passed in every run |
| OI `ImportedConditionMethodWireTests` (16) | 16/16 (and in each combined run) |
| L2 worst case (opt-in) | **FAIL** 2 of 3 runs (above) |
| `git diff master -- '*Goldens.cs'` | empty |
## Live — run `a3br1-cond-1` (build `c82ea04e`, clean tree) — PASS
Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, 90 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). Imported
ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ `BadEventIdUnknown [809A0000]`; ack through the
consumer `Acknowledge successful` (596 ms, through the new per-connection slot + dispatch floor + mapping-timeout path); origin
subscriber and consumer subscriber each saw exactly one Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers
or networks left.
# A3 — Round 2 (merge blocker: the OI condition-refresh failures; L2 worst-case memory)
2026-11-25, branch `a3-consumer`. Not merged, not pushed. Commits: `6be0b8dc` (fix + red/green test), `b884db5f` (L2), this docs
commit.
## Root cause of the OI condition-refresh failures — an A3 defect, now fixed
**SDK 2.0.1 pools `EventFieldList` process-wide, and `ProjectedEventFieldList` (A3a, §5.4) went back into that pool.**
`EventFieldListActivator : PooledEncodeableType<EventFieldList>` (bounded, process-global, 1,024); `MonitoredItem.GetEventFields`
rents every event's list from it; `SentMessageQueue.ReuseNotificationPayloads` calls `Reuse()` on every list of an acknowledged /
evicted message, and the base `ReuseCore` resets the instance and returns it — **whatever its runtime type** — to the stock pool.
A released `ProjectedEventFieldList` was therefore rented by ANY server's next `GetEventFields` — an unrelated session's
`RefreshStart`/`RefreshEnd` or local condition event — still carrying the imported condition's `ProjectedEventMarker`, and
`ProjectedNotificationRewriter` judged that unrelated event by the stale marker: when its gate denied (a revoked caller, a removed
condition), the event was **dropped**. The data path already knew this trap (`ProjectedSdkNotification` overrides `ReuseCore` and
"stays out of the shared stock pool"; `OrdinaryTagMarker` validates itself against its notification); the A3a event subclass did
not follow it.
This is a production defect, not a test artifact: in one server process, any session's events (refresh markers, local alarms,
acks) could be dropped by another session's imported-condition gate, and every recycled list pinned a marker closure (condition +
identity) for as long as it sat in the pool.
How it was found (one test run at a time, `--blame-hang-timeout 120s`):
| Step | Set | Runs | Failed runs |
|---|---|---|---|
| A3 build, full combined filter (139) | — | 1 | 1 |
| A3 build, master's 109 only (`FullyQualifiedName!~ImportedCondition`) | **A3 production code alone** | 4 | **0** ⇒ the A3 tests trigger it |
| without `ImportedConditionMethodWireTests` (123) | event wire tests in | 4 | 2 |
| deferral + folder classes + event wire tests only (52) | — | 4 | **4** |
| … + half A (6 tests) | — | 3 | 2 |
| … + `Exactly_one…`, `A3_SEC_with_ACLs_off…`, `A_condition_child_Read…` | — | 3 | 3 |
| … + `A_condition_child_Read…` only (no event subscription) | — | 3 | 0 |
| … + `Exactly_one…` only (no revocation) | — | 3 | 0 |
| … + `A3_SEC_with_ACLs_off…` only (**revokes** a marked event's caller) | — | 3 | 2 |
Then a temporary publish-path trace (server: the SDK's message before and after the rewriter; client: RefreshStart/End received;
reverted, never committed) on a failing run showed it directly:
```
PUBraw app=urn:OtOpcUa.Refresh855.… sub=3999762809 seq=2 h=19 START EventFieldList
PUBraw app=urn:OtOpcUa.Refresh855.… sub=3999762809 seq=2 h=19 END ProjectedEventFieldList ← a non-imported rig's RefreshEnd
PUB app=urn:OtOpcUa.Refresh855.… sub=3999762809 seq=2 h=19 START EventFieldList ← END dropped by the rewriter
RCV sub=3999762809 h=19 START
PUBraw app=urn:OtOpcUa.Refresh854Gate.… sub=990727810 seq=3 h=30 END ProjectedEventFieldList (never published)
```
That explains every symptom: "RefreshEnd never arrives" (the recycled list was the RefreshEnd), "RefreshStart missing but
RefreshEnd present" (the recycled list was the RefreshStart), "no stall/deferral at all" (plain refresh, same pool), extra events
inside a window (a recycled list whose stale marker PERMITTED), the scaling with suite size and the need for other tests in the
process (more marked lists in the pool), and master never reproducing (no marked lists). The earlier leads (thread-pool
starvation, CPU load, the static `FilterGroup` registry) were not it.
**Fix** (`ProjectedEventDelivery.cs`): `ProjectedEventFieldList` overrides `ReuseCore` — clears its marker, `ResetForReuse()`,
never returns to the stock pool (the GC takes it), exactly like `ProjectedSdkNotification`. `Marker` is nullable; the rewriter
treats a released (marker-less) list as denied (fail closed; it is never published again anyway). No `Lock` involvement.
**Red/green** (`ImportedConditionClassifierTests.A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker`,
OpcUaServer.Tests, deterministic): `Reuse()` a marked list as `SentMessageQueue` does, drain `DefaultMaximumRetained + 64` lists
from `EventFieldListActivator.Instance`, assert none is a `ProjectedEventFieldList`, the marker is gone, and a released list
through the rewriter is dropped. Red on revert, both ways: override body → `base.ReuseCore()` ⇒ `marked.Marker should be null`;
`Marker = null; base.ReuseCore()` ⇒ `rented should not contain an element satisfying the condition`.
After the fix: the 52-test reproducer 0/3 (was 4/4); the combined OI filter — see gates.
## L2 worst-case memory — PASS (the round-1 "FAIL" was a measurement artifact)
1. **EventId window → 8** (`ProjectedConditionRegistry.RecentEventIds`), the plan's §5.6 step 3 "within its last N (default 8)".
A3a's 32 had no recorded need (deviation 1 only stated it); validity is "minted under the current marker", which only the
newest few EventIds can meet. No test depended on 32 (only the L2 harness reads the constant).
2. **`GC.GetTotalMemory` is not the retained heap on .NET 10 regions.** In the same process state it reported **+92 or +218 MiB**
run to run (bimodal; it is the source of round 1's "+217.8 MiB" and run 1's "GC noise"). In those very runs
`GC.GetGCMemoryInfo().HeapSizeBytes` was 135.5 MB both times, and a heap dump of a "+218" run (`dotnet-dump`, taken while
paused after the measurement) held **136 MB of objects in total** (`eeheap -gc`: allocated 136,318,696 B, committed
236,208,128 B): the extra ~125 MiB was committed-but-free region space, and the working set measured the instant after the
forced GCs counted it too (+214 MiB; +133 MiB two seconds later in the same run). The harness now takes
`HeapSizeBytes − FragmentedBytes` after a full blocking GC, samples the working set until the GC has decommitted (two samples
500 ms apart within 1 MiB, ≤ 10 s), still logs the `GetTotalMemory` delta for comparison, and asserts **both** heap and working
set ≤ 200 MiB (stricter than before, not looser).
3. **What dominates** (end-of-run dump, 32-slot build): of 136 MB live, our own types are 6.4 MB — 3.1 MB of it the 32-slot
EventId window (32,000 `LinkedListNode` + 33,000 `DataActivationMarker`, now ÷4), the rest registry entries, placements,
1,000 `ImportedCondition`, 3,000 marked lists/markers (queues capped at 1,000 per item), the harness's Live + Buffer records
(~0.6 MB). ~86 MB is SDK `Opc.Ua.*` node state (property/variable/method states, `ReferenceDictionary`, 158 `Lock`s and 400
`object`s per condition), not ours to cut without touching the SDK node model.
Worst case (2 placements per condition, all 8 EventId slots filled, 3 event items with publishing off, Live + Buffer records):
| Run | Managed heap growth | Working-set growth (settled) | heap B/condition | WS B/condition | `GetTotalMemory` delta (not used) |
|---|---|---|---|---|---|
| 1 | +106.5 MiB | +151.3 MiB | 111,715 | 158,629 | +211.6 MiB |
| 2 | +106.5 MiB | +149.2 MiB | 111,682 | 156,434 | +211.5 MiB |
| 3 | +106.5 MiB | +149.4 MiB | 111,654 | 156,663 | +211.5 MiB |
**L2: PASS** (both ≤ 200 MiB in every run). `BytesPerCondition` = the larger of the two per-condition figures, max of three runs,
rounded up: 158,629 → **160,000** (was 230,000); `MaxImportedConditionBytes` default = 160,000 × 2,500 = **400,000,000 B
(≈ 381 MiB)** (was ≈ 548 MiB). The X0 node-only figure (160,997) and A3b's 197.4 MiB were taken with `GetTotalMemory` too and are
likely inflated the same way (not re-measured here).
## Gates (round 2, at `b884db5f`)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` | passed (`20261125T024649…`) |
| `run-unit-phase.py A2` | passed (`20261125T024744…`) |
| `run-unit-phase.py A1` | passed (`20261125T024855…`) |
| `run-unit-phase.py X0` | passed (`20261125T025234…`) |
| Host.Tests `.DataConnections.` (both v1 gates) | 207 passed |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2054 passed, 3 skipped (see note) |
| OpcUaServer.Tests full (same filter) | 1457 passed, 1 skipped |
| OI combined (139) | **3 consecutive clean runs**: 138 passed, 1 skipped (the opt-in L2 harness) each |
| L2 worst case (opt-in) | PASS 3/3 (above) |
| `git diff master -- '*Goldens.cs'` | empty |
Note (Runtime): the first full run, made while the live rig's images were building (heavy CPU), failed one test,
`GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` (A2, unchanged by A3 — it races 6 raises
against the condition item's read position to force a hub eviction). Not touched by round 2 (no Runtime behaviour changed; only the
`BytesPerCondition` constant). The class passed 5/5 alone and the full suite passed on the re-run without load. Not root-caused
here and not called a flake: to be filed as a load-sensitivity follow-up.
## Live — run `a3r2-cond-1` (build `b884db5f`, clean tree) — PASS
Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, 90 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). Imported
ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ `BadEventIdUnknown [809A0000]`; ack through the
consumer `Acknowledge successful` (1,990 ms); origin subscriber and consumer subscriber each saw exactly one
Active/Acknowledged; `passed: true`. Teardown: no run-labelled containers or networks left.
## Left over
- File: the `GrpcDataConditionStreamTests.Overflow_before_the_snapshot_is_drained_resets_the_stream` load sensitivity (above).
- The plan's L2 / X0 figures (≈ 157–161 KiB per condition node, §5.5 table) came from `GC.GetTotalMemory` and are likely
inflated by the same region accounting; the plan's §5.5 table was not edited (evidence only).
# A3 — Verification review round 2
2026-11-25, branch `a3-consumer`. Not merged, not pushed. **Verdict: approve-with-changes** — one must-fix (N1) and one
comment/test fix; both done in `c8b35d49`. N2/N3 filed as #930; N4–N8 filed as #931.
## N1 — the runner predecessor chain leaked one runner per demand cycle — fixed
`ConnectionRunner._predecessor` was `readonly` and never cleared, and every runner kept `_states` (its last stream's Live/Buffer
record sets). Each linger expiry + re-subscribe, or mapping change, added a link R3 → R2 → R1, so memory grew without bound.
Fix (`ProjectedConditionAccess.Runner.cs`): the hand-over moved into `HandOverAsync` (its own state machine, so no hoisted
`previous` local outlives it), which awaits the old runner's `Stopped` (loop end + removal), takes its materialised set, and only
then sets `_predecessor = null` — the S3/S4 ordering is unchanged. A stopping runner's continuation now resets `_states = []`
before (optionally) removing its conditions, so a runner parked in `_stopping` until the next demand holds no record sets.
New test observation `ProjectedConditionAccess.RunnerReference(connectionId)` (a `WeakReference`, never a strong one).
**Red/green** — `GrpcDataProjectedConditionAccessTests.N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable`
(Runtime.Tests): first runner completes a snapshot, then 3 linger-expiry + re-demand cycles and 2 mapping changes, each with a
complete snapshot; asserts the hand-over still holds (`Sink.Live == [x]`) and, after forced GCs, that the first runner's weak
reference is dead. Red with the original `Runner.cs` restored (`first.IsAlive should be False`); green with the fix, 5/5 repeats.
S3/S4 hand-over tests still pass.
## Pool-fix comment corrected + clone dependency pinned
The `ProjectedEventFieldList` summary claimed the SDK never clones a queued list. Wrong: SDK 2.0.1 `SentMessageQueue` returns
`CoreUtils.Clone` of the stored message on Publish and Republish, so the rewriter never sees the queued instance. The gate works
because `EventFieldList.Clone()` is `MemberwiseClone`, which keeps the subclass, the marker and the handle. The comment now says
that. New test `ImportedConditionClassifierTests.Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker`
(OpcUaServer.Tests): `Clone()` and `CoreUtils.Clone(NotificationMessage)` both yield a `ProjectedEventFieldList` with the same
marker and handle, and the rewriter still drops the copy when its re-check fails. Shown to discriminate: a temporary
`Clone()` override returning a stock `EventFieldList` (what an activator-based clone would do) turns it red
(`marked.Clone() should be of type ProjectedEventFieldList`); reverted.
## Gates (verification round 2, at `c8b35d49`)
| Gate | Result |
|---|---|
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx --no-incremental` | 0 warnings, 0 errors |
| `run-unit-phase.py A3` | passed (`20261125T032703…`) |
| `run-unit-phase.py A2` | passed (`20261125T032802…`) |
| Runtime.Tests full (`Category!=E2E&Category!=LiveIntegration`) | 2055 passed, 3 skipped |
| OpcUaServer.Tests full (same filter) | 1458 passed, 1 skipped |
| Host.Tests `.DataConnections.` | 207 passed |
| OI combined (139) | clean: 138 passed, 1 skipped (the opt-in L2 harness) |
| `git diff master -- '*Goldens.cs'` | empty |
## Live — run `a3v2-cond-1` (build `c8b35d49`) — PASS
Same procedure as `a3b-cond-3` (`rig.py up --conditions`, seed, 90 s, deploy, `conditions_a3_smoke.py`, `rig.py down`). Imported
ScalarHigh at the consumer (`ns=6;s=c1.…`, 32-char EventId); bogus EventId ⇒ `BadEventIdUnknown [809A0000]`; ack through the
consumer `Acknowledge successful` (540 ms); origin subscriber and consumer subscriber each saw exactly one Active/Acknowledged;
`passed: true`. Teardown: no run-labelled containers or networks left.
@@ -0,0 +1,132 @@
"""A3 consumer-condition live smoke on a `rig.py up --conditions` run (plan §9 A3 exit; the full gate is A4).
Raises the SOURCE scripted alarm `ScalarHigh` (scalar register 20 := 150) through the device control API, then:
1. starts the CLI `alarms --refresh` on the SOURCE Primary (the origin's OWN subscriber) and on the CONSUMER Primary (whose
Server-object item opens condition demand, so the consumer imports ScalarHigh over its data connection);
2. waits for the IMPORTED `ScalarHigh` (Active, Unacknowledged) on the consumer, with its consumer-minted EventId and its
`mapped/conditions` ConditionNodeId;
3. refuses first: a bogus EventId must answer `BadEventIdUnknown` (nothing sent);
4. acknowledges it THROUGH THE CONSUMER with the CLI `ack` (§5.6: claimed by the node manager, dispatched to the origin's
`CallConditionMethod`, never applied locally);
5. requires the origin's own subscriber to see EXACTLY ONE `Active, Acknowledged` ScalarHigh event, and the consumer to
see the acknowledgement come back (the origin's record re-imported) — exactly one consumer `Active, Acknowledged` event;
6. clears the alarm.
Evidence lands in the run's restricted `evidence/` folder (`A3-*.txt`, `A3-*.process.json`, `A3-conditions-consumer.json`).
"""
import argparse
import json
import os
import re
import signal
import subprocess
import sys
import time
import scenarios
def watch(runner, node, name):
log = runner.folder / name
descriptor = os.open(log, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
process = subprocess.Popen(["dotnet", str(runner.cli_dll), "alarms", "-u", runner.endpoint(node), "-U", "apikey", "-P", runner.key,
"--refresh", "-i", "250"], stdout=descriptor, stderr=subprocess.STDOUT, start_new_session=True)
os.close(descriptor)
return process, log
def stop(process):
process.send_signal(signal.SIGINT)
try:
process.wait(timeout=20)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=10)
def blocks(log, condition="ScalarHigh"):
found = []
for block in log.read_text(errors="replace").split("\n\n"):
if f"Condition: {condition}" not in block:
continue
fields = {}
for line in block.splitlines():
match = re.match(r"\s*(State|ConditionNodeId|EventId|Message):\s*(.*)$", line)
if match:
fields[match.group(1)] = match.group(2).strip()
found.append(fields)
return found
def wait_for(predicate, timeout, step=1.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
value = predicate()
if value:
return value
time.sleep(step)
return predicate()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-id", required=True)
parser.add_argument("--settle-seconds", type=int, default=8)
parser.add_argument("--import-timeout", type=int, default=120)
arguments = parser.parse_args(argv)
runner = scenarios.ScenarioRunner(arguments.run_id)
runner.active, runner.deadline = "A3", time.monotonic() + 900
runner.publish()
runner.device("set", address=20, value=150)
time.sleep(arguments.settle_seconds)
source, consumer = runner.primary("source"), runner.primary("consumer")
origin_watch, origin_log = watch(runner, source, "A3-origin-alarms.txt")
consumer_watch, consumer_log = watch(runner, consumer, "A3-consumer-alarms.txt")
report = {"source_primary": source, "consumer_primary": consumer, "checks": {}}
try:
imported = wait_for(lambda: next((b for b in blocks(consumer_log) if b.get("State") == "Active, Unacknowledged"
and b.get("EventId") and b.get("ConditionNodeId")), None), arguments.import_timeout)
report["checks"]["imported_active_unacked"] = bool(imported)
if not imported:
raise scenarios.ScenarioError("the consumer never showed the imported ScalarHigh (Active, Unacknowledged)")
report["imported"] = {"condition_node_id": imported["ConditionNodeId"], "event_id_len": len(imported["EventId"])}
endpoint = runner.endpoint(consumer)
base = ["dotnet", str(runner.cli_dll), "ack", "-u", endpoint, "-U", "apikey", "-P", runner.key, "-n", imported["ConditionNodeId"]]
bogus = runner.process(base + ["-e", "00" * 16, "-c", "A3 bogus"], "A3-ack-bogus-eventid", timeout=60)
bogus_text = bogus.stdout + bogus.stderr
report["checks"]["bogus_eventid_refused"] = ("BadEventIdUnknown" in bogus_text or "809A0000" in bogus_text.upper()) \
and "successful" not in bogus_text
report["bogus"] = bogus_text[-300:]
time.sleep(3)
report["checks"]["nothing_acked_after_bogus"] = all(b.get("State") != "Active, Acknowledged" for b in blocks(origin_log))
started = time.monotonic()
ack = runner.process(base + ["-e", imported["EventId"], "-c", "A3 consumer ack"], "A3-ack-consumer", timeout=60)
report["ack"] = {"returncode": ack.returncode, "elapsed_ms": round((time.monotonic() - started) * 1000),
"stdout": ack.stdout[-400:]}
report["checks"]["ack_good"] = ack.returncode == 0 and "Acknowledge successful" in ack.stdout
acked_back = wait_for(lambda: any(b.get("State") == "Active, Acknowledged" for b in blocks(consumer_log)), 30)
report["checks"]["consumer_sees_ack_back"] = bool(acked_back)
time.sleep(6) # let any duplicate arrive before counting
finally:
stop(consumer_watch)
stop(origin_watch)
runner.device("set", address=20, value=0)
origin_states = [b.get("State") for b in blocks(origin_log)]
consumer_states = [b.get("State") for b in blocks(consumer_log)]
report["origin_subscriber"] = {"states": origin_states, "active_acknowledged_events": origin_states.count("Active, Acknowledged")}
report["consumer_subscriber"] = {"states": consumer_states, "active_acknowledged_events": consumer_states.count("Active, Acknowledged")}
report["checks"]["origin_exactly_one_ack_event"] = report["origin_subscriber"]["active_acknowledged_events"] == 1
report["checks"]["consumer_exactly_one_ack_event"] = report["consumer_subscriber"]["active_acknowledged_events"] == 1
report["passed"] = all(report["checks"].values())
runner.save("A3-conditions-consumer.json", report)
print(json.dumps(report, indent=2)[:20000])
return 0 if report["passed"] else 1
if __name__ == "__main__":
sys.exit(main())
+6 -2
View File
@@ -388,7 +388,10 @@ try
db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true,
ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "SOURCE",
EligibleTargetNodeIds = ["source-1:4053", "source-2:4053"], Endpoints = ["https://source-1:4057", "https://source-2:4057"],
SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER", AllowedOperations = grantedOperations,
// A3: the conditions profile makes the CONSUMER condition-bearing too (connection + mappings carry AlarmSubscribe and
// the method bits), so a consumer Server-object subscription imports ScalarHigh and can acknowledge it remotely.
SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER",
AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None),
TimeoutMilliseconds = 30000 });
foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns })
{
@@ -406,7 +409,8 @@ try
ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"],
Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source",
RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment, AllowedOperations = grantedOperations, WriteThrough = true });
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment,
AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None), WriteThrough = true });
if (history)
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli",
ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead });
@@ -1148,5 +1148,39 @@
],
"existing_classes": []
}
],
"A3": [
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.GrpcDataConditionStreamTests.|FullyQualifiedName~.GrpcDataConditionMethodClientTests.",
"new_classes": [
"GrpcDataProjectedConditionAccessTests",
"GrpcDataProjectedConditionMethodTests"
],
"existing_classes": [
"GrpcDataConditionStreamTests",
"GrpcDataConditionMethodClientTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.ConditionMethodNodeManagerTests.|FullyQualifiedName~.ProjectedHistoryReadTests.",
"new_classes": [
"ImportedConditionClassifierTests"
],
"existing_classes": [
"ConditionMethodNodeManagerTests",
"ProjectedHistoryReadTests"
]
},
{
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj",
"filter": "(Feature=GrpcData&Phase=A3)|FullyQualifiedName~.GrpcDataV1CompatibilityTests.|FullyQualifiedName~.GrpcDataV1RealOriginCompatibilityTests.",
"new_classes": [],
"existing_classes": [
"GrpcDataV1CompatibilityTests",
"GrpcDataV1RealOriginCompatibilityTests"
]
}
]
}
@@ -148,6 +148,16 @@ public interface IDataSubscriptionFreshnessSupport
bool SupportsFreshnessChallenges { get; }
int FreshnessMaxItems { get; }
}
/// <summary>
/// A3 (review r1, deviation 9): a connection that can open a subscription served by the origin's <b>Primary</b> only —
/// condition items are served by the Primary (a Secondary advertises the feature but refuses the item, A2 N7), so the
/// consumer's condition stream must not land on a ReadyReplica Secondary the v1 value path would accept.
/// </summary>
public interface IDataPrimarySubscriptionSource
{
/// <summary>Like <see cref="IDataSubscriptionService.SubscribeAsync"/>, admitting only an endpoint whose serving role is Primary.</summary>
Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken);
}
/// <summary>Immutable serving identity captured when the subscription was established.</summary>
public interface IDataSubscriptionProvenance
{
@@ -19,6 +19,10 @@ public sealed class DataConnectionOptions
public int MaxStreamsPerPrincipal { get; set; } = 8;
public int MaxMonitoredItems { get; set; } = 10_000;
public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024;
/// <summary>A3 (§5.5): imported-condition node budget per consumer node (2,500 × 49 worst-case nodes per condition).</summary>
public int MaxImportedConditionNodes { get; set; } = 122_500;
/// <summary>A3 (§5.5): imported-condition memory budget per consumer node (§9.3 L2: worst-case measured 160,000 B/condition × 2,500 ≈ 381 MiB).</summary>
public long MaxImportedConditionBytes { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionOptions.DefaultMaxImportedConditionBytes;
public long MaxPendingBytes { get; set; } = 1024 * 1024;
public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1);
/// <summary>A2b: remote condition-method operations the origin remembers at once for duplicate protection (all principals).</summary>
@@ -1,5 +1,6 @@
using Akka.Hosting;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
@@ -143,6 +144,17 @@ public static class DataConnectionRegistration
? bytes : null,
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataConnectionHistoryDiagnostics>()));
services.AddSingleton<IProjectedHistoryAccess>(sp => sp.GetRequiredService<ProjectedHistoryAccess>());
// A3: imported conditions (§5.3–§5.5) — the gate, per-connection demand and the stream runtime. The node manager is
// bound as its sink by OtOpcUaServerHostedService once the server is up.
services.AddSingleton(sp => new ProjectedConditionAccess(
new DeployedConditionMappings(sp.GetRequiredService<ProjectedMappingDeploymentRuntime>()),
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(), sp.GetRequiredService<DataOperationPolicy>(), null,
sp.GetRequiredService<TimeProvider>(), ProjectedConditionOptions.Default with
{
MaxImportedConditionNodes = options.MaxImportedConditionNodes,
MaxImportedConditionBytes = options.MaxImportedConditionBytes,
}, sp.GetRequiredService<ILoggerFactory>().CreateLogger<ProjectedConditionAccess>()));
services.AddSingleton<IProjectedConditionAccess>(sp => sp.GetRequiredService<ProjectedConditionAccess>());
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
sp.GetRequiredService<ProjectedNamespaceApplier>(), sp.GetRequiredService<IProjectedNodeLookup>(),
@@ -61,6 +61,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
private readonly IProjectedDataAccess? _projectedDataAccess;
private readonly IProjectedHistoryAccess? _projectedHistoryAccess;
private readonly IProjectedConditionAccess? _projectedConditionAccess;
// A1 (plan §5.1): the condition-state hub the node manager's delta callback feeds. Invisible until A2.
private readonly IConditionStateSink? _conditionStateSink;
private readonly IFederatedProjectionCatalog? _projectedCatalog;
@@ -170,8 +171,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
IProjectedDataAccess? projectedDataAccess = null,
IFederatedProjectionCatalog? projectedCatalog = null,
IProjectedHistoryAccess? projectedHistoryAccess = null,
IConditionStateSink? conditionStateSink = null)
IConditionStateSink? conditionStateSink = null,
IProjectedConditionAccess? projectedConditionAccess = null)
{
_projectedConditionAccess = projectedConditionAccess;
_projectedHistoryAccess = projectedHistoryAccess;
_conditionStateSink = conditionStateSink;
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
@@ -273,6 +276,12 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
_server.NodeManager.ProjectedBrowseClock = _time;
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
_server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess;
// A3: imported conditions — the gate/demand into the node manager, the node manager as the runtime's sink.
_server.NodeManager.ProjectedConditionAccess = _projectedConditionAccess;
// A3b (§5.6): remote condition methods go through the same condition runtime (its per-caller method gate + the lease).
_server.NodeManager.ProjectedConditionMethods = _projectedConditionAccess as ZB.MOM.WW.OtOpcUa.OpcUaServer.IProjectedConditionMethods;
if (_projectedConditionAccess is ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedConditionAccess conditions)
conditions.Sink = _server.NodeManager;
_server.NodeManager.ConditionStateSink = _conditionStateSink;
if (_projectedCatalog is { } projectedCatalog)
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
@@ -5,7 +5,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>Preserves the application's repeat-method contract at the SDK's supported validation seam.</summary>
internal static class ApplicationAlarmConditions
{
internal static AlarmConditionState Create(string type, NodeState parent) => type switch
internal static AlarmConditionState Create(string type, NodeState? parent) => type switch
{
"OffNormalAlarm" => new OffNormal(parent),
"DiscreteAlarm" => new Discrete(parent),
@@ -34,7 +34,7 @@ internal static class ApplicationAlarmConditions
}
}
private sealed class OffNormal(NodeState parent) : OffNormalAlarmState(parent)
private sealed class OffNormal(NodeState? parent) : OffNormalAlarmState(parent!)
{
protected override ServiceResult ProcessBeforeAcknowledge(ISystemContext context, ByteString id, LocalizedText comment) =>
CurrentTrunkRepeat(base.ProcessBeforeAcknowledge(context, id, comment), this, context, id, comment, true);
@@ -43,7 +43,7 @@ internal static class ApplicationAlarmConditions
protected override ConditionState CreateBranchInstance() => new OffNormal(this);
}
private sealed class Discrete(NodeState parent) : DiscreteAlarmState(parent)
private sealed class Discrete(NodeState? parent) : DiscreteAlarmState(parent!)
{
protected override ServiceResult ProcessBeforeAcknowledge(ISystemContext context, ByteString id, LocalizedText comment) =>
CurrentTrunkRepeat(base.ProcessBeforeAcknowledge(context, id, comment), this, context, id, comment, true);
@@ -52,7 +52,7 @@ internal static class ApplicationAlarmConditions
protected override ConditionState CreateBranchInstance() => new Discrete(this);
}
private sealed class Alarm(NodeState parent) : AlarmConditionState(parent)
private sealed class Alarm(NodeState? parent) : AlarmConditionState(parent!)
{
protected override ServiceResult ProcessBeforeAcknowledge(ISystemContext context, ByteString id, LocalizedText comment) =>
CurrentTrunkRepeat(base.ProcessBeforeAcknowledge(context, id, comment), this, context, id, comment, true);
@@ -0,0 +1,89 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// A3 (plan §5.2/§5.5): one current placement of an imported condition on this consumer — realm-consistent: the
/// placement address lives in the realm of <see cref="MappingId"/>'s export, and the folder it hangs under is a
/// projected node of that same mapping.
/// </summary>
/// <param name="MappingId">The <c>RemoteNamespaceMapping</c> whose root item listed the placement.</param>
/// <param name="Realm">The mapping's (and the placement's) realm.</param>
/// <param name="Placement">The origin placement address (a listing view; never a cross-realm id).</param>
/// <param name="FolderLocalSubject">
/// The LOCAL subject (slash-joined local scope segments) of the projected folder the placement sits under: the
/// mapping anchor's own subject when the placement's parent is the remote root. The node manager wires that folder
/// when (and only while) it is materialised (N7).
/// </param>
/// <param name="RelativePath">The placement address relative to the mapping's remote root (display only).</param>
public sealed record ImportedConditionPlacement(string MappingId, DataRealm Realm, DataView Placement, string FolderLocalSubject,
string RelativePath);
/// <summary>
/// A3: one imported condition as the consumer's condition runtime hands it to the node manager — identity
/// (<see cref="ConnectionId"/>, <see cref="DataConditionState.ConditionKey"/>), its current placements (primary first) and
/// the origin record to mirror. The node manager mints the NodeId from the identity only (N4).
/// </summary>
/// <param name="ConnectionId">The deployed <c>DataConnection</c> the condition was imported over.</param>
/// <param name="State">The origin record (already version-gated by the runtime).</param>
/// <param name="Info">The condition's static facts (type, name, source kind); the latest one the stream carried.</param>
/// <param name="Placements">Every current placement on this node, the PRIMARY one first (§5.2: deployed config only).</param>
/// <param name="SourceName">The primary placement's display path (§5.2).</param>
public sealed record ImportedConditionUpdate(string ConnectionId, DataConditionState State, DataConditionInfo? Info,
IReadOnlyList<ImportedConditionPlacement> Placements, string SourceName);
/// <summary>
/// A3 (§5.3/§5.5): what the consumer's condition runtime tells the node manager. Every call is bounded per Lock hold by
/// the implementation; none blocks on the network.
/// </summary>
public interface IProjectedConditionSink
{
/// <summary>Materialises new conditions and applies records through the shared #656 delta gate.</summary>
void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates);
/// <summary>Removes conditions (an origin <c>removed</c> record, or a complete re-snapshot that no longer lists them).</summary>
void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys);
/// <summary>The connection is gone past its stale timeout: <c>Quality = BadNoCommunication</c>, one event each.</summary>
void MarkConnectionStale(string connectionId);
/// <summary>Review r1 B2: these conditions' state is unknown (their mapping did not complete a snapshot) —
/// <c>Quality = BadNoCommunication</c>, one event each, never removed and never "known inactive".</summary>
void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys);
/// <summary>Sends <c>RefreshRequiredEventType</c> to every item that may see a condition of the connection.</summary>
void RequireRefresh(string connectionId);
}
/// <summary>
/// A3 (§5.4/§5.5): the consumer's condition access — the per-caller visibility gate and per-connection demand. SDK-free
/// apart from the identity type, like <see cref="IProjectedHistoryAccess"/>.
/// </summary>
public interface IProjectedConditionAccess
{
/// <summary>
/// The §5.4 gate: whether <paramref name="caller"/> passes the mapping gate for <c>CreateMonitoredItems</c>
/// (<see cref="DataOperations.Subscribe"/>) on ANY current placement mapping. Evaluated regardless of
/// <c>Security:Acl:Enabled</c>. Null caller ⇒ false.
/// </summary>
bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements);
/// <summary>Deviation 3 (review r1): the mapping gate on one projected folder of a condition-bearing mapping — admits a
/// folder event item (and its demand) before any imported condition is wired there.</summary>
bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject);
/// <summary>Deviation 3 (review r1): whether a deployed mapping is condition-bearing — its projected folders are event
/// notifiers from materialisation (the SDK refuses an event item on a node without <c>SubscribeToEvents</c>).</summary>
bool IsConditionBearingMapping(string mappingId);
/// <summary>A generation that moves whenever anything the gate reads may have changed (verdict caches key on it).</summary>
long AuthorityGeneration { get; }
/// <summary>
/// An admitted local event item that could see imported conditions (Server object or a projected notifier). The
/// first one opens condition demand for every connection the caller could see; disposing the last starts the linger.
/// Null when no connection carries conditions (nothing to open).
/// </summary>
IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller);
}
@@ -0,0 +1,426 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// A3b (plan §5.6 step 2): where an authorized remote condition method goes — the placement the origin resolves (one the
/// caller passed the mapping gate on, primary order first) and that mapping's <c>ConditionMethodTimeoutMilliseconds</c>.
/// </summary>
/// <param name="Placement">The placement to dispatch through.</param>
/// <param name="Timeout">The mapping's method ceiling (default 5 s).</param>
public sealed record ImportedConditionMethodRoute(ImportedConditionPlacement Placement, TimeSpan Timeout);
/// <summary>
/// A3b (plan §5.6 step 4): one remote condition method the consumer's node manager hands to its condition runtime. Never
/// carries the local caller's credentials: the origin sees the connection's service principal; <see cref="OnBehalfOf"/> is
/// audit text only.
/// </summary>
/// <param name="ConnectionId">The connection the condition was imported over.</param>
/// <param name="ConditionKey">The origin's opaque key (diagnostics only; the origin resolves <see cref="Placement"/>).</param>
/// <param name="Placement">The placement to address the origin with.</param>
/// <param name="Method">Exactly one method.</param>
/// <param name="ExpectedActivation">The marker of the latest applied record (T3).</param>
/// <param name="Comment">The Part 9 comment, or null.</param>
/// <param name="OperationId">A fresh id per dispatched call (the origin joins duplicates of it, never retried here).</param>
/// <param name="RemainingBudget">min(request deadline, the mapping's method ceiling) minus what was already spent.</param>
/// <param name="OnBehalfOf">The local caller's principal, for the origin's audit log.</param>
public sealed record ImportedConditionMethodCall(string ConnectionId, string ConditionKey, ImportedConditionPlacement Placement,
DataConditionMethods Method, DataActivationMarker ExpectedActivation, string? Comment, string OperationId, TimeSpan RemainingBudget,
string? OnBehalfOf);
/// <summary>
/// A3b (plan §5.6): the consumer condition runtime's method port. SDK-free apart from the identity type.
/// </summary>
public interface IProjectedConditionMethods
{
/// <summary>
/// The per-caller gate (re-evaluated for every local caller — the stream itself runs under the connection's service
/// principal): the caller's <c>AlarmAcknowledge</c> (Acknowledge, AddComment) or <c>AlarmConfirm</c> (Confirm) grant on
/// the placement's folder scope, on a current, condition-bearing mapping that itself grants the method's bit, with a
/// usable key (#563). Regardless of <c>Security:Acl:Enabled</c>. Null = denied.
/// </summary>
ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
DataConditionMethods method);
/// <summary>One remote call. Answers, never throws for a remote failure; never retried.</summary>
Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken);
}
/// <summary>
/// A3b (plan §5.6 step 1): the Call service's interception point for imported conditions. The SDK's
/// <c>AsyncNodeManagerAdapter</c> forwards <c>CallAsync</c> to a wrapped manager only when it implements
/// <see cref="ICallAsyncNodeManager"/>; otherwise it runs the synchronous <c>Call</c>, which takes <c>Lock</c> per request.
/// </summary>
public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager
{
/// <summary>Most remote condition methods in flight on this node (§5.6: bounds upstream load, not threads).</summary>
internal const int DefaultImportedMethodConcurrency = 8;
/// <summary>
/// A3b review S4: most remote condition methods in flight to ONE connection — a sub-limit inside the node-wide
/// <see cref="DefaultImportedMethodConcurrency"/>, so a stalled origin holds at most half the node's slots and acks to
/// healthy origins still dispatch.
/// </summary>
internal const int DefaultImportedMethodConcurrencyPerConnection = 4;
/// <summary>How long past the call's own budget the node manager waits for the port before answering <c>BadTimeout</c>.</summary>
internal static readonly TimeSpan ImportedMethodGrace = TimeSpan.FromMilliseconds(250);
/// <summary>
/// A3b review S4: a call whose remaining budget at dispatch is below this is refused <c>BadTimeout</c> UNSENT — the origin
/// could apply it while the consumer had already answered <c>BadTimeout</c>.
/// </summary>
internal static readonly TimeSpan ImportedMethodMinimumDispatchBudget = TimeSpan.FromMilliseconds(250);
private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency);
// One per connection that ever dispatched (connections are few and long-lived; never removed — a SemaphoreSlim is small).
private readonly ConcurrentDictionary<string, SemaphoreSlim> _importedMethodConnectionSlots = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, Task<ServiceResult>> _importedMethodsInFlight = new(StringComparer.Ordinal);
private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused;
/// <summary>A3b: the consumer's remote condition method port (null ⇒ every imported method is <c>BadNotSupported</c>).</summary>
public IProjectedConditionMethods? ProjectedConditionMethods { get; set; }
/// <summary>Remote condition methods handed to the port (test/diagnostic observation).</summary>
internal long ImportedMethodsDispatched => Interlocked.Read(ref _importedMethodsDispatched);
/// <summary>Calls that joined an identical call already in flight instead of dispatching again.</summary>
internal long ImportedMethodsJoined => Interlocked.Read(ref _importedMethodsJoined);
/// <summary>Imported-condition calls refused locally (nothing sent).</summary>
internal long ImportedMethodsRefused => Interlocked.Read(ref _importedMethodsRefused);
/// <summary>
/// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in <c>mapped/conditions</c> — a namespace-index
/// test, no lock; (b) the unchanged synchronous <c>base.Call</c> for everything else (it skips claimed requests), run
/// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore.
/// No <c>Lock</c> is held by this method at any point. Review S1: nothing after <c>base.Call</c> throws — local items are
/// already applied by then, so a fault there must become a per-item status, never a ServiceFault for the batch.
/// </summary>
public override async ValueTask CallAsync(OperationContext context, ArrayOf<CallMethodRequest> methodsToCall,
IList<CallMethodResult> results, IList<ServiceResult> errors, CancellationToken cancellationToken = default)
{
List<int>? claimed = null;
for (var i = 0; i < methodsToCall.Count; i++)
{
var request = methodsToCall[i];
if (request is null || request.Processed || !IsImportedConditionId(request.ObjectId)) continue;
request.Processed = true;
(claimed ??= []).Add(i);
}
base.Call(context, methodsToCall, results, errors);
if (claimed is null) return;
var caller = context.UserIdentity as RoleCarryingUserIdentity;
var deadline = context.OperationDeadline;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken);
var calls = new Task<ServiceResult>[claimed.Count];
for (var k = 0; k < claimed.Count; k++)
{
results[claimed[k]] = new CallMethodResult();
calls[k] = CallImportedGuardedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token);
}
// Each task is guarded (never faults), so WhenAll never throws; results are collected per item regardless.
await Task.WhenAll(calls).ConfigureAwait(false);
for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = calls[k].Result;
}
/// <summary>Review S1: <see cref="CallImportedAsync"/> as a task that cannot fault (a synchronous throw included).</summary>
private async Task<ServiceResult> CallImportedGuardedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
CancellationToken cancellationToken)
{
try
{
return await CallImportedAsync(caller, request, deadline, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch");
return Refuse(StatusCodes.BadInternalError);
}
}
/// <summary>
/// §5.6 steps 2–5 for one claimed request. Every refusal returns before anything is sent; nothing here changes local
/// condition state — the origin applies, reports and streams, and the record's arrival changes the node (§5.3).
/// </summary>
private async Task<ServiceResult> CallImportedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline,
CancellationToken cancellationToken)
{
var started = Stopwatch.GetTimestamp();
try
{
if (!request.ObjectId.TryGetValue(out string objectIdentifier)
|| !ImportedConditionIds.TryParse(objectIdentifier, out var conditionIdentifier, out _, out _, out _)
|| _importedConditions.Find(new NodeId(conditionIdentifier, request.ObjectId.NamespaceIndex)) is not { } condition)
return Refuse(StatusCodes.BadNodeIdUnknown);
var method = ImportedMethodOf(request.MethodId, conditionIdentifier);
if (method == DataConditionMethods.None) return Refuse(StatusCodes.BadNotSupported); // shelve, enable/disable, …
if (ProjectedConditionMethods is not { } port) return Refuse(StatusCodes.BadNotSupported);
// Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else
// (review N5: the two answers above are the SDK pre-validation's own — the node and its method exist publicly).
var placements = condition.Placements;
var route = port.AuthorizeMethod(caller, placements, method);
if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied);
if (method == DataConditionMethods.Confirm && condition.IsNative) return Refuse(StatusCodes.BadNotSupported);
if (condition.SupportedMethods is { } supported && (supported & (uint)method) == 0) return Refuse(StatusCodes.BadNotSupported);
if (_standby.RefusesMutations) { Interlocked.Increment(ref _importedMethodsRefused); return WarmStandbyState.StandbyRefusal($"call {DataConditionMethodSets.Part9Name(method)}"); }
if (!TryReadMethodArguments(request.InputArguments, out var eventId, out var comment, out var argumentError))
return Refuse(argumentError);
// EventId: minted by this consumer for this condition under the SAME marker as the latest applied record (N6/T3).
DataActivationMarker? expected = null;
lock (condition.MethodGate)
{
foreach (var (id, activation) in condition.RecentEvents)
{
if (id != eventId) continue;
if (activation is not null && activation == condition.Activation) expected = activation;
break;
}
}
if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown);
// An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch.
// Review N4: a joiner shares the first caller's outcome — its cancellation and budget included (it asked for the
// same thing at the same moment; a joiner never dispatches a second time).
var key = string.Join('\n', caller.Principal, condition.Alarm.NodeId.ToString(), Convert.ToHexString(eventId.Span),
((uint)method).ToString(System.Globalization.CultureInfo.InvariantCulture), comment ?? "\u0001");
var mine = new TaskCompletionSource<ServiceResult>(TaskCreationOptions.RunContinuationsAsynchronously);
var existing = _importedMethodsInFlight.GetOrAdd(key, mine.Task);
if (!ReferenceEquals(existing, mine.Task))
{
Interlocked.Increment(ref _importedMethodsJoined);
return await existing.ConfigureAwait(false);
}
try
{
ServiceResult result;
try
{
result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started,
cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// DispatchImportedAsync answers every post-dispatch failure itself: anything escaping it was thrown before
// the port was called — nothing was sent (review S1/S3).
_logger.LogError(ex, "OtOpcUaNodeManager: imported condition method failed before dispatch");
result = Refuse(StatusCodes.BadInternalError);
}
mine.TrySetResult(result);
return result;
}
finally
{
_importedMethodsInFlight.TryRemove(new KeyValuePair<string, Task<ServiceResult>>(key, mine.Task));
}
}
catch (Exception ex) when (ex is ArgumentException or FormatException)
{
return Refuse(StatusCodes.BadInvalidArgument);
}
}
private async Task<ServiceResult> DispatchImportedAsync(IProjectedConditionMethods port, ImportedCondition condition,
ImportedConditionMethodRoute route, DataConditionMethods method, DataActivationMarker expected, string? comment,
RoleCarryingUserIdentity caller, DateTime deadline, long started, CancellationToken cancellationToken)
{
// Step 4: timeout = min(request deadline, ConditionMethodTimeout), as ONE end instant (review N7: elapsed time was
// subtracted from the request-deadline leg twice). When the request deadline binds, the grace the node manager waits
// past the budget is taken out of it, so the answer still lands inside the client's TimeoutHint.
var end = started + (long)(route.Timeout.TotalSeconds * Stopwatch.Frequency);
if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue)
{
var byDeadline = Stopwatch.GetTimestamp() + (long)((deadline - DateTime.UtcNow - ImportedMethodGrace).TotalSeconds * Stopwatch.Frequency);
if (byDeadline < end) end = byDeadline;
}
TimeSpan Remaining() => Stopwatch.GetElapsedTime(Stopwatch.GetTimestamp(), end);
if (Remaining() < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout);
// Review S4: the connection's sub-limit first, then the node-wide slots. Review S3: a cancel while WAITING is unsent.
var perConnection = _importedMethodConnectionSlots.GetOrAdd(condition.ConnectionId,
static _ => new SemaphoreSlim(DefaultImportedMethodConcurrencyPerConnection, DefaultImportedMethodConcurrencyPerConnection));
bool connectionSlot = false, nodeSlot = false;
try
{
try
{
connectionSlot = await perConnection.WaitAsync(Remaining() is var w && w > TimeSpan.Zero ? w : TimeSpan.Zero, cancellationToken)
.ConfigureAwait(false);
if (!connectionSlot) return Refuse(StatusCodes.BadTooManyOperations);
nodeSlot = await _importedMethodSlots.WaitAsync(Remaining() is var n && n > TimeSpan.Zero ? n : TimeSpan.Zero, cancellationToken)
.ConfigureAwait(false);
if (!nodeSlot) return Refuse(StatusCodes.BadTooManyOperations);
}
catch (OperationCanceledException)
{
return Refuse(StatusCodes.BadRequestCancelledByClient); // nothing sent
}
var remaining = Remaining();
if (remaining < ImportedMethodMinimumDispatchBudget) return Refuse(StatusCodes.BadTimeout); // review S4 floor: unsent
var call = new ImportedConditionMethodCall(condition.ConnectionId, condition.ConditionKey, route.Placement, method, expected,
comment, "a3-" + Guid.NewGuid().ToString("N"), remaining, caller.Principal);
using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
bounded.CancelAfter(remaining + ImportedMethodGrace);
Interlocked.Increment(ref _importedMethodsDispatched);
DataConditionMethodResult result;
try
{
result = await port.CallAsync(call, bounded.Token).WaitAsync(remaining + ImportedMethodGrace, CancellationToken.None)
.ConfigureAwait(false);
}
catch (TimeoutException)
{
// The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried.
// Review N1: WaitAsync and CancelAfter share a due time; cancel explicitly so the port's call ends with it.
bounded.Cancel();
return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout.");
}
catch (OperationCanceledException) when (bounded.IsCancellationRequested)
{
return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout,
"OutcomeUnknown: the call was cancelled after dispatch.");
}
catch (Exception ex)
{
// The port is contracted not to throw for a remote failure; one that does may have sent the request.
return Unknown(StatusCodes.BadCommunicationError, "OutcomeUnknown: " + ex.GetType().Name);
}
return MapOutcome(result);
}
finally
{
if (nodeSlot) _importedMethodSlots.Release();
if (connectionSlot) perConnection.Release();
}
}
/// <summary>
/// §5.6 step 5 outcome mapping. Applied (scripted <c>DriverConfirmedSuccess</c>) and accepted (native
/// <c>AcceptedUnconfirmed</c>) ⇒ Good — the confirming record arrives on the stream; <c>RejectedBeforeDispatch</c> and
/// <c>DriverConfirmedFailure</c> ⇒ the origin's status (review S3: a definite failure is not "unknown");
/// <c>OutcomeUnknown</c> ⇒ the status the transport KNEW (review S2: <c>BadTimeout</c> on a deadline, else
/// <c>BadCommunicationError</c>) — always Bad (the client must not read it as done), with "OutcomeUnknown" in the
/// diagnostic.
/// </summary>
internal ServiceResult MapOutcome(DataConditionMethodResult result)
{
switch (result.State)
{
case DataWriteState.DriverConfirmedSuccess:
case DataWriteState.AcceptedUnconfirmed:
return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good;
case DataWriteState.RejectedBeforeDispatch:
case DataWriteState.DriverConfirmedFailure:
var refused = new StatusCode(result.StatusCode);
if (!StatusCode.IsBad(refused)) refused = StatusCodes.BadInternalError;
return result.Diagnostic is { Length: > 0 } text ? new ServiceResult(refused, new LocalizedText(text)) : new ServiceResult(refused);
default:
var known = new StatusCode(result.StatusCode);
return Unknown(StatusCode.IsBad(known) && known.Code == StatusCodes.BadTimeout.Code ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError,
"OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown."));
}
}
private ServiceResult Unknown(StatusCode status, string diagnostic)
{
_logger.LogWarning("OtOpcUaNodeManager: imported condition method outcome unknown ({Status}): {Diagnostic}", status, diagnostic);
return new ServiceResult(status, new LocalizedText(diagnostic));
}
private ServiceResult Refuse(StatusCode status)
{
Interlocked.Increment(ref _importedMethodsRefused);
return new ServiceResult(status);
}
/// <summary>The Part 9 method a MethodId names: the type's declaration or this condition's instance child.</summary>
private static DataConditionMethods ImportedMethodOf(NodeId methodId, string conditionIdentifier)
{
if (methodId == MethodIds.AcknowledgeableConditionType_Acknowledge) return DataConditionMethods.Acknowledge;
if (methodId == MethodIds.AcknowledgeableConditionType_Confirm) return DataConditionMethods.Confirm;
if (methodId == MethodIds.ConditionType_AddComment) return DataConditionMethods.AddComment;
if (!methodId.TryGetValue(out string identifier)
|| !ImportedConditionIds.TryParse(identifier, out var owner, out _, out _, out var path)
|| !string.Equals(owner, conditionIdentifier, StringComparison.Ordinal)) return DataConditionMethods.None;
return path switch
{
"Acknowledge" => DataConditionMethods.Acknowledge,
"Confirm" => DataConditionMethods.Confirm,
"AddComment" => DataConditionMethods.AddComment,
_ => DataConditionMethods.None,
};
}
/// <summary>Acknowledge / Confirm / AddComment all take (EventId ByteString, Comment LocalizedText).</summary>
private static bool TryReadMethodArguments(ArrayOf<Variant> arguments, out ByteString eventId, out string? comment, out StatusCode error)
{
eventId = default; comment = null; error = StatusCodes.Good;
if (arguments.Count < 2) { error = StatusCodes.BadArgumentsMissing; return false; }
if (arguments.Count > 2) { error = StatusCodes.BadTooManyArguments; return false; }
if (!arguments[0].TryGetValue(out eventId) || eventId.IsEmpty) { error = StatusCodes.BadTypeMismatch; return false; }
if (arguments[1].IsNull) return true;
if (!arguments[1].TryGetValue(out LocalizedText text)) { error = StatusCodes.BadTypeMismatch; return false; }
comment = string.IsNullOrEmpty(text.Text) ? null : text.Text;
if (comment is { Length: > DataConditionMethodRequest.MaxCommentLength }) { error = StatusCodes.BadInvalidArgument; return false; }
return true;
}
/// <summary>
/// N6 (§5.6 step 3) after a record that changed no state. A moved marker re-binds the retained EventIds only when the
/// record's <c>time</c> equals the one they were bound under (F6); otherwise a fresh EventId is bound to the new marker
/// (so a ConditionRefresh returns an ackable one) and the caller queues RefreshRequired. A condition with no bound
/// EventId yet (its first record reported nothing) gets one. Under <c>Lock</c> (the apply path).
/// </summary>
/// <returns>True when retained EventIds were invalidated (RefreshRequired).</returns>
private bool RebindImportedEventIds(ImportedCondition condition, DataActivationMarker? previous, DateTimeOffset? previousTime,
DataConditionState state)
{
var current = state.Activation;
lock (condition.MethodGate)
{
if (condition.RecentEvents.Count == 0)
{
MintImportedEventId(condition, current);
return false;
}
if (previous == current) return false;
// Review N3: a marker appearing or disappearing is a marker change too — mint and refresh, never leave the current
// EventId bound to a marker no record carries. Review N2: re-binding (F6) is for an origin RESTART only — a new
// incarnation re-announcing the same state at the same time; a same-incarnation sequence bump is, by the origin's
// definition, a new occurrence.
if (previous is not null && current is not null && previous.Incarnation != current.Incarnation
&& state.TimeUtc is { } time && previousTime == time)
{
var node = condition.RecentEvents.First;
while (node is not null)
{
if (node.Value.Activation == previous) node.Value = (node.Value.EventId, current);
node = node.Next;
}
return false;
}
MintImportedEventId(condition, current);
return true;
}
}
private static void MintImportedEventId(ImportedCondition condition, DataActivationMarker? activation)
{
if (condition.Alarm.EventId is not { } field) return;
var eventId = ByteString.From(Guid.NewGuid().ToByteArray());
field.Value = eventId;
condition.RecentEvents.AddFirst((eventId, activation));
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
}
}
@@ -120,8 +120,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <see cref="V3NodeIds.UnsNamespaceUri"/> SECOND ([1]); <see cref="NamespaceIndexForRealm"/> maps a realm
/// to its index. Which realm a node belongs to travels with each sink call as an
/// <see cref="AddressSpaceRealm"/> — the namespace is never parsed back out of the id string.</summary>
// A3 (§5.2 N4): the imported-condition namespace is registered FIFTH ([4]). It has no realm — every classifier dispatches
// IsImportedConditionId BEFORE RealmOf (which folds every index other than 0/2 into Uns).
private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri,
ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri };
ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri, Core.Abstractions.DataConnections.ImportedConditionIds.NamespaceUri };
/// <summary>Transitional alias kept so the pre-v3 single-namespace integration tests
/// (<c>SubscriptionSurvivalTests</c>) still resolve a namespace index. It points at
@@ -286,6 +288,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// ones this manager mints into).</summary>
/// <param name="nodeId">The resolved SDK node id.</param>
/// <returns>The realm the node belongs to.</returns>
/// <remarks>⚠️ A3: an imported-condition id (<see cref="IsImportedConditionId"/>) has NO realm and must be dispatched before
/// this is asked; every classifier does (the authorizer intercepts the namespace before using the realm it is handed).</remarks>
private AddressSpaceRealm RealmOf(NodeId nodeId) =>
nodeId.NamespaceIndex == NamespaceIndexes[0] || nodeId.NamespaceIndex == NamespaceIndexes[2] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
@@ -821,6 +825,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
value.UnsSubjectResolver = ResolveUnsAclSubject;
value.MappedSubjectResolver = _mappedSubjectResolver;
value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant;
value.ImportedConditionClassifier = ClassifyImportedCondition; // A3: before RealmOf, always
}
_authorizer = value;
}
@@ -1361,63 +1366,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// NEVER passed through this method, so a last-written cache would be stale and
// wrongly report a delta. By the time the engine re-projects that ack here, the node already
// holds the acked state → no delta → suppress.
var current = ReadConditionDelta(condition);
var incoming = ToConditionDelta(state, condition);
bool fire = ShouldFireConditionEvent(current, incoming);
// EnabledState / AckedState / ActiveState are mandatory children — always present after
// Create. Confirm + Shelving are optional Part 9 children: T14's real-server finding is
// that Create auto-builds them for our subtypes, but a base AlarmConditionState (or a
// future SDK that builds a leaner child set) may leave them null. Null-guard each optional
// child so projecting Confirmed/Shelving onto a node that lacks the sub-state machine is a
// no-op rather than an NRE.
condition.SetEnableState(SystemContext, state.Enabled);
condition.SetActiveState(SystemContext, state.Active);
condition.SetAcknowledgedState(SystemContext, state.Acknowledged);
if (condition.ConfirmedState is not null)
{
condition.SetConfirmedState(SystemContext, state.Confirmed);
}
// A1 review nit: the absolute timed-shelve expiry rides the condition-state record (A2 projects it).
if (state.Shelving == AlarmShelvingKind.Timed && state.UnshelveAtUtc is { } unshelveAt) _conditionUnshelveAt[key] = unshelveAt;
else _conditionUnshelveAt.Remove(key);
if (condition.ShelvingState is not null)
{
// SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's
// (shelved, oneShot) flag pair. Timed shelving's expiry is owned by the engine; the time
// passed here is the engine's remaining time, so the node's UnshelveTime counts down to the
// real expiry (a 0 here reads as MaxTimeShelved, ~24.8 days). The SDK timer it
// arms does nothing (OnTimedUnshelve is a no-op): the engine's own expiry re-projects.
condition.SetShelvingState(
SystemContext,
shelved: state.Shelving != AlarmShelvingKind.Unshelved,
oneShot: state.Shelving == AlarmShelvingKind.OneShot,
shelvingTime: state.Shelving == AlarmShelvingKind.Timed ? RemainingShelveMs(state.UnshelveAtUtc, UtcNow) : 0);
}
condition.SetSeverity(SystemContext, ToPart9Severity(state.Severity));
condition.Message!.Value = new LocalizedText(state.Message);
// #839: a classifying native source's Part 9 ConditionClass. Null leaves the node's class as it is
// (BaseConditionClass from materialise, or what an earlier event set). Not in the delta-gate: a class
// rides along with the transition that set it and never fires an event on its own.
if (state.ConditionClass is { } conditionClass) ApplyConditionClass(condition, conditionClass);
// Project the source-data quality. A Good→Bad bucket change is a genuine condition
// change (it's in the delta-gate above), so it fires a Part 9 event carrying the new Quality;
// it never touches Active/Acked/Retain (annotation only). Quality is an optional Part 9 child —
// null-guard it like Confirmed/Shelving in case a leaner SDK child set omits it.
if (condition.Quality is not null)
{
condition.Quality.Value = new StatusCode(state.StatusCode);
if (condition.Quality.SourceTimestamp is not null) condition.Quality.SourceTimestamp.Value = sourceTimestampUtc;
}
// Part 9: retain the condition while it is active OR unacknowledged so a client's
// ConditionRefresh replays it. The event firing below also depends on this Retain being
// correct (a non-retained inactive+acked condition still fires its transition event, but
// won't be replayed on a later ConditionRefresh).
condition.Retain!.Value = state.Active || !state.Acknowledged;
condition.Time!.Value = sourceTimestampUtc;
condition.ReceiveTime!.Value = sourceTimestampUtc;
// A3 (§5.3): the state-apply + #656 delta gate is shared with imported conditions (ApplyConditionState).
bool fire = ApplyConditionState(condition, state, sourceTimestampUtc);
// T20 — fire a real Part 9 condition event ONLY when this projection is a genuine state
// change (the delta-gate decided above, against the node's pre-projection state). A
@@ -1447,6 +1400,71 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
}
/// <summary>
/// Projects <paramref name="state"/> onto <paramref name="condition"/> and decides, against the node's state BEFORE the
/// projection, whether it is a genuine transition (the T20 / #656 delta gate). Shared by <see cref="WriteAlarmCondition(string, AlarmConditionSnapshot, DateTime, AddressSpaceRealm, bool)"/>
/// and the A3 imported-condition registry so both use exactly one gate. Caller holds <c>Lock</c>.
/// </summary>
/// <returns><see langword="true"/> when the projection is a genuine change that must be reported as one event.</returns>
private bool ApplyConditionState(AlarmConditionState condition, AlarmConditionSnapshot state, DateTime sourceTimestampUtc)
{
var current = ReadConditionDelta(condition);
var incoming = ToConditionDelta(state, condition);
bool fire = ShouldFireConditionEvent(current, incoming);
// EnabledState / AckedState / ActiveState are mandatory children — always present after
// Create. Confirm + Shelving are optional Part 9 children: T14's real-server finding is
// that Create auto-builds them for our subtypes, but a base AlarmConditionState (or a
// future SDK that builds a leaner child set) may leave them null. Null-guard each optional
// child so projecting Confirmed/Shelving onto a node that lacks the sub-state machine is a
// no-op rather than an NRE.
condition.SetEnableState(SystemContext, state.Enabled);
condition.SetActiveState(SystemContext, state.Active);
condition.SetAcknowledgedState(SystemContext, state.Acknowledged);
if (condition.ConfirmedState is not null)
{
condition.SetConfirmedState(SystemContext, state.Confirmed);
}
if (condition.ShelvingState is not null)
{
// SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's
// (shelved, oneShot) flag pair. Timed shelving's expiry is owned by the engine; the time
// passed here is the engine's remaining time, so the node's UnshelveTime counts down to the
// real expiry (a 0 here reads as MaxTimeShelved, ~24.8 days). The SDK timer it
// arms does nothing (OnTimedUnshelve is a no-op): the engine's own expiry re-projects.
condition.SetShelvingState(
SystemContext,
shelved: state.Shelving != AlarmShelvingKind.Unshelved,
oneShot: state.Shelving == AlarmShelvingKind.OneShot,
shelvingTime: state.Shelving == AlarmShelvingKind.Timed ? RemainingShelveMs(state.UnshelveAtUtc, UtcNow) : 0);
}
condition.SetSeverity(SystemContext, ToPart9Severity(state.Severity));
condition.Message!.Value = new LocalizedText(state.Message);
// #839: a classifying native source's Part 9 ConditionClass. Null leaves the node's class as it is
// (BaseConditionClass from materialise, or what an earlier event set). Not in the delta-gate: a class
// rides along with the transition that set it and never fires an event on its own.
if (state.ConditionClass is { } conditionClass) ApplyConditionClass(condition, conditionClass);
// Project the source-data quality. A Good→Bad bucket change is a genuine condition
// change (it's in the delta-gate above), so it fires a Part 9 event carrying the new Quality;
// it never touches Active/Acked/Retain (annotation only). Quality is an optional Part 9 child —
// null-guard it like Confirmed/Shelving in case a leaner SDK child set omits it.
if (condition.Quality is not null)
{
condition.Quality.Value = new StatusCode(state.StatusCode);
if (condition.Quality.SourceTimestamp is not null) condition.Quality.SourceTimestamp.Value = sourceTimestampUtc;
}
// Part 9: retain the condition while it is active OR unacknowledged so a client's
// ConditionRefresh replays it. The event firing below also depends on this Retain being
// correct (a non-retained inactive+acked condition still fires its transition event, but
// won't be replayed on a later ConditionRefresh).
condition.Retain!.Value = state.Active || !state.Acknowledged;
condition.Time!.Value = sourceTimestampUtc;
condition.ReceiveTime!.Value = sourceTimestampUtc;
return fire;
}
/// <summary>
/// The Part 9 class type id + browse name of an <see cref="AlarmConditionClass"/> (lmxopcua#839).
/// </summary>
@@ -1918,6 +1936,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// </summary>
private void QueueToItem(IEventMonitoredItem item, IFilterTarget e)
{
if (ImportedOf(e) is { } imported)
{
QueueImportedToItem(item, e, imported);
return;
}
if (e is ConditionEventSnapshot snapshot)
{
if (snapshot.DeliveryCache.Queue(Server, item, e, UseProjectedEventDelivery)) Interlocked.Increment(ref _projectedDeliveries);
@@ -2017,7 +2041,11 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// legitimate notifier of it, and its visibility scopes — is resolved ONCE per hop, not per item (it is what
// IsNotifierEventVisibleTo resolves for an item attached here). Only the grant check and the SDK's role check
// remain per item.
var enforced = AclEnforced;
// A3 (§5.4): an imported condition reaches a projected folder's items only while the registry wires it there, and
// each item passes the mapping gate — ACLs on or off.
var imported = ImportedOf(e);
if (imported is not null && !_importedConditions.IsWiredTo(imported, monitored.Node)) return;
var enforced = AclEnforced && imported is null;
List<NodeId>? scopes = null;
if (enforced)
{
@@ -2040,6 +2068,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (IsAuditEvent(e) && !IsAuditDeliverableTo(item)) continue;
if (!RoleAllows(item, e)) continue;
if (scopes is not null && !IsConditionVisibleTo(item, scopes, visibleByIdentity!)) continue;
if (imported is not null && !ImportedVisibleTo(item, imported)) continue;
QueueConditionEventToItem(item, e, deferred, DeferredFolderDeliveryProbe);
}
catch (Exception ex)
@@ -2062,7 +2091,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <summary>Whether <paramref name="condition"/> is the instance the address space currently holds for its NodeId.</summary>
private bool IsLiveCondition(NodeState condition) =>
_alarmConditions.TryGetValue(MapKey(condition.NodeId), out var live) && ReferenceEquals(live, condition);
IsImportedConditionId(condition.NodeId)
? _importedConditions.IsLive(condition)
: _alarmConditions.TryGetValue(MapKey(condition.NodeId), out var live) && ReferenceEquals(live, condition);
/// <summary>Adjusts the deferred depth and logs episode entry/exit. Under the gate.</summary>
private void CountDeferred(int delta, AlarmConditionState condition)
@@ -2402,6 +2433,106 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return AlarmShelvingKind.Unshelved;
}
/// <summary>
/// Builds one Part 9 condition node — type, the optional children added before <c>Create()</c>, child ids
/// (<see cref="New"/>), and the initial field values. Shared by <see cref="MaterialiseAlarmCondition"/> and the A3
/// imported-condition registry (one helper, so an imported condition has exactly a local one's shape). Caller holds
/// <c>Lock</c>; the caller wires handlers and parents/registers the node.
/// </summary>
private AlarmConditionState CreateConditionNode(string alarmType, NodeState? parent, NodeId nodeId, string displayName,
string sourceName, int severity, bool isNative)
{
AlarmConditionState alarm = CreateAlarmConditionOfType(alarmType, parent);
// SDK 2.0 creates optional confirmation nodes only when requested explicitly.
// Both are part of the application's existing Part 9 method/state contract.
alarm.ConfirmedState = new TwoStateVariableState(alarm);
alarm.Confirm = new AddCommentMethodState(alarm);
alarm.ShelvingState = new ShelvedStateMachineState(alarm);
alarm.MaxTimeShelved = new PropertyState<double>.Implementation<VariantBuilder>(alarm);
alarm.SymbolicName = displayName;
// Create builds the full mandatory Part 9 child set (EnabledState, AckedState,
// ActiveState, the Acknowledge/Confirm/AddComment/Enable/Disable methods, ...) from the
// type's embedded definition; we do not hand-build them.
alarm.Create(
SystemContext,
nodeId,
new QualifiedName(displayName, nodeId.NamespaceIndex),
new LocalizedText(displayName),
assignNodeIds: true);
// Create initializes the embedded definition and resets ReferenceTypeId in SDK 2.0.1.
// Restore the application's parent ownership before AddChild: hierarchical folder browses
// must expose the alarm as a HasComponent object, as they did before the SDK upgrade.
alarm.ReferenceTypeId = ReferenceTypeIds.HasComponent;
// Main-branch id MUST be a concrete (null) NodeId before any Set* call: SetEnableState ->
// UpdateRetainState -> GetRetainState -> IsBranch() dereferences BranchId.Value, which
// Create leaves as a null reference and would NRE. NodeId.Null marks "the main branch".
// (Real-server finding from the T14 integration test — not obvious from the SDK notes.)
if (alarm.BranchId is not null) alarm.BranchId.Value = NodeId.Null;
// The mandatory BaseEventType identity fields. Create() builds these three children from
// the type's embedded definition but leaves them UNSET (the init string declares them mandatory
// with NO default), and nothing downstream fills them in: the auto-filling
// BaseEventState.Initialize(context, source, severity, message) overload is only used for
// transient events, and ReportEvent / InstanceStateSnapshot copy the children verbatim. Unset
// here ⇒ null on the wire on EVERY condition event, so a client cannot attribute the alarm.
// SourceNode — the condition's OWN NodeId (== ConditionId): the condition IS the source. An
// alarm-bearing raw tag materialises ONLY this condition, with no sibling value
// variable (see AddressSpaceApplier's alarm branch), so there is no other node.
// SourceName — the same identifying id string (RawPath native / ScriptedAlarmId scripted).
// Deliberately the UNIQUE id, NOT the leaf: the leaf collides across devices and
// is already carried by ConditionName below. See docs/AlarmTracking.md.
alarm.EventType!.Value = alarm.TypeDefinitionId;
alarm.SourceNode!.Value = alarm.NodeId; // Create() assigned this above; do not rebuild it
alarm.SourceName!.Value = sourceName;
// The mandatory ConditionType classification fields, unset by Create() for the same reason as
// the fields above (mandatory, no default, nothing downstream synthesises them) ⇒ NodeId.Null + empty
// text on the wire, which buckets every alarm as unclassified in a Part 9 HMI.
// BaseConditionClassType is Part 9's "no class modelled" value and is the honest report: we hold no
// classification at this seam. Deliberately NOT ProcessConditionClassType (the SDK sample's pick) — it
// would assert a classification we cannot back, and would be actively wrong for a Galaxy alarm whose
// upstream category is Safety/Diagnostics. Per-alarm classification arrives at RUNTIME instead: a
// classifying native driver states AlarmEventArgs.ConditionClass on its transitions (#839, Heidenhain),
// which WriteAlarmCondition applies over this default — the deploy-time seam still holds none.
if (alarm.ConditionClassId is not null) alarm.ConditionClassId.Value = ObjectTypeIds.BaseConditionClassType;
if (alarm.ConditionClassName is not null) alarm.ConditionClassName.Value = new LocalizedText("BaseConditionClass");
// ConditionType.Quality (the quality of the condition's source data). Create() leaves it
// UNSET, and default(StatusCode) == StatusCodes.Good (0x0), so an unassigned Quality reports Good
// unconditionally — a wrong VALUE (not a null), which hides a comms-lost source. A NATIVE condition
// has no data yet at materialise (its driver hasn't confirmed connectivity), so it starts
// BadWaitingForInitialData — the same "no driver data yet" convention value variables use — and is
// driven Good by the driver-connectivity path (DriverHostActor → ProjectQuality) once Connected. A
// SCRIPTED condition is script-computed and always live in v1, so it starts Good. Quality is a pure
// annotation: it NEVER alters Active/Acked/Retain (a comms-lost active alarm must stay active).
if (alarm.Quality is not null)
{
alarm.Quality.Value = isNative ? StatusCodes.BadWaitingForInitialData : StatusCodes.Good;
if (alarm.Quality.SourceTimestamp is not null) alarm.Quality.SourceTimestamp.Value = UtcNow;
}
// Initial state via the SDK setters (T14: basic state only, NO event firing).
alarm.SetEnableState(SystemContext, true);
alarm.SetActiveState(SystemContext, false);
alarm.SetAcknowledgedState(SystemContext, true);
// A native condition is never Unconfirmed: it has no confirm workflow — Confirm is
// refused and Acknowledge re-asserts Confirmed — so start it Confirmed, the value NativeAlarmProjector
// supplies on every transition, rather than the SDK's default false until the first projection.
if (isNative && alarm.ConfirmedState is not null) alarm.SetConfirmedState(SystemContext, true);
alarm.SetSeverity(SystemContext, ToPart9Severity(severity));
// Create() leaves MaxTimeShelved at 0, and the SDK's
// TimedShelve handler rejects any ShelvingTime above it — so every client TimedShelve failed with
// BadShelvingTimeOutOfRange. The bound becomes the longest shelve the SDK's own shelving timer can
// represent (int.MaxValue ms ≈ 24.8 days, the same ceiling SetShelvingState already saturated a 0 to).
if (alarm.MaxTimeShelved is { } maxTimeShelved && maxTimeShelved.Value <= 0)
maxTimeShelved.Value = int.MaxValue;
alarm.Retain!.Value = false; // inactive + acked ⇒ nothing to retain yet
alarm.Message!.Value = new LocalizedText(displayName);
if (alarm.ConditionName is not null) alarm.ConditionName.Value = displayName;
return alarm;
}
/// <summary>
/// Materialise a real OPC UA Part 9 <see cref="AlarmConditionState"/> node under its equipment
/// folder so clients can browse it as a proper condition (and subscribe to its events). The node
@@ -2488,94 +2619,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var parent = ResolveParentFolder(equipmentNodeId, realm);
AlarmConditionState alarm = CreateAlarmConditionOfType(alarmType, parent);
// SDK 2.0 creates optional confirmation nodes only when requested explicitly.
// Both are part of the application's existing Part 9 method/state contract.
alarm.ConfirmedState = new TwoStateVariableState(alarm);
alarm.Confirm = new AddCommentMethodState(alarm);
alarm.ShelvingState = new ShelvedStateMachineState(alarm);
alarm.MaxTimeShelved = new PropertyState<double>.Implementation<VariantBuilder>(alarm);
alarm.SymbolicName = displayName;
// Create builds the full mandatory Part 9 child set (EnabledState, AckedState,
// ActiveState, the Acknowledge/Confirm/AddComment/Enable/Disable methods, ...) from the
// type's embedded definition; we do not hand-build them.
alarm.Create(
SystemContext,
new NodeId(alarmNodeId, ns),
new QualifiedName(displayName, ns),
new LocalizedText(displayName),
assignNodeIds: true);
// Create initializes the embedded definition and resets ReferenceTypeId in SDK 2.0.1.
// Restore the application's parent ownership before AddChild: hierarchical folder browses
// must expose the alarm as a HasComponent object, as they did before the SDK upgrade.
alarm.ReferenceTypeId = ReferenceTypeIds.HasComponent;
// Main-branch id MUST be a concrete (null) NodeId before any Set* call: SetEnableState ->
// UpdateRetainState -> GetRetainState -> IsBranch() dereferences BranchId.Value, which
// Create leaves as a null reference and would NRE. NodeId.Null marks "the main branch".
// (Real-server finding from the T14 integration test — not obvious from the SDK notes.)
if (alarm.BranchId is not null) alarm.BranchId.Value = NodeId.Null;
// The mandatory BaseEventType identity fields. Create() builds these three children from
// the type's embedded definition but leaves them UNSET (the init string declares them mandatory
// with NO default), and nothing downstream fills them in: the auto-filling
// BaseEventState.Initialize(context, source, severity, message) overload is only used for
// transient events, and ReportEvent / InstanceStateSnapshot copy the children verbatim. Unset
// here ⇒ null on the wire on EVERY condition event, so a client cannot attribute the alarm.
// SourceNode — the condition's OWN NodeId (== ConditionId): the condition IS the source. An
// alarm-bearing raw tag materialises ONLY this condition, with no sibling value
// variable (see AddressSpaceApplier's alarm branch), so there is no other node.
// SourceName — the same identifying id string (RawPath native / ScriptedAlarmId scripted).
// Deliberately the UNIQUE id, NOT the leaf: the leaf collides across devices and
// is already carried by ConditionName below. See docs/AlarmTracking.md.
alarm.EventType!.Value = alarm.TypeDefinitionId;
alarm.SourceNode!.Value = alarm.NodeId; // Create() assigned this above; do not rebuild it
alarm.SourceName!.Value = alarmNodeId;
// The mandatory ConditionType classification fields, unset by Create() for the same reason as
// the fields above (mandatory, no default, nothing downstream synthesises them) ⇒ NodeId.Null + empty
// text on the wire, which buckets every alarm as unclassified in a Part 9 HMI.
// BaseConditionClassType is Part 9's "no class modelled" value and is the honest report: we hold no
// classification at this seam. Deliberately NOT ProcessConditionClassType (the SDK sample's pick) — it
// would assert a classification we cannot back, and would be actively wrong for a Galaxy alarm whose
// upstream category is Safety/Diagnostics. Per-alarm classification arrives at RUNTIME instead: a
// classifying native driver states AlarmEventArgs.ConditionClass on its transitions (#839, Heidenhain),
// which WriteAlarmCondition applies over this default — the deploy-time seam still holds none.
if (alarm.ConditionClassId is not null) alarm.ConditionClassId.Value = ObjectTypeIds.BaseConditionClassType;
if (alarm.ConditionClassName is not null) alarm.ConditionClassName.Value = new LocalizedText("BaseConditionClass");
// ConditionType.Quality (the quality of the condition's source data). Create() leaves it
// UNSET, and default(StatusCode) == StatusCodes.Good (0x0), so an unassigned Quality reports Good
// unconditionally — a wrong VALUE (not a null), which hides a comms-lost source. A NATIVE condition
// has no data yet at materialise (its driver hasn't confirmed connectivity), so it starts
// BadWaitingForInitialData — the same "no driver data yet" convention value variables use — and is
// driven Good by the driver-connectivity path (DriverHostActor → ProjectQuality) once Connected. A
// SCRIPTED condition is script-computed and always live in v1, so it starts Good. Quality is a pure
// annotation: it NEVER alters Active/Acked/Retain (a comms-lost active alarm must stay active).
if (alarm.Quality is not null)
{
alarm.Quality.Value = isNative ? StatusCodes.BadWaitingForInitialData : StatusCodes.Good;
if (alarm.Quality.SourceTimestamp is not null) alarm.Quality.SourceTimestamp.Value = UtcNow;
}
// Initial state via the SDK setters (T14: basic state only, NO event firing).
alarm.SetEnableState(SystemContext, true);
alarm.SetActiveState(SystemContext, false);
alarm.SetAcknowledgedState(SystemContext, true);
// A native condition is never Unconfirmed: it has no confirm workflow — Confirm is
// refused and Acknowledge re-asserts Confirmed — so start it Confirmed, the value NativeAlarmProjector
// supplies on every transition, rather than the SDK's default false until the first projection.
if (isNative && alarm.ConfirmedState is not null) alarm.SetConfirmedState(SystemContext, true);
alarm.SetSeverity(SystemContext, ToPart9Severity(severity));
// Create() leaves MaxTimeShelved at 0, and the SDK's
// TimedShelve handler rejects any ShelvingTime above it — so every client TimedShelve failed with
// BadShelvingTimeOutOfRange. The bound becomes the longest shelve the SDK's own shelving timer can
// represent (int.MaxValue ms ≈ 24.8 days, the same ceiling SetShelvingState already saturated a 0 to).
if (alarm.MaxTimeShelved is { } maxTimeShelved && maxTimeShelved.Value <= 0)
maxTimeShelved.Value = int.MaxValue;
alarm.Retain!.Value = false; // inactive + acked ⇒ nothing to retain yet
alarm.Message!.Value = new LocalizedText(displayName);
if (alarm.ConditionName is not null) alarm.ConditionName.Value = displayName;
// A3 (§5.3): field/child-id assignment is shared with imported conditions (CreateConditionNode).
AlarmConditionState alarm = CreateConditionNode(alarmType, parent, new NodeId(alarmNodeId, ns), displayName, alarmNodeId, severity, isNative);
// T18 — inbound Part 9 method handlers. Create() materialised the Acknowledge/Confirm/
// AddComment/Shelve/Unshelve method nodes and the condition types wired their built-in OnCall
@@ -4067,7 +4112,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
/// <summary>Map our domain <c>AlarmType</c> string to the matching SDK condition subtype. Script
/// alarms have no OPC limit/setpoint values, so limit-style types fall back to the base
/// <see cref="AlarmConditionState"/> (see <see cref="MaterialiseAlarmCondition"/> remarks).</summary>
private static AlarmConditionState CreateAlarmConditionOfType(string alarmType, NodeState parent) =>
private static AlarmConditionState CreateAlarmConditionOfType(string alarmType, NodeState? parent) =>
ApplicationAlarmConditions.Create(alarmType, parent);
/// <summary>
@@ -4291,6 +4336,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
parent.AddChild(folder); AddPredefinedNode(SystemContext, folder);
_projectedAnchors[id] = (definition, folder);
_projectedNodeCharges.Add(id, charge); _projectedNodeBytes += charge;
OnProjectedFolderMaterialised(folder, definition.MappingId, definition.LocalSubject); // A3 N7
nodeId = id; return true;
}
}
@@ -4319,12 +4365,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
if (_projectedVariables.Remove(id, out var child))
{
OnProjectedFolderRemoving(id); // A3 N7: a removed mapping unwires even a pinned folder
if (_projectedDefinitions.Remove(id, out var definition)) RetireProjectedCharge(id, definition.Lifetime);
RemoveProjectedSample(id);
TombstoneMonitoredNode(id, UtcNow);
child.Node.Parent?.RemoveChild(child.Node); PredefinedNodes?.Remove(id);
}
}
OnProjectedFolderRemoving(nodeId);
_projectedAnchors.TryRemove(nodeId, out _);
_projectedRootLeaves.TryRemove(nodeId, out _);
RetireProjectedCharge(nodeId, anchor.Definition.Lifetime);
@@ -4412,9 +4460,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true;
foreach (var pair in _projectedDefinitions.ToArray())
{
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() ||
if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
_projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue;
if (!_projectedVariables.Remove(pair.Key, out var entry)) continue;
OnProjectedFolderRemoving(pair.Key);
_projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
RemoveCommittedProjectedDefinition(pair.Key);
if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes;
@@ -4423,9 +4472,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
}
foreach (var pair in _projectedAnchors.ToArray())
{
if (pair.Value.Definition.AuthorityIsCurrent() ||
if (pair.Value.Definition.AuthorityIsCurrent() || IsPinnedEventFolder(pair.Key) ||
_projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue;
if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue;
OnProjectedFolderRemoving(pair.Key);
if (_projectedRootLeaves.TryRemove(pair.Key, out _))
{
_projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key);
@@ -4799,6 +4849,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var id in added)
{
if (!_projectedVariables.Remove(id, out var entry)) continue;
OnProjectedFolderRemoving(id);
RemoveProjectedSample(id);
_projectedDefinitions.Remove(id);
if (_projectedNodeCharges.Remove(id, out var charge)) _projectedNodeBytes -= charge;
@@ -4909,7 +4960,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
lock (Lock)
{
if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) ||
IsPinnedEventFolder(nodeId) || // A3 N7: a folder holding an admitted event item is not retired
_projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false;
OnProjectedFolderRemoving(nodeId);
_projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime);
TombstoneMonitoredNode(nodeId, UtcNow);
entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(nodeId);
@@ -4976,6 +5029,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
_projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent));
_projectedDefinitions.Add(candidate, definition);
_projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge;
if (node is FolderState projectedFolder && definition.Metadata.View.MappingId is { } folderMapping)
OnProjectedFolderMaterialised(projectedFolder, folderMapping, definition.Metadata.View.Subject); // A3 N7
if (!stage) CommitProjectedDefinition(candidate, definition);
nodeId = candidate; return true;
}
@@ -5600,6 +5655,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray();
Volatile.Write(ref _committedProjectedDefinitions, _committedProjectedDefinitions.Clear());
foreach (var item in _liveItems.Keys.OfType<ProjectedMonitoredItem>()) item.Retire();
UnwireAllImportedFolders(); // A3 review r1 S1: the folders go; their notifier wiring and promotion go with them
foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id);
foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id);
foreach (var (id, definition) in _projectedDefinitions) RetireProjectedCharge(id, definition.Lifetime);
@@ -5996,7 +6052,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
private bool OwnsNamespace(NodeId? nodeId) =>
nodeId is { } id
&& (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1] ||
id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3]);
id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3] ||
// A3: the imported-condition namespace is ours too — without it a condition's children keep their type ids and
// every Permits() would pass an imported id as "not ours to gate".
(NamespaceIndexes.Count > 4 && id.NamespaceIndex == NamespaceIndexes[4]));
/// <summary>Pulls the ACL identity off an SDK operation context.</summary>
/// <param name="context">The SDK context carrying the session identity.</param>
@@ -6019,6 +6078,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
{
if (!OwnsNamespace(nodeId)) return true;
// A3 (§5.2): the imported-condition namespace has no realm — classified BEFORE RealmOf, ACLs on or off.
if (IsImportedConditionId(nodeId)) return AuthorizeImportedCondition(identity, operation, nodeId);
var realm = RealmOf(nodeId);
if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse)
{
@@ -6498,7 +6559,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
//
// Only creation is gated. Refusing an UNSUBSCRIBE would strand the item on a node the session can
// no longer reach — the client could never detach it, and the server would keep delivering.
if (SecurityFilteringActive && !unsubscribe
// A3 (§5.4): an event item on a projected notifier (a folder wired for imported conditions) is admitted through the
// verified path — the mapping gate of some condition wired there at subscribe time, per event at delivery and again
// at publish — instead of the mapped blanket deny that still applies to data items.
var projectedNotifier = !unsubscribe && IsHandleInNamespace(sourceId) is { } candidate && IsProjectedEventNotifier(candidate.NodeId)
? candidate.NodeId : (NodeId?)null;
if (projectedNotifier is { } notifierId)
{
if (!ImportedNotifierAdmits(IdentityOf(context), notifierId)) return StatusCodes.BadUserAccessDenied;
}
else if (SecurityFilteringActive && !unsubscribe
&& IsHandleInNamespace(sourceId) is { } source
&& !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, source.NodeId))
{
@@ -6507,6 +6577,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (unsubscribe)
{
// A3 review r1 B3: the item's condition demand goes FIRST — both early returns below skip the base call, and a
// lease released only after them leaked (demand never reached 0, streams and conditions held forever).
TrackImportedDemand(monitoredItem, unsubscribe: true);
// An item RevalidateMonitoredItems stood down is ALREADY off its notifier's fan-out, and so is
// one whose notifier a rebuild / surgical remove tombstoned (review 01 L2, TombstoneMonitoredNode).
// Handing either delete to the SDK would make it remove an item that is not there — at best a
@@ -6535,6 +6609,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var result = base.SubscribeToEvents(context, sourceId, subscriptionId, monitoredItem, unsubscribe);
TrackLiveEventItem(sourceId, monitoredItem);
if (projectedNotifier is not null && ServiceResult.IsGood(result)) TrackImportedDemand(monitoredItem, unsubscribe: false);
return result;
}
@@ -7062,6 +7137,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
ReconcileAllEventsMonitoring();
}
// A3 (§5.5): a Server-object event item could see imported conditions — it opens (or releases) per-connection demand.
// Off Lock: the access never blocks, but it is not ours to call under Lock.
TrackImportedDemand(monitoredItem, unsubscribe);
return ServiceResult.Good;
}
@@ -7230,10 +7309,12 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
// through its OLD equipment folder (#808).
if (!IsLiveCondition(node)) return;
// A3 (§5.4): an imported condition is gated per item by the mapping gate, ACLs on or off.
var imported = _importedConditions.Find(node);
List<NodeId>? scopes;
try
{
scopes = AclEnforced ? ConditionVisibilityScopes(node) : null;
scopes = imported is null && AclEnforced ? ConditionVisibilityScopes(node) : null;
}
catch (Exception ex)
{
@@ -7252,6 +7333,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
{
if (e is AuditEventState && !IsAuditDeliverableTo(item)) continue;
if (scopes is not null && !IsConditionVisibleTo(item, scopes, visibleByIdentity!)) continue;
if (imported is not null && !ImportedVisibleTo(item, imported)) continue;
if (!RoleAllows(item, e)) continue;
if (reportingSession is { IsNull: false } reportingId
&& item.Session?.Id is { } own
@@ -7848,6 +7930,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (direct.Count > 0) RefreshDirectItems(systemContext, direct, enforced);
if (serverItems.Count > 0) RefreshServerObjectItems(systemContext, serverItems, enforced);
// A3 (§5.4): imported conditions are replayed through the gated, marked path, ACLs on or off.
ReplayImportedConditions(serverItems, direct);
return ServiceResult.Good;
}
finally
@@ -7953,7 +8037,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var (e, _, scopes) in replay)
{
// #855 review 3: never replay a condition a deploy removed or replaced since the walk collected it.
if (ConditionOf(e) is AlarmConditionState walked && !IsLiveCondition(walked)) continue;
if (ConditionOf(e) is AlarmConditionState walked && (IsImportedConditionId(walked.NodeId) || !IsLiveCondition(walked))) continue;
if (scopes is not null && !IsConditionVisibleTo(item, scopes)) continue;
if (ServiceResult.IsBad(ValidateEventRolePermissions(item, e))) continue;
item.QueueEvent(e);
@@ -8238,7 +8322,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var e in events)
{
// #855 review 3: never replay a condition a deploy removed or replaced since the walk collected it.
if (ConditionOf(e) is AlarmConditionState walked && !IsLiveCondition(walked)) continue;
if (ConditionOf(e) is AlarmConditionState walked && (IsImportedConditionId(walked.NodeId) || !IsLiveCondition(walked))) continue;
if (!IsDirectRefreshEventAllowed(item, e, enforced)) continue;
item.QueueEvent(e);
}
@@ -8347,6 +8431,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var target in live)
{
if (target is not BaseInstanceState instance) continue;
if (IsImportedConditionId(instance.NodeId)) continue; // A3: replayed through the marked path only
// A condition materialised since the verdicts were taken is decided here (rare).
if (!allowed.Contains((item, instance)))
{
@@ -8622,7 +8707,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
if (eventsStoodDown > 0 || eventsRestored > 0)
{
_authorizer!.LogFiltered(
// An imported-notifier item is revalidated through the imported gate even where no authorizer is wired (A3 r1 B3).
_authorizer?.LogFiltered(
"RevalidateEventSubscriptions", principal: null, eventsStoodDown, _eventItems.Count);
}
}
@@ -8672,8 +8758,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
foreach (var (item, tracked) in _eventItems)
{
var permitted = IsSubscriptionStillPermitted(
item.EffectiveIdentity as RoleCarryingUserIdentity, tracked.Handle.NodeId, verdicts);
// A3 review r1 B3: an item on a projected notifier was admitted through the imported gate, not Permits (which
// blanket-denies a mapped CreateMonitoredItems) — revalidate it through the same gate, or every admitted folder
// item is stood down on the next ACL tick or deploy.
var identity = item.EffectiveIdentity as RoleCarryingUserIdentity;
var permitted = IsProjectedEventNotifier(tracked.Handle.NodeId)
? ImportedNotifierAdmits(identity, tracked.Handle.NodeId)
: IsSubscriptionStillPermitted(identity, tracked.Handle.NodeId, verdicts);
if (permitted != tracked.Suppressed) continue;
lock (Lock)
@@ -743,7 +743,7 @@ public sealed class OtOpcUaSdkServer : StandardServer
var response = await base.PublishAsync(secureChannelContext, requestHeader, subscriptionAcknowledgements, requestLifetime)
.ConfigureAwait(false);
if (response?.NotificationMessage is { } projectedMessage)
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false);
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false, ImportedGateFor(requestHeader));
if (_standby.Delivery is not { } record || response?.NotificationMessage is not { } message) return response!;
if (message.NotificationData.Count > 0)
@@ -765,12 +765,29 @@ public sealed class OtOpcUaSdkServer : StandardServer
var response = await base.RepublishAsync(secureChannelContext, requestHeader, subscriptionId, retransmitSequenceNumber,
requestLifetime).ConfigureAwait(false);
if (response?.NotificationMessage is { } projectedMessage)
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true);
response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true, ImportedGateFor(requestHeader));
if (_standby.Delivery is { } record && response?.NotificationMessage is { NotificationData.Count: > 0 } message)
response.NotificationMessage = Decide(record, subscriptionId, message);
return response!;
}
/// <summary>
/// A3 (§5.4): the publishing session's gate for UNMARKED imported-condition event lists (a select-clause modify rebuilt
/// them). Null when no imported condition exists (v1 path, nothing to judge).
/// </summary>
private Func<EventFieldList, bool?>? ImportedGateFor(RequestHeader? requestHeader)
{
if (NodeManager is not { HasImportedConditions: true } nm) return null;
object? identity = null;
try
{
if (requestHeader?.AuthenticationToken is { IsNull: false } token)
identity = ServerInternal?.SessionManager?.GetSession(token)?.EffectiveIdentity;
}
catch (Exception) { identity = null; }
return list => nm.ReevaluateImportedEvent(list, identity);
}
/// <summary>The recorded (or, first time, current) decision for one delivery, applied to the SDK's fresh clone.</summary>
private NotificationMessage Decide(FirstDeliveryRecord record, uint subscriptionId, NotificationMessage message)
{
@@ -0,0 +1,761 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.Server;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ReferenceEqualityComparer = System.Collections.Generic.ReferenceEqualityComparer;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// A3 (plan §5.3): one imported condition — its node, identity (connection, condition_key), current placements and the
/// projected folders it is wired into right now. Mutated only under the node manager's <c>Lock</c>.
/// </summary>
internal sealed class ImportedCondition(AlarmConditionState alarm, string connectionId, string conditionKey)
{
public AlarmConditionState Alarm { get; } = alarm;
public string ConnectionId { get; } = connectionId;
public string ConditionKey { get; } = conditionKey;
private IReadOnlyList<ImportedConditionPlacement> _placements = [];
private long _supportedMethods = -1;
/// <summary>Written under <c>Lock</c>; read without it by A3b methods (review N8: a volatile publication of an immutable list).</summary>
public IReadOnlyList<ImportedConditionPlacement> Placements
{
get => Volatile.Read(ref _placements);
set => Volatile.Write(ref _placements, value);
}
public HashSet<FolderState> Folders { get; } = new(ReferenceEqualityComparer.Instance);
/// <summary>NIT (review r1): an immutable copy of <see cref="Folders"/> for the delivery paths that read off <c>Lock</c>.</summary>
public FolderState[] WiredFolders { get; set; } = [];
/// <summary>The last origin record applied (state known), re-applied with another Quality on staleness.</summary>
public AlarmConditionSnapshot? Last { get; set; }
/// <summary>The marker of the latest applied record. Written under <see cref="MethodGate"/> (A3b reads it without <c>Lock</c>).</summary>
public DataActivationMarker? Activation { get; set; }
/// <summary>N6: consumer-minted EventIds of this condition's recent events → the activation marker each described.
/// Mutated and read under <see cref="MethodGate"/>.</summary>
public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new();
/// <summary>A3b (§5.6 step 2): the small EventId registry's own lock — a remote method resolves its EventId and the current
/// marker under it, never under the node manager's <c>Lock</c>.</summary>
public object MethodGate { get; } = new();
/// <summary>The origin's <c>supported_methods</c> for the service principal (null until a listing carried it).</summary>
/// <remarks>Review N8: read without <c>Lock</c> by A3b methods — stored as one atomic 64-bit word (-1 = not listed yet).</remarks>
public uint? SupportedMethods
{
get => Interlocked.Read(ref _supportedMethods) is var v && v >= 0 ? (uint)v : null;
set => Interlocked.Exchange(ref _supportedMethods, value is { } m ? m : -1);
}
/// <summary>The <c>time</c> of the latest applied record (N6/F6: re-binding requires it unchanged).</summary>
public DateTimeOffset? LastTime { get; set; }
/// <summary>Bumped on every placement change (verdict caches key on it).</summary>
public long PlacementVersion { get; set; }
/// <summary>Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path.</summary>
public bool IsNative { get; init; }
}
/// <summary>
/// A3: what a consumer-minted EventId of an imported condition resolves to — the seam remote condition methods (A3b, §5.6)
/// dispatch through: the connection, the origin's opaque key, the PRIMARY placement (the address the origin resolves), and
/// the activation marker of the event the client saw.
/// </summary>
public sealed record ImportedConditionBinding(string ConnectionId, string ConditionKey, ImportedConditionPlacement Primary,
IReadOnlyList<ImportedConditionPlacement> Placements, DataActivationMarker? Activation, bool IsNative);
/// <summary>
/// A3 (plan §5.3, N7): the consumer's imported-condition registry, keyed by FULL NodeId in the
/// <c>https://zb.com/otopcua/mapped/conditions</c> namespace. Imported conditions never enter the realm-keyed maps
/// (<c>_alarmConditions</c> and friends). Mutated only under the node manager's <c>Lock</c>; <see cref="IsLive"/> and
/// <see cref="Find"/> are lock-free reads.
/// </summary>
internal sealed class ProjectedConditionRegistry
{
/// <summary>
/// Recent EventIds kept per condition (§5.6 step 3: "within its last N (default 8) events"). A3 review round 2: back to
/// the plan's 8 — A3a's 32 had no recorded need (validity is "minted under the current marker", which only the newest
/// few can satisfy; an older EventId already answers <c>BadEventIdUnknown</c> at the origin).
/// </summary>
internal const int RecentEventIds = 8;
private readonly ConcurrentDictionary<NodeId, ImportedCondition> _byNode = new();
private readonly ConcurrentDictionary<AlarmConditionState, ImportedCondition> _byInstance = new(ReferenceEqualityComparer.Instance);
/// <summary>(mapping, folder local subject) → conditions placed there (wired or waiting for the folder to materialise).</summary>
internal readonly Dictionary<(string Mapping, string Subject), HashSet<NodeId>> ByFolderKey = new();
/// <summary>Projected folder node → the folder INSTANCE promoted for it and the conditions wired into it (review r1 S1: a
/// re-created folder with the same NodeId is a different notifier and is promoted afresh).</summary>
internal readonly Dictionary<NodeId, (FolderState Folder, HashSet<NodeId> Conditions)> WiredByFolder = new();
/// <summary>Review r1 S5: (mapping, local subject) → projected folder NodeId, maintained incrementally (was a scan of every
/// projected node per apply chunk); resolved against the live projected maps at use.</summary>
internal readonly Dictionary<(string Mapping, string Subject), NodeId> FolderIds = new();
internal readonly Dictionary<NodeId, (string Mapping, string Subject)> FolderKeys = new();
/// <summary>Deviation 3: projected folders of condition-bearing mappings, event notifiers from materialisation.</summary>
internal readonly HashSet<NodeId> PromotedFolders = new();
/// <summary>Review r1 S2: a positive verdict is re-proved at least this often (credential expiry is honoured exactly).</summary>
internal static readonly TimeSpan PositiveVerdictTtl = TimeSpan.FromSeconds(5);
private readonly object _verdictGate = new();
private readonly Dictionary<(object Identity, NodeId Condition), (long Generation, long PlacementVersion, bool Allowed, DateTimeOffset ValidUntil)> _verdicts = new();
public int Count => _byNode.Count;
public IEnumerable<ImportedCondition> All => _byNode.Values;
public bool IsLive(NodeState node) => node is AlarmConditionState alarm && _byInstance.ContainsKey(alarm);
public ImportedCondition? Find(NodeState? node) =>
node is AlarmConditionState alarm && _byInstance.TryGetValue(alarm, out var c) ? c : null;
public ImportedCondition? Find(NodeId id) => _byNode.TryGetValue(id, out var c) ? c : null;
public bool IsWiredTo(ImportedCondition condition, NodeState notifier) =>
notifier is FolderState folder && Array.IndexOf(condition.WiredFolders, folder) >= 0 && _byInstance.ContainsKey(condition.Alarm);
public void Add(ImportedCondition condition)
{
_byNode[condition.Alarm.NodeId] = condition;
_byInstance[condition.Alarm] = condition;
}
public void Remove(ImportedCondition condition)
{
_byNode.TryRemove(condition.Alarm.NodeId, out _);
_byInstance.TryRemove(condition.Alarm, out _);
foreach (var key in condition.Placements.Select(FolderKey).Distinct())
if (ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0) ByFolderKey.Remove(key);
lock (_verdictGate)
foreach (var stale in _verdicts.Keys.Where(k => k.Condition == condition.Alarm.NodeId).ToList()) _verdicts.Remove(stale);
}
public static (string, string) FolderKey(ImportedConditionPlacement p) => (p.MappingId, p.FolderLocalSubject);
/// <summary>
/// The §5.4 verdict, cached per (identity, condition, authority generation, placement version). Review r1 S2: a positive
/// verdict also carries the caller's credential expiry and a short TTL — a Server-object item has no other revalidation,
/// so an expired key (or anything the generation does not capture) is never served from cache past either.
/// </summary>
public bool Verdict(object identity, ImportedCondition condition, long generation, DateTimeOffset now, DateTimeOffset? credentialExpires,
Func<bool> compute)
{
var key = (identity, condition.Alarm.NodeId);
lock (_verdictGate)
{
if (_verdicts.TryGetValue(key, out var cached) && cached.Generation == generation && cached.PlacementVersion == condition.PlacementVersion
&& now < cached.ValidUntil)
return cached.Allowed;
}
var allowed = compute();
var validUntil = !allowed ? DateTimeOffset.MaxValue
: credentialExpires is { } expires && expires < now + PositiveVerdictTtl ? expires : now + PositiveVerdictTtl;
lock (_verdictGate)
{
if (_verdicts.Count >= 65_536) _verdicts.Clear(); // bounded: a flood of identities only costs recomputation
_verdicts[key] = (generation, condition.PlacementVersion, allowed, validUntil);
}
return allowed;
}
}
public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink
{
/// <summary>Most imported updates applied per <c>Lock</c> hold (bounded Lock holds, A1 lessons).</summary>
internal const int ImportedApplyChunk = 128;
private readonly ProjectedConditionRegistry _importedConditions = new();
private readonly ConcurrentDictionary<IEventMonitoredItem, IDisposable> _importedEventDemand = new();
private long _importedEventsReported, _importedRefreshRequired;
/// <summary>A3: the consumer's condition gate + demand (null on a node with no data connections).</summary>
public IProjectedConditionAccess? ProjectedConditionAccess { get; set; }
/// <summary>Whether any imported condition is materialised (the publish rewriter's fast exit).</summary>
internal bool HasImportedConditions => _importedConditions.Count > 0;
/// <summary>Imported conditions currently materialised (test/diagnostic observation).</summary>
internal int ImportedConditionCount => _importedConditions.Count;
/// <summary>Imported condition events reported (one per genuine origin transition).</summary>
internal long ImportedEventsReported => Interlocked.Read(ref _importedEventsReported);
/// <summary>How many N6 EventId slots a condition holds (test/diagnostic observation, the L2 harness).</summary>
internal int FindImportedConditionRecentEventCount(string connectionId, string conditionKey)
{
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey)) is not { } c) return 0;
lock (c.MethodGate) return c.RecentEvents.Count;
}
/// <summary>RefreshRequired events queued for imported conditions.</summary>
internal long ImportedRefreshRequiredQueued => Interlocked.Read(ref _importedRefreshRequired);
/// <summary>
/// A3 (§5.2 N4): whether <paramref name="nodeId"/> is in the imported-condition namespace. Every NodeId classifier
/// (authorizer, read, history, call) asks this BEFORE <see cref="RealmOf"/>, which would fold it into Uns.
/// </summary>
internal bool IsImportedConditionId(NodeId nodeId) =>
NamespaceIndexes.Count > 4 && nodeId.NamespaceIndex == NamespaceIndexes[4];
/// <summary>The imported-condition NodeId for (connection, condition_key) — never the mapping or placement (N4).</summary>
internal NodeId ImportedConditionNodeId(string connectionId, string conditionKey) =>
new(ImportedConditionIds.Identifier(connectionId, conditionKey), NamespaceIndexes[4]);
/// <summary>The imported condition an event is about (its snapshot handle, or an audit's SourceNode), or null.</summary>
private ImportedCondition? ImportedOf(IFilterTarget e)
{
if (_importedConditions.Count == 0) return null;
var node = ConditionOf(e);
if (_importedConditions.Find(node) is { } c) return c;
return node is BaseEventState { SourceNode.Value: { IsNull: false } source } && IsImportedConditionId(source)
? _importedConditions.Find(source)
: null;
}
/// <summary>
/// A3 (§5.4): the mapping gate (<c>CreateMonitoredItems</c> on ANY current placement mapping) for an item's identity,
/// REGARDLESS of <c>Security:Acl:Enabled</c>. No access wired / no role-carrying identity ⇒ false.
/// </summary>
private bool ImportedVisibleTo(IEventMonitoredItem item, ImportedCondition condition) =>
ImportedVisibleTo(item.EffectiveIdentity, condition);
private bool ImportedVisibleTo(object? identity, ImportedCondition condition)
{
if (ProjectedConditionAccess is not { } access || identity is not RoleCarryingUserIdentity caller) return false;
var generation = access.AuthorityGeneration;
var placements = condition.Placements;
return _importedConditions.Verdict(caller, condition, generation, DateTimeOffset.UtcNow, caller.CredentialExpiresUtc,
() => access.CanSee(caller, placements));
}
/// <summary>The marker a queued imported event carries: re-checked at every Publish and Republish (§5.4).</summary>
private ProjectedEventMarker ImportedMarker(IEventMonitoredItem item, ImportedCondition condition)
{
var identity = item.EffectiveIdentity;
var generation = ProjectedConditionAccess?.AuthorityGeneration ?? 0;
return new ProjectedEventMarker(identity, condition.Alarm.NodeId, generation,
() => _importedConditions.IsLive(condition.Alarm) && ImportedVisibleTo(identity, condition));
}
/// <summary>Imported-condition events always take the marked path, whatever <see cref="UseProjectedEventDelivery"/> says.</summary>
private void QueueImportedToItem(IEventMonitoredItem item, IFilterTarget e, ImportedCondition condition)
{
var cache = e is ConditionEventSnapshot snapshot ? snapshot.DeliveryCache : new EventDeliveryCache();
if (cache.QueueMarked(Server, item, e, i => ImportedMarker(i, condition))) Interlocked.Increment(ref _projectedDeliveries);
}
/// <summary>
/// §5.4: the publish-time gate for an UNMARKED list (a select-clause modify rebuilt it). Null when the list is not an
/// imported-condition event; otherwise the gate re-evaluated for the publishing session.
/// </summary>
internal bool? ReevaluateImportedEvent(EventFieldList list, object? identity)
{
if (list.Handle is not InstanceStateSnapshot { Handle: ConditionState condition } || !IsImportedConditionId(condition.NodeId))
return null;
return _importedConditions.Find(condition.NodeId) is { } live && ReferenceEquals(live.Alarm, condition)
&& ImportedVisibleTo(identity, live);
}
/// <summary>
/// A3 (§5.4): the authorizer's classifier for an imported-condition id (or a child of one): Browse / Read /
/// CreateMonitoredItems are allowed when the caller passes the mapping gate on any placement; everything else
/// (Call — A3b, HistoryRead, writes) is refused here.
/// </summary>
internal bool AuthorizeImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
{
if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.CreateMonitoredItems)) return false;
if (!nodeId.TryGetValue(out string identifier)
|| !ImportedConditionIds.TryParse(identifier, out var conditionIdentifier, out _, out _, out _)) return false;
var condition = _importedConditions.Find(new NodeId(conditionIdentifier, nodeId.NamespaceIndex));
return condition is not null && ImportedVisibleTo(identity, condition);
}
/// <summary>
/// A3b seam (§5.6, N6): resolves an imported condition NodeId and a consumer-minted EventId to its connection, origin
/// key, primary placement and the activation marker the event described. False for an unknown condition or EventId.
/// </summary>
public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding)
{
binding = null;
if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false;
lock (c.MethodGate)
{
foreach (var (id, activation) in c.RecentEvents)
{
if (id != eventId) continue;
binding = new(c.ConnectionId, c.ConditionKey, c.Placements[0], c.Placements, activation, c.IsNative);
return true;
}
return false;
}
}
// ---------------------------------------------------------------------------------------------------------------------
// IProjectedConditionSink
// ---------------------------------------------------------------------------------------------------------------------
/// <inheritdoc />
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates)
{
ArgumentNullException.ThrowIfNull(updates);
EnsureAddressSpaceCreated();
var unbindable = new List<ImportedCondition>();
for (var start = 0; start < updates.Count; start += ImportedApplyChunk)
{
lock (Lock)
{
if (_disposing) return;
for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++)
{
try { if (ApplyImported(updates[i]) is { } c) unbindable.Add(c); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException)
{
_logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})",
updates[i].ConnectionId);
}
}
}
}
// N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock — only to the
// items that may see one of THOSE conditions (A3b open item, review r1).
if (unbindable.Count > 0) QueueImportedRefresh(unbindable);
}
/// <inheritdoc />
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys)
{
var keys = conditionKeys.ToArray();
var removed = new List<ImportedCondition>();
var targets = new RefreshTargets();
for (var start = 0; start < keys.Length; start += ImportedApplyChunk)
{
lock (Lock)
{
var chunk = new List<ImportedCondition>();
foreach (var key in keys.Skip(start).Take(ImportedApplyChunk))
{
if (!ImportedConditionIds.IsWellFormedConditionKey(key)) continue;
if (_importedConditions.Find(ImportedConditionNodeId(connectionId, key)) is { } c) chunk.Add(c);
}
// Deviation 6 (review r1): who may have been holding these conditions is captured BEFORE they are unwired.
CollectRefreshTargets(chunk, targets);
foreach (var c in chunk) RemoveImported(c);
removed.AddRange(chunk);
}
}
// §5.2 "removal + RefreshRequired": a client holding a removed (e.g. Active/Retain) condition is told to refresh, after
// which it no longer lists it. Outside Lock.
if (removed.Count > 0) QueueRefreshRequired(targets, removed);
}
/// <inheritdoc />
public void MarkConnectionStale(string connectionId) =>
MarkStale(_importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList());
/// <inheritdoc />
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) =>
MarkStale(conditionKeys.Where(ImportedConditionIds.IsWellFormedConditionKey)
.Select(key => _importedConditions.Find(ImportedConditionNodeId(connectionId, key))).OfType<ImportedCondition>().ToList());
private void MarkStale(List<ImportedCondition> targets)
{
for (var start = 0; start < targets.Count; start += ImportedApplyChunk)
{
lock (Lock)
{
foreach (var c in targets.Skip(start).Take(ImportedApplyChunk))
{
if (!_importedConditions.IsLive(c.Alarm)) continue;
var stale = (c.Last ?? CurrentSnapshot(c.Alarm)) with { StatusCode = StatusCodes.BadNoCommunication.Code };
if (ApplyConditionState(c.Alarm, stale, UtcNow)) ReportImported(c, UtcNow);
}
}
}
}
/// <inheritdoc />
/// <remarks>
/// A connection with no materialised condition returns early: nothing of it can be held by a client (a removal tells
/// its own holders, captured before the removal — deviation 6, review r1).
/// </remarks>
public void RequireRefresh(string connectionId)
{
var conditions = _importedConditions.All.Where(c => string.Equals(c.ConnectionId, connectionId, StringComparison.OrdinalIgnoreCase)).ToList();
if (conditions.Count > 0) QueueImportedRefresh(conditions);
}
/// <summary>Event items that may be holding imported conditions: the Server-object items, and each direct item with the
/// conditions wired at its notifier.</summary>
private sealed class RefreshTargets
{
public HashSet<IEventMonitoredItem> ServerItems { get; } = new(ReferenceEqualityComparer.Instance);
public Dictionary<IEventMonitoredItem, List<ImportedCondition>> Direct { get; } = new(ReferenceEqualityComparer.Instance);
}
/// <summary>Under Lock: the items that may see <paramref name="conditions"/> (bounded by the caller's chunk).</summary>
private void CollectRefreshTargets(IReadOnlyList<ImportedCondition> conditions, RefreshTargets targets)
{
if (conditions.Count == 0) return;
foreach (var item in _allEventsItems.Keys) targets.ServerItems.Add(item);
foreach (var c in conditions)
foreach (var folder in c.Folders)
if (MonitoredNodes.TryGetValue(folder.NodeId, out var monitored) && monitored.EventMonitoredItems is { } attached)
foreach (var item in attached.Values)
{
if (item is null) continue;
if (!targets.Direct.TryGetValue(item, out var list)) targets.Direct[item] = list = [];
list.Add(c);
}
}
/// <summary>Review r1 S5: the targets are gathered in 128-condition Lock holds; visibility is decided off Lock.</summary>
private void QueueImportedRefresh(IReadOnlyList<ImportedCondition> conditions)
{
var targets = new RefreshTargets();
for (var start = 0; start < conditions.Count; start += ImportedApplyChunk)
{
var chunk = conditions.Skip(start).Take(ImportedApplyChunk).ToList();
lock (Lock) CollectRefreshTargets(chunk, targets);
}
QueueRefreshRequired(targets, conditions);
}
/// <summary>Off Lock: one RefreshRequired per item that may see at least one of the conditions (§5.4 gate).</summary>
private void QueueRefreshRequired(RefreshTargets targets, IReadOnlyList<ImportedCondition> conditions)
{
var send = new List<IEventMonitoredItem>();
foreach (var item in targets.ServerItems)
if (conditions.Any(c => ImportedVisibleTo(item, c))) send.Add(item);
foreach (var (item, candidates) in targets.Direct)
if (!targets.ServerItems.Contains(item) && candidates.Any(c => ImportedVisibleTo(item, c))) send.Add(item);
foreach (var item in send)
{
var e = new RefreshRequiredEventState(null);
e.Initialize(SystemContext, null, EventSeverity.Low, new LocalizedText("RefreshRequired"));
e.SetChildValue(SystemContext, BrowseNames.SourceNode, ObjectIds.Server, false);
e.SetChildValue(SystemContext, BrowseNames.SourceName, "Server", false);
item.QueueEvent(e);
Interlocked.Increment(ref _importedRefreshRequired);
}
}
// ---------------------------------------------------------------------------------------------------------------------
// Materialise / apply / remove (under Lock)
// ---------------------------------------------------------------------------------------------------------------------
/// <returns>The condition when a resync left its retained EventIds un-re-bindable (the caller queues RefreshRequired).</returns>
private ImportedCondition? ApplyImported(ImportedConditionUpdate update)
{
var state = update.State;
if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update));
var id = ImportedConditionNodeId(update.ConnectionId, state.ConditionKey);
if (state.Removed)
{
if (_importedConditions.Find(id) is { } gone) RemoveImported(gone);
return null;
}
var condition = _importedConditions.Find(id);
if (condition is null)
{
var info = update.Info;
var name = string.IsNullOrWhiteSpace(info?.ConditionName) ? state.ConditionKey : info!.ConditionName;
var native = info?.SourceKind == DataConditionSourceKind.Native;
var type = info?.ConditionType is { } t && t.Contains("OffNormalAlarm", StringComparison.Ordinal) ? "OffNormalAlarm"
: info?.ConditionType is { } d && d.Contains("DiscreteAlarm", StringComparison.Ordinal) ? "DiscreteAlarm" : "AlarmCondition";
var alarm = CreateConditionNode(type, null, id, name, update.SourceName, (int)Math.Clamp(state.Severity, 1u, 1000u), native);
// A3a: no local apply of a remote method. Remote dispatch (claim / base.Call / await) is A3b (§5.6); until then
// every Part 9 method on an imported condition is refused before the SDK touches its state.
alarm.OnAcknowledge = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
alarm.OnConfirm = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
alarm.OnAddComment = (_, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
alarm.OnShelve = (_, _, _, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
alarm.OnTimedUnshelve = (_, _) => ServiceResult.Good;
alarm.OnEnableDisable = (_, _, _) => new ServiceResult(StatusCodes.BadNotSupported);
alarm.OnReportEvent = OnConditionReportEvent;
AddPredefinedNode(SystemContext, alarm);
condition = new ImportedCondition(alarm, update.ConnectionId, state.ConditionKey) { IsNative = native };
if (!state.StateKnown && alarm.Quality is not null)
{
// §5.1 T2: unknown at first sight ⇒ Uncertain, never "known inactive".
alarm.Quality.Value = StatusCodes.UncertainInitialValue;
}
_importedConditions.Add(condition);
}
UpdatePlacements(condition, update.Placements);
if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event
if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods;
// §5.1 T2: a record with state_known = false never changes the consumer's last state.
if (!state.StateKnown) return null;
var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled,
Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved,
(ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality,
state.UnshelveAtUtc?.UtcDateTime,
Enum.IsDefined(typeof(AlarmConditionClass), state.ConditionClass) ? (AlarmConditionClass)state.ConditionClass : null);
var ts = state.TimeUtc?.UtcDateTime ?? UtcNow;
if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment);
if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId;
var previous = condition.Activation;
var previousTime = condition.LastTime;
lock (condition.MethodGate) condition.Activation = state.Activation;
condition.Last = snapshot;
condition.LastTime = state.TimeUtc;
if (ApplyConditionState(condition.Alarm, snapshot, ts))
{
ReportImported(condition, ts);
return null;
}
return RebindImportedEventIds(condition, previous, previousTime, state) ? condition : null;
}
/// <summary>Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter.</summary>
private void ReportImported(ImportedCondition condition, DateTime ts)
{
ReportConditionEvent(condition.Alarm, ts);
Interlocked.Increment(ref _importedEventsReported);
if (condition.Alarm.EventId?.Value is { } eventId)
{
lock (condition.MethodGate)
{
condition.RecentEvents.AddFirst((eventId, condition.Activation));
while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast();
}
}
}
private void RemoveImported(ImportedCondition condition)
{
foreach (var folder in condition.Folders.ToList()) UnwireImportedFolder(condition, folder);
_importedConditions.Remove(condition);
TombstoneMonitoredSubtree(condition.Alarm, UtcNow);
ForgetPredefinedSubtree(condition.Alarm);
}
/// <summary>A snapshot of a node's current state (staleness before any known record arrived).</summary>
private static AlarmConditionSnapshot CurrentSnapshot(AlarmConditionState alarm) => new(
alarm.ActiveState?.Id?.Value == true, alarm.AckedState?.Id?.Value != false, alarm.ConfirmedState?.Id?.Value != false,
alarm.EnabledState?.Id?.Value != false, AlarmShelvingKind.Unshelved, (ushort)Math.Clamp((int)(alarm.Severity?.Value ?? 1), 1, 1000),
alarm.Message?.Value.Text ?? "", alarm.Quality?.Value.Code ?? StatusCodes.Good.Code);
// ---------------------------------------------------------------------------------------------------------------------
// Notifier wiring (N7): lazy, symmetric
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>(mapping, local subject) → the live materialised projected folder (anchors included), or null. Under Lock.</summary>
private FolderState? FindProjectedFolder((string Mapping, string Subject) key)
{
if (!_importedConditions.FolderIds.TryGetValue(key, out var id)) return null;
if (_projectedAnchors.TryGetValue(id, out var anchor) && anchor.Node is FolderState a) return a;
return _projectedVariables.TryGetValue(id, out var entry) && entry.Node is FolderState f ? f : null;
}
private void UpdatePlacements(ImportedCondition condition, IReadOnlyList<ImportedConditionPlacement> placements)
{
var before = condition.Placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
var after = placements.Select(ProjectedConditionRegistry.FolderKey).ToHashSet();
if (!condition.Placements.SequenceEqual(placements)) condition.PlacementVersion++;
condition.Placements = placements;
foreach (var key in before.Except(after))
if (_importedConditions.ByFolderKey.TryGetValue(key, out var set) && set.Remove(condition.Alarm.NodeId) && set.Count == 0)
_importedConditions.ByFolderKey.Remove(key);
foreach (var key in after)
{
if (!_importedConditions.ByFolderKey.TryGetValue(key, out var set)) _importedConditions.ByFolderKey[key] = set = [];
set.Add(condition.Alarm.NodeId);
}
var desired = new HashSet<FolderState>(ReferenceEqualityComparer.Instance);
foreach (var key in after) if (FindProjectedFolder(key) is { } f) desired.Add(f);
foreach (var folder in condition.Folders.Where(f => !desired.Contains(f)).ToList()) UnwireImportedFolder(condition, folder);
foreach (var folder in desired) WireImportedFolder(condition, folder);
}
private void WireImportedFolder(ImportedCondition condition, FolderState folder)
{
if (condition.Folders.Contains(folder)) return;
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && !ReferenceEquals(entry.Folder, folder))
{
// S1 backstop: a dead instance with this NodeId is still recorded — unwire it, then promote the new one.
foreach (var id in entry.Conditions.ToList())
if (_importedConditions.Find(id) is { } stale) UnwireImportedFolder(stale, entry.Folder);
_importedConditions.WiredByFolder.Remove(folder.NodeId);
}
condition.Folders.Add(folder);
condition.WiredFolders = [.. condition.Folders];
condition.Alarm.AddNotifier(SystemContext, NodeId.Null, isInverse: true, folder);
folder.AddNotifier(SystemContext, NodeId.Null, isInverse: false, condition.Alarm);
if (!_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out entry))
{
_importedConditions.WiredByFolder[folder.NodeId] = entry = (folder, []);
// Projected folders are created with EventNotifier = None (NM projected page sink); promoted only while wired.
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
AddRootNotifier(folder);
folder.ClearChangeMasks(SystemContext, includeChildren: false);
}
entry.Conditions.Add(condition.Alarm.NodeId);
condition.PlacementVersion++;
}
private void UnwireImportedFolder(ImportedCondition condition, FolderState folder)
{
if (!condition.Folders.Remove(folder)) return;
condition.WiredFolders = [.. condition.Folders];
condition.Alarm.RemoveNotifier(SystemContext, folder, bidirectional: true);
condition.PlacementVersion++;
if (_importedConditions.WiredByFolder.TryGetValue(folder.NodeId, out var entry) && ReferenceEquals(entry.Folder, folder)
&& entry.Conditions.Remove(condition.Alarm.NodeId) && entry.Conditions.Count == 0)
{
_importedConditions.WiredByFolder.Remove(folder.NodeId);
RemoveRootNotifier(folder);
if (!_importedConditions.PromotedFolders.Contains(folder.NodeId))
folder.EventNotifier = (byte)(folder.EventNotifier & ~EventNotifiers.SubscribeToEvents);
folder.ClearChangeMasks(SystemContext, includeChildren: false);
}
}
/// <summary>A projected folder (or anchor) materialised: index it and wire every imported condition placed there (N7). Under Lock.</summary>
private void OnProjectedFolderMaterialised(FolderState folder, string mappingId, string localSubject)
{
if (_importedConditions.FolderKeys.Remove(folder.NodeId, out var previous)) _importedConditions.FolderIds.Remove(previous);
_importedConditions.FolderIds[(mappingId, localSubject)] = folder.NodeId;
_importedConditions.FolderKeys[folder.NodeId] = (mappingId, localSubject);
if (ProjectedConditionAccess is { } access && access.IsConditionBearingMapping(mappingId))
{
// Deviation 3 (review r1): a folder-only client can subscribe (and so open condition demand) before anything is wired.
_importedConditions.PromotedFolders.Add(folder.NodeId);
folder.EventNotifier = (byte)(folder.EventNotifier | EventNotifiers.SubscribeToEvents);
}
if (_importedConditions.Count == 0 || !_importedConditions.ByFolderKey.TryGetValue((mappingId, localSubject), out var set)) return;
foreach (var id in set.ToList())
if (_importedConditions.Find(id) is { } c) WireImportedFolder(c, folder);
}
/// <summary>A projected folder is being removed: unwire it symmetrically first (N7) and drop it from the index. Under Lock.</summary>
private void OnProjectedFolderRemoving(NodeId folderId)
{
if (_importedConditions.FolderKeys.Remove(folderId, out var key)) _importedConditions.FolderIds.Remove(key);
_importedConditions.PromotedFolders.Remove(folderId);
if (!_importedConditions.WiredByFolder.TryGetValue(folderId, out var entry)) return;
foreach (var id in entry.Conditions.ToList())
if (_importedConditions.Find(id) is { } c) UnwireImportedFolder(c, entry.Folder);
}
/// <summary>Review r1 S1: a full rebuild discards every projected folder — unwire all of them (and clear the index) before
/// the maps are cleared, so a re-materialised folder is promoted and wired afresh. Under Lock.</summary>
private void UnwireAllImportedFolders()
{
foreach (var folderId in _importedConditions.WiredByFolder.Keys.ToList()) OnProjectedFolderRemoving(folderId);
_importedConditions.FolderIds.Clear();
_importedConditions.FolderKeys.Clear();
_importedConditions.PromotedFolders.Clear();
}
/// <summary>
/// N7: a projected folder holding an admitted event item is pinned — capacity eviction and page removal skip it (a
/// mapping removal still removes it, unwiring first). Under Lock.
/// </summary>
private bool IsPinnedEventFolder(NodeId nodeId) =>
(_importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId))
&& MonitoredNodes.TryGetValue(nodeId, out var monitored) && monitored.EventMonitoredItems is { Count: > 0 };
/// <summary>
/// A projected folder (or anchor) event items are admitted on through the verified path (§5.4): one wired as a notifier of
/// an imported condition, or — deviation 3, review r1 — any materialised projected folder, so a folder-only client can
/// open condition demand before any condition is wired there.
/// </summary>
private bool IsProjectedEventNotifier(NodeId nodeId)
{
if (ProjectedConditionAccess is null) return false;
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId) || _importedConditions.FolderKeys.ContainsKey(nodeId);
}
/// <summary>
/// §5.4 admission (and revalidation, review r1 B3) of an event item on a projected notifier: the caller sees at least one
/// condition wired there, or passes the mapping gate on the folder's own (mapping, local subject) placement key.
/// </summary>
private bool ImportedNotifierAdmits(RoleCarryingUserIdentity? identity, NodeId notifierId)
{
List<ImportedCondition> wired = [];
(string Mapping, string Subject)? key = null;
lock (Lock)
{
if (_importedConditions.WiredByFolder.TryGetValue(notifierId, out var entry))
wired = entry.Conditions.Select(_importedConditions.Find).OfType<ImportedCondition>().ToList();
if (_importedConditions.FolderKeys.TryGetValue(notifierId, out var folderKey)) key = folderKey;
}
if (wired.Any(c => ImportedVisibleTo(identity, c))) return true;
return key is { } k && identity is not null && ProjectedConditionAccess is { } access && access.CanSubscribeFolder(identity, k.Mapping, k.Subject);
}
/// <summary>
/// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise
/// the imported verdict.
/// </summary>
internal bool? ClassifyImportedCondition(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) =>
IsImportedConditionId(nodeId) ? AuthorizeImportedCondition(identity, operation, nodeId) : null;
/// <summary>Test observation: whether a projected folder is currently wired as a notifier of some imported condition.</summary>
internal bool IsImportedNotifierWired(NodeId folderId)
{
lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(folderId);
}
/// <summary>Test observation: the imported condition node for (connection, key), or null.</summary>
internal AlarmConditionState? FindImportedCondition(string connectionId, string conditionKey) =>
_importedConditions.Find(ImportedConditionNodeId(connectionId, conditionKey))?.Alarm;
// ---------------------------------------------------------------------------------------------------------------------
// Demand + ConditionRefresh
// ---------------------------------------------------------------------------------------------------------------------
/// <summary>An admitted event item (Server object or projected notifier) opens condition demand; its removal releases it.</summary>
private void TrackImportedDemand(IEventMonitoredItem item, bool unsubscribe)
{
if (unsubscribe)
{
if (_importedEventDemand.TryRemove(item, out var lease)) lease.Dispose();
return;
}
if (ProjectedConditionAccess is not { } access || _importedEventDemand.ContainsKey(item)) return;
IDisposable? acquired;
try { acquired = access.AcquireEventDemand(item.EffectiveIdentity as RoleCarryingUserIdentity); }
catch (Exception ex) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition demand failed"); return; }
if (acquired is not null && !_importedEventDemand.TryAdd(item, acquired)) acquired.Dispose();
}
/// <summary>
/// ConditionRefresh for imported conditions: every retained one the item may see, through the marked path. Server-object
/// items see all; a direct item only those wired to its notifier. Review r1 (deviation 8): chunked at
/// <see cref="ImportedApplyChunk"/> conditions per <c>Lock</c> hold; each condition's snapshot and its queueing happen in the
/// same hold (so its ordering against its live events holds), and one <see cref="EventDeliveryCache"/> per condition
/// snapshot is shared by every item it is queued to (one projection, not one per item).
/// </summary>
private void ReplayImportedConditions(List<IEventMonitoredItem> serverItems, List<IEventMonitoredItem> directItems)
{
if (_importedConditions.Count == 0) return;
var all = _importedConditions.All.ToList();
for (var start = 0; start < all.Count; start += ImportedApplyChunk)
{
lock (Lock)
{
var direct = directItems.Where(item => MonitoredItems.ContainsKey(item.Id))
.Select(item => (Item: item, Notifier: (item.ManagerHandle as NodeHandle)?.Node as FolderState))
.Where(x => x.Notifier is not null).ToList();
for (var i = start; i < Math.Min(all.Count, start + ImportedApplyChunk); i++)
{
var c = all[i];
if (!_importedConditions.IsLive(c.Alarm) || c.Alarm.Retain?.Value != true) continue;
InstanceStateSnapshot? snapshot = null;
EventDeliveryCache? cache = null;
void Queue(IEventMonitoredItem item)
{
if (!ImportedVisibleTo(item, c) || ServiceResult.IsBad(ValidateEventRolePermissions(item, c.Alarm))) return;
if (snapshot is null)
{
snapshot = new InstanceStateSnapshot();
snapshot.Initialize(SystemContext, c.Alarm);
cache = new EventDeliveryCache();
}
cache!.QueueMarked(Server, item, snapshot, x => ImportedMarker(x, c));
}
foreach (var item in serverItems) Queue(item);
foreach (var (item, notifier) in direct)
if (c.Folders.Contains(notifier!)) Queue(item);
}
}
}
}
}
@@ -101,6 +101,24 @@ internal sealed class EventDeliveryCache
return false;
}
/// <summary>
/// A3 (§5.4): queues an imported-condition event ALWAYS through the projected path with a
/// <see cref="ProjectedEventFieldList"/> marker, whatever the node manager's <c>UseProjectedEventDelivery</c> switch
/// says. An item of a shape the projected path cannot serve gets nothing (fail closed, counted) — never the SDK's
/// unmarked <c>QueueEvent(IFilterTarget)</c>.
/// </summary>
/// <returns>True when queued (or decided not to queue exactly as the SDK would).</returns>
public bool QueueMarked(IServerInternal server, IEventMonitoredItem item, IFilterTarget e, Func<IEventMonitoredItem, ProjectedEventMarker> marker)
{
if (item.GetType() == typeof(SdkMonitoredItem)
&& e is InstanceStateSnapshot { Handle: ConditionState condition }
&& condition.SupportsFilteredRetain?.Value != true
&& ProjectedEventDelivery.TryQueue(server, (SdkMonitoredItem)item, e, this, marker))
return true;
Interlocked.Increment(ref ProjectedEventFieldList.s_unservable);
return false;
}
/// <summary>Marks the item as queued for this report; false when it already was (the SDK's duplicate check).</summary>
internal bool TryMarkQueued(IEventMonitoredItem item)
{
@@ -216,7 +234,8 @@ internal static class ProjectedEventDelivery
/// The SDK's <c>QueueEvent(instance, bypassFilter: false)</c> for one condition snapshot, with the projection taken
/// from <paramref name="cache"/>. Returns false (nothing done) when the item is not in a shape this reproduces.
/// </summary>
internal static bool TryQueue(IServerInternal server, SdkMonitoredItem item, IFilterTarget e, EventDeliveryCache cache)
internal static bool TryQueue(IServerInternal server, SdkMonitoredItem item, IFilterTarget e, EventDeliveryCache cache,
Func<IEventMonitoredItem, ProjectedEventMarker>? marker = null)
{
if (!Available || (item.MonitoredItemType & 2) == 0) return false;
@@ -237,12 +256,20 @@ internal static class ProjectedEventDelivery
if (!projection.Passes || handler.SetQueueOverflowIfFull()) return true;
Interlocked.Increment(ref s_projectedQueued);
item.QueueEvent(new EventFieldList
{
ClientHandle = item.ClientHandle,
Handle = e,
EventFields = projection.Fields, // shared, read-only (see Projection)
});
// A3 (§5.4): an imported condition's list carries its publish-time re-check (ProjectedNotificationRewriter).
item.QueueEvent(marker is null
? new EventFieldList
{
ClientHandle = item.ClientHandle,
Handle = e,
EventFields = projection.Fields, // shared, read-only (see Projection)
}
: new ProjectedEventFieldList(marker(item))
{
ClientHandle = item.ClientHandle,
Handle = e,
EventFields = projection.Fields,
});
return true;
}
}
@@ -412,3 +439,62 @@ internal static class ProjectedEventDelivery
return property.GetMethod.CreateDelegate<Func<SdkMonitoredItem, T?>>();
}
}
/// <summary>
/// A3 (§5.4): the captured authority of one queued imported-condition event — the caller, the condition, the authority
/// generation it was admitted under and a re-check, like <c>ProjectedNotificationMarker</c> for data.
/// </summary>
internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId, long Generation, Func<bool> Recheck)
{
/// <summary>Re-evaluates the gate; any failure denies.</summary>
public bool Permits()
{
try { return Recheck(); }
catch { return false; }
}
}
/// <summary>
/// A3 (§5.4): an <see cref="EventFieldList"/> carrying its <see cref="ProjectedEventMarker"/>. The rewriter does NOT see
/// the queued instance: SDK 2.0.1 <c>SentMessageQueue</c> stores the constructed message and returns a
/// <c>CoreUtils.Clone</c> of it on Publish and on Republish. The gate still works because
/// <see cref="EventFieldList.Clone"/> is <c>MemberwiseClone</c>, so every copy keeps this subclass, its
/// <see cref="Marker"/> and its handle, and <c>ProjectedNotificationRewriter</c> drops the copy when the re-check fails.
/// That clone dependency is pinned by
/// <c>ImportedConditionClassifierTests.Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker</c>:
/// an SDK that cloned through the activator would turn it red.
/// </summary>
/// <remarks>
/// A3 review round 2 (root cause of the OI refresh failures): SDK 2.0.1 POOLS <see cref="EventFieldList"/> process-wide
/// (<c>EventFieldListActivator : PooledEncodeableType</c>). <c>SentMessageQueue</c> calls <c>Reuse()</c> on every list of an
/// acknowledged/evicted message, and the base <c>ReuseCore</c> returns the instance — whatever its runtime type — to the
/// shared stock pool, from which ANY server's <c>MonitoredItem.GetEventFields</c> rents its next list. A recycled
/// instance of this subclass therefore became some unrelated session's RefreshStart/RefreshEnd or local condition event,
/// still carrying THIS marker: the rewriter judged it by another condition's (possibly revoked) gate and dropped it.
/// Like <c>ProjectedSdkNotification</c> on the data path, this subclass stays out of the stock pool.
/// </remarks>
internal sealed class ProjectedEventFieldList(ProjectedEventMarker marker) : EventFieldList
{
internal static long s_unservable, s_droppedOnPublish, s_droppedUnmarked, s_keptUnmarked;
/// <summary>The captured authority; null once the SDK has released the list (it is never published again).</summary>
public ProjectedEventMarker? Marker { get; private set; } = marker;
/// <inheritdoc />
protected override void ReuseCore()
{
// ACK, eviction and message disposal reach this through IPooledEncodeable.Reuse: reset, drop the marker (and with it
// the closure over the condition and identity), and let the GC have it — never the shared EventFieldList pool.
Marker = null;
ResetForReuse();
}
/// <summary>Imported events an item could not receive through the marked path (fail closed).</summary>
internal static long Unservable => Interlocked.Read(ref s_unservable);
/// <summary>Marked events dropped at Publish/Republish because the re-check failed.</summary>
internal static long DroppedOnPublish => Interlocked.Read(ref s_droppedOnPublish);
/// <summary>Unmarked imported events (rebuilt by a select-clause modify) dropped because the gate denied.</summary>
internal static long DroppedUnmarked => Interlocked.Read(ref s_droppedUnmarked);
/// <summary>Unmarked imported events kept after the gate re-evaluated them for the publishing session.</summary>
internal static long KeptUnmarked => Interlocked.Read(ref s_keptUnmarked);
}
@@ -141,6 +141,12 @@ public sealed class DataPlaneAuthorizer
/// <summary>Live catalog classification owned by the node manager, consulted before either local path resolver.</summary>
public Func<AddressSpaceRealm, string, MappedNodeResolution>? MappedSubjectResolver { get; set; }
/// <summary>
/// A3: the node manager's imported-condition classifier — null for an id outside the imported-condition namespace,
/// otherwise the verdict (Browse/Read/CreateMonitoredItems via the condition's mapping gate; anything else refused).
/// </summary>
public Func<RoleCarryingUserIdentity?, OpcUaOperation, NodeId, bool?>? ImportedConditionClassifier { get; set; }
/// <summary>Optional actual-namespace filter for projected subject classification.</summary>
public Func<NodeId, bool>? MappedNamespacePredicate { get; set; }
@@ -162,6 +168,20 @@ public sealed class DataPlaneAuthorizer
public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto)
{
// A3 (§5.2 N4): the imported-condition namespace has NO realm; it is classified before anything reads `realm` (which a
// caller computed with the node manager's RealmOf, folding it into Uns). Every entry point (Authorize, AuthorizeIfRequired,
// IsAllowedCached, TryAuthorizeMapped) reaches this first, ACLs on or off.
if (ImportedConditionClassifier is { } imported)
{
bool? verdict;
try { verdict = imported(identity, operation, nodeId); }
catch (Exception ex)
{
_log.LogWarning(ex, "Imported condition classification failed");
verdict = false;
}
if (verdict is { } decided) { veto = decided ? null : DeniedResult; return true; }
}
var resolver = MappedSubjectResolver;
if (MappedNamespacePredicate is { } predicate && !predicate(nodeId)) { veto = null; return false; }
if (resolver is null) { veto = null; return false; }
@@ -916,12 +916,48 @@ internal sealed class ProjectedLossMarker(uint clientHandle, ProjectedMonitoredI
/// <summary>Rechecks captured projected notification authority for every delivery and retransmission.</summary>
internal static class ProjectedNotificationRewriter
{
public static NotificationMessage Project(NotificationMessage message, bool republish)
public static NotificationMessage Project(NotificationMessage message, bool republish) => Project(message, republish, null);
/// <param name="message">The message about to be sent (Publish) or re-sent (Republish).</param>
/// <param name="republish">Whether this is a Republish.</param>
/// <param name="importedGate">
/// A3 (§5.4): for an UNMARKED event list whose <c>Handle</c> is an imported-condition snapshot (a select-clause
/// <c>ModifyMonitoredItems</c> rebuilt it through <c>GetEventFields</c>), re-evaluates the gate for the publishing
/// session: true keeps it, false drops it; null = not an imported condition (kept, v1 behaviour).
/// </param>
public static NotificationMessage Project(NotificationMessage message, bool republish, Func<EventFieldList, bool?>? importedGate)
{
var changed = false;
var payloads = new List<ExtensionObject>(message.NotificationData.Count);
foreach (var payload in message.NotificationData)
{
if (payload.TryGetValue<EventNotificationList>(out var events) && events is not null)
{
var kept = new List<EventFieldList>(events.Events.Count);
foreach (var list in events.Events)
{
if (list is ProjectedEventFieldList marked)
{
if (marked.Marker?.Permits() == true) kept.Add(list); // a released list (no marker) fails closed
else Interlocked.Increment(ref ProjectedEventFieldList.s_droppedOnPublish);
continue;
}
bool? verdict;
try { verdict = importedGate?.Invoke(list); }
catch { verdict = false; }
if (verdict == false) { Interlocked.Increment(ref ProjectedEventFieldList.s_droppedUnmarked); continue; }
if (verdict == true) Interlocked.Increment(ref ProjectedEventFieldList.s_keptUnmarked);
kept.Add(list);
}
if (kept.Count == events.Events.Count) payloads.Add(payload);
else
{
changed = true;
// Events have no Bad-value form: a denied event is dropped; an emptied list leaves the payload out.
if (kept.Count > 0) payloads.Add(new ExtensionObject(new EventNotificationList { Events = kept }));
}
continue;
}
if (!payload.TryGetValue<DataChangeNotification>(out var change) || change is null)
{ payloads.Add(payload); continue; }
var items = new List<MonitoredItemNotification>(change.MonitoredItems.Count);
@@ -524,8 +524,22 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
}
/// <summary>A non-owning handle with the deployed operation and resource policy.</summary>
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDisposable
public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistoryService, IHistoryBatchLimit, IDataConditionMethodService, IDataPrimarySubscriptionSource, IDisposable
{
/// <summary>
/// A3b: a remote condition method through the deployed connection — needs the row's AlarmAcknowledge / AlarmConfirm
/// bit (refused unsent otherwise) and an inner connection that serves methods. The outcome is passed through untouched
/// (no post-check: once sent, an answer is the only truth about whether the origin applied it).
/// </summary>
public Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
Check(DataConditionMethodSets.OperationFor(request.Method));
return _inner is IDataConditionMethodService methods
? methods.CallConditionMethodAsync(request, cancellationToken)
: Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x803D0000u, "The connection does not serve condition methods."));
}
/// <summary>
/// H2 remote history through the deployed connection: needs the connection row's HistoryRead bit (masked to the
/// understood set) and an inner connection that implements history; otherwise every item is unsupported.
@@ -665,9 +679,17 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDataHistor
catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or UnauthorizedAccessException)
{ return request.Items.Select(x => new WriteItemResult(x.CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown after scope change."))).ToArray(); }
}
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: false, cancellationToken);
/// <inheritdoc />
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: true, cancellationToken);
private async Task<IDataSubscription> SubscribeCoreAsync(bool primaryOnly, CancellationToken cancellationToken)
{
Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
Check(DataOperations.Subscribe);
var stream = primaryOnly && _inner is IDataPrimarySubscriptionSource primary
? await primary.SubscribePrimaryAsync(cancellationToken).ConfigureAwait(false)
: await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false);
try { Check(DataOperations.Subscribe); return stream is IDataSubscriptionProvenance provenance
? new ProvenancedScopedSubscription(this, stream, provenance.Serving)
: new ScopedSubscription(this, stream); }
@@ -16,9 +16,17 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class GrpcDataConnection : IDataConditionMethodService
{
internal const uint BadCommunicationError = 0x80050000u;
private TimeSpan _conditionMethodTimeout = TimeSpan.FromSeconds(5);
/// <summary>
/// The validator's ceiling for a mapping's <c>ConditionMethodTimeoutMilliseconds</c> (3,600,000 ms) — the client's default
/// backstop. A3b review S2: the per-MAPPING ceiling arrives in <see cref="DataConditionMethodRequest.RemainingBudget"/>
/// (the consumer node manager computes min(request deadline, mapping timeout) − elapsed); a connection-wide 5 s default
/// here silently capped a 30 s mapping at 5 s.
/// </summary>
public static readonly TimeSpan MaxConditionMethodTimeout = TimeSpan.FromMilliseconds(3_600_000);
/// <summary>The per-call method ceiling (the mapping's <c>ConditionMethodTimeoutMilliseconds</c>; A3 binds it per mapping).</summary>
private TimeSpan _conditionMethodTimeout = MaxConditionMethodTimeout;
/// <summary>An optional connection-wide backstop over the per-call budget (default <see cref="MaxConditionMethodTimeout"/>).</summary>
public TimeSpan ConditionMethodTimeout
{
get => _conditionMethodTimeout;
@@ -29,7 +37,9 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
public async Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
request.Validate();
// A3b review S3: an invalid request is refused unsent, never thrown into a caller that would read it as "unknown".
try { request.Validate(); }
catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); }
var start = Clock.GetTimestamp();
var deadline = request.RemainingBudget < ConditionMethodTimeout ? request.RemainingBudget : ConditionMethodTimeout;
if (deadline <= TimeSpan.Zero) return new(DataWriteState.RejectedBeforeDispatch, BadTimeout, "Budget expired before dispatch.");
@@ -82,6 +92,12 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
ex.StatusCode is StatusCode.PermissionDenied or StatusCode.Unauthenticated ? 0x801F0000u : BadNotSupportedMethod,
"Refused by the origin transport: " + ex.StatusCode);
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded && !cancellationToken.IsCancellationRequested)
{
// A3b review S2: the deadline is a KNOWN timeout — say BadTimeout here instead of letting the caller infer it
// from its own clock. Still OutcomeUnknown: the origin may have applied it.
return new(DataWriteState.OutcomeUnknown, BadTimeout, "OutcomeUnknown: no answer before the method deadline.");
}
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException
or ArgumentException or IOException)
{
@@ -99,4 +115,5 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
}
private const uint BadNotSupportedMethod = 0x803D0000u;
private const uint BadInvalidArgument = 0x80AB0000u;
}
@@ -23,7 +23,7 @@ public interface IDataConnectionSecurityProvider
public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint);
/// <summary>Caller-bound remote facade. All channels and requests are bounded by configured local limits.</summary>
public sealed partial class GrpcDataConnection : IDataConnection
public sealed partial class GrpcDataConnection : IDataConnection, IDataPrimarySubscriptionSource
{
private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer)
{
@@ -531,7 +531,14 @@ public sealed partial class GrpcDataConnection : IDataConnection
actual == expected || actual.NodeId == expected.NodeId && actual.Incarnation == expected.Incarnation &&
results.Count > 0 && results.All(x => x.Outcome.State == DataWriteState.RejectedBeforeDispatch);
public async Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: false, cancellationToken);
/// <inheritdoc />
/// <remarks>A3 review r1 (deviation 9): condition streams skip a ReadyReplica Secondary. An endpoint refused only for its
/// role is not a discovery failure (no probe backoff for the value path).</remarks>
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeCoreAsync(primaryOnly: true, cancellationToken);
private async Task<IDataSubscription> SubscribeCoreAsync(bool primaryOnly, CancellationToken cancellationToken)
{
EnterWork();
var reserved = false;
@@ -546,11 +553,18 @@ public sealed partial class GrpcDataConnection : IDataConnection
}
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1000, _maxMessageBytes);
var start = Clock.GetTimestamp(); Exception? failure = null;
var roleOnly = primaryOnly;
foreach (var endpoint in _endpoints)
{
try
{
var selected = await SelectAsync(endpoint, start, budget, false, cancellationToken).ConfigureAwait(false);
if (primaryOnly && !string.Equals(selected.Capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
{
failure = new InvalidOperationException("Endpoint is not the Primary.");
continue;
}
roleOnly = false;
if ((selected.Capabilities.Operations & DataOperations.Subscribe) == 0 ||
Volatile.Read(ref _activeStreams) > selected.Capabilities.Limits.MaxStreams)
throw new InvalidOperationException("Subscriptions unavailable or peer stream capacity exhausted.");
@@ -593,10 +607,10 @@ public sealed partial class GrpcDataConnection : IDataConnection
}
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; RecordFailure(ex); }
{ failure = ex; RecordFailure(ex); roleOnly = false; }
}
ProbeFailed();
throw new InvalidOperationException("No ready subscription endpoint.", failure);
if (!roleOnly) ProbeFailed();
throw new InvalidOperationException(roleOnly ? "No Primary subscription endpoint." : "No ready subscription endpoint.", failure);
}
finally
{
@@ -0,0 +1,98 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// A3b (plan §5.6): the consumer's remote condition method port. The gate is per LOCAL caller (the condition stream runs
/// under the connection's service principal, so nothing it carries authorizes a local session); the call goes through the
/// deployed connection lease to the origin's <c>CallConditionMethod</c> (A2b), addressed by the placement and the serving
/// incarnation of the stream the condition's records arrived on.
/// </summary>
public sealed partial class ProjectedConditionAccess : IProjectedConditionMethods
{
private const uint BadNoCommunication = 0x80310000u;
private const uint BadNotSupported = 0x803D0000u;
private const uint BadUserAccessDenied = 0x801F0000u;
private const uint BadInvalidArgument = 0x80AB0000u;
/// <inheritdoc />
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
DataConditionMethods method)
{
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements is null || placements.Count == 0
|| !DataConditionMethodSets.IsSingle(method)) return null;
var required = DataConditionMethodSets.OperationFor(method);
var operation = method == DataConditionMethods.Confirm ? OpcUaOperation.AlarmConfirm : OpcUaOperation.AlarmAcknowledge;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
var current = _mappings.Current;
foreach (var placement in placements)
{
var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, placement.MappingId, StringComparison.OrdinalIgnoreCase));
if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || mapping.Mapping.Realm != placement.Realm
|| (mapping.Mapping.AllowedOperations & required) != required) continue;
if (!TryFolderScope(mapping, placement.FolderLocalSubject, out var scope)) continue;
try
{
// AuthorizeLocal re-checks the caller's key (usable, version, expiry: #563) on every call.
if (_policy.AuthorizeLocal(identity, operation, scope))
return new ImportedConditionMethodRoute(placement,
TimeSpan.FromMilliseconds(Math.Max(1, mapping.Mapping.ConditionMethodTimeoutMilliseconds)));
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { }
}
return null;
}
/// <inheritdoc />
public async Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(call);
ServingIdentity? serving;
lock (_gate) serving = _runners.TryGetValue(call.ConnectionId, out var runner) ? runner.Serving : null;
// No open condition stream ⇒ no serving incarnation to address: the connection is down for this purpose. Nothing sent.
if (serving is null)
return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "No condition stream is open on the connection.");
var request = new DataConditionMethodRequest(call.OperationId, call.Placement.Placement, call.Method, call.ExpectedActivation,
call.Comment, serving.Incarnation, call.RemainingBudget, call.OnBehalfOf);
// A3b review S3: validated before the lease — an invalid request is refused unsent, never an "unknown" outcome.
try { request.Validate(); }
catch (ArgumentException ex) { return new(DataWriteState.RejectedBeforeDispatch, BadInvalidArgument, "Invalid request: " + ex.Message); }
IGrpcDataAdapterConnectionLease? lease;
try { lease = await _connections.AcquireAsync(call.ConnectionId, cancellationToken).ConfigureAwait(false); }
catch (Exception ex) when (ex is InvalidOperationException or OperationCanceledException or TimeoutException)
{ return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is unavailable."); }
if (lease is null) return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is unavailable.");
await using (lease.ConfigureAwait(false))
{
if (lease.Connection is not IDataConditionMethodService methods)
return new(DataWriteState.RejectedBeforeDispatch, BadNotSupported, "The connection does not serve condition methods.");
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, lease.CancellationToken);
try
{
var result = await methods.CallConditionMethodAsync(request, linked.Token).ConfigureAwait(false);
if (result.State == DataWriteState.OutcomeUnknown)
_log.LogWarning("Imported condition method {Method} on {Connection}/{Key} (op {Operation}): outcome unknown — {Diagnostic}",
call.Method, call.ConnectionId, call.ConditionKey, call.OperationId, result.Diagnostic);
return result;
}
catch (UnauthorizedAccessException)
{
// The deployed connection row does not enable the method's operation: refused by the lease, nothing sent.
return new(DataWriteState.RejectedBeforeDispatch, BadUserAccessDenied, "The connection does not allow this condition method.");
}
catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
{
// The lease's own scope check (connection no longer ready / disposed) refuses before anything is sent.
return new(DataWriteState.RejectedBeforeDispatch, BadNoCommunication, "The connection is no longer ready.");
}
}
}
}
@@ -0,0 +1,578 @@
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class ProjectedConditionAccess
{
// -----------------------------------------------------------------------------------------------------------------
// The node-wide host-cap ledger (review r1 B4)
// -----------------------------------------------------------------------------------------------------------------
/// <summary>
/// §5.5 host caps, node-wide: one ledger across every connection. A connection is charged
/// <c>max(materialised keys, Σ mapping claims)</c> — conditions are charged once per key, a mapping's claim is its
/// admitted snapshot <c>total</c> while it snapshots and its record count afterwards (so post-snapshot growth is charged),
/// and a re-snapshot of keys the connection already holds is not double-charged. Admission is order-independent: a
/// begin is decided against everything already charged or claimed, whichever connection or mapping arrived first.
/// </summary>
private sealed class ConditionLedger(ProjectedConditionOptions options)
{
private sealed class Entry
{
public int Materialised;
public readonly Dictionary<string, int> Claims = new(StringComparer.OrdinalIgnoreCase);
public long Charge => Math.Max(Materialised, Claims.Values.Sum(x => (long)x));
}
private readonly object _gate = new();
private readonly Dictionary<string, Entry> _connections = new(StringComparer.OrdinalIgnoreCase);
public long Total { get { lock (_gate) return TotalLocked(); } }
private long TotalLocked() => _connections.Values.Sum(x => x.Charge);
private bool Over(long conditions) =>
conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes
|| conditions * ProjectedConditionOptions.BytesPerCondition > options.MaxImportedConditionBytes;
public bool HighWater(long conditions) =>
conditions * ProjectedConditionOptions.NodesPerCondition > options.MaxImportedConditionNodes * 8L / 10;
/// <summary>Sets a mapping's claim when the node total stays within both caps; otherwise leaves it unchanged.</summary>
public bool TryClaim(string connection, string mapping, int count, out long total)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
var had = entry.Claims.TryGetValue(mapping, out var previous);
entry.Claims[mapping] = count;
total = TotalLocked();
if (!Over(total) || count <= previous) return true;
if (had) entry.Claims[mapping] = previous; else entry.Claims.Remove(mapping);
return false;
}
}
public void Release(string connection, string mapping)
{
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Remove(mapping);
}
public void ResetClaims(string connection)
{
lock (_gate) if (_connections.TryGetValue(connection, out var entry)) entry.Claims.Clear();
}
public void SetMaterialised(string connection, int count)
{
lock (_gate)
{
if (!_connections.TryGetValue(connection, out var entry)) _connections[connection] = entry = new Entry();
entry.Materialised = count;
if (count == 0 && entry.Claims.Count == 0) _connections.Remove(connection);
}
}
}
// -----------------------------------------------------------------------------------------------------------------
// One connection: one stream, one root item per condition-bearing mapping
// -----------------------------------------------------------------------------------------------------------------
/// <summary>One mapping's records: versions per key, the listed infos, and (for a snapshot buffer) the begin's total.</summary>
private sealed class ConditionSet(int total)
{
public int Total { get; } = total;
public Dictionary<string, DataConditionState> Records { get; } = new(StringComparer.Ordinal);
public Dictionary<string, DataConditionInfo> Infos { get; } = new(StringComparer.Ordinal);
public Dictionary<string, long> Versions { get; } = new(StringComparer.Ordinal);
/// <summary>The per-key version rule: a removal bypasses the gate and forgets the key (and its info).</summary>
public void Apply(DataConditionState record, HashSet<string>? changed)
{
var key = record.ConditionKey;
if (record.Removed)
{
Records.Remove(key); Versions.Remove(key); Infos.Remove(key);
changed?.Add(key);
return;
}
if (record.Info is { } info) Infos[key] = info;
if (Versions.TryGetValue(key, out var last) && record.Version <= last) return;
Versions[key] = record.Version;
Records[key] = record;
changed?.Add(key);
}
}
private sealed class MappingState(ProjectedMappingPlacement placement)
{
public ProjectedMappingPlacement Placement { get; } = placement;
public string MappingId => Placement.Mapping.RemoteNamespaceMappingId;
// The origin view of the remote root, built exactly as RemoteNamespaceResolver builds it (subject = the mapping's
// RemoteRootEntityId): a UNS root's address identifier is an opaque id, and the origin refuses a root item whose subject
// is not its own (live a3b-cond-2: map-uns item Denied).
public DataView Root { get; } = new(placement.Anchor.Address, placement.Mapping.Realm, null, 0,
string.IsNullOrWhiteSpace(placement.Mapping.RemoteRootEntityId) ? placement.Anchor.Address.Identifier : placement.Mapping.RemoteRootEntityId);
public string? RootSubject { get; set; }
/// <summary>The origin's canonical view of the remote root (from metadata): the root item must carry the origin's own
/// subject — a view built from the address alone (subject = identifier) is refused for an opaque-id UNS root.</summary>
public DataView? RootView { get; set; }
public ulong? Handle { get; set; }
public DataItemHandle? ItemHandle { get; set; }
public ProjectedConditionMappingStatus Status { get; set; } = ProjectedConditionMappingStatus.Pending;
/// <summary>The origin refused the item (or its metadata failed): nothing more arrives on this stream.</summary>
public bool Refused { get; set; }
/// <summary>The mapping's committed complete set in this stream (null until its first snapshot completes).</summary>
public ConditionSet? Live { get; set; }
/// <summary>Review r1 B1: a (re-)snapshot in progress, swapped in only at <c>snapshot_complete</c>.</summary>
public ConditionSet? Buffer { get; set; }
public bool Contributes => Live is not null && Status != ProjectedConditionMappingStatus.ConditionCapacity;
/// <summary>Whether the mapping's key set is known: listed (complete) or known-empty (over capacity).</summary>
public bool Known => Contributes || Status == ProjectedConditionMappingStatus.ConditionCapacity;
public int Claim => Math.Max(Buffer?.Total ?? 0, Live?.Records.Count ?? 0);
}
private sealed class ConnectionRunner
{
private readonly ProjectedConditionAccess _owner;
private readonly ProjectedMappingPlacement[] _mappings;
private readonly CancellationTokenSource _stop = new();
private readonly object _statusGate = new();
private readonly object _staleGate = new();
/// <summary>Verification r2 N1: dropped right after the hand-over, so runners never chain (R3 → R2 → R1 …).</summary>
private ConnectionRunner? _predecessor;
private Task _loop = Task.CompletedTask;
private Task _stopped = Task.CompletedTask;
private MappingState[] _states = [];
/// <summary>Keys currently materialised at the sink. Owned by the loop; handed over only after the predecessor stopped.</summary>
private HashSet<string> _materialised = new(StringComparer.Ordinal);
private ITimer? _stale;
private long _staleGeneration;
private int _barriers;
private int _consecutiveRetries;
public ConnectionRunner(ProjectedConditionAccess owner, string connectionId, ProjectedMappingPlacement[] mappings, string signature,
ConnectionRunner? predecessor)
{
_owner = owner; ConnectionId = connectionId; _mappings = mappings; Signature = signature; _predecessor = predecessor;
}
public string ConnectionId { get; }
public string Signature { get; }
public int Barriers => Volatile.Read(ref _barriers);
private ServingIdentity? _serving;
/// <summary>A3b: the serving identity of the CURRENT condition stream (null while no stream is open).</summary>
public ServingIdentity? Serving => Volatile.Read(ref _serving);
/// <summary>Completes once the loop ended and (for a removing stop) its conditions were removed.</summary>
public Task Stopped => _stopped;
public IReadOnlyDictionary<string, ProjectedConditionMappingStatus> Statuses
{
get { lock (_statusGate) return _states.ToDictionary(x => x.MappingId, x => x.Status, StringComparer.OrdinalIgnoreCase); }
}
public void Start() => _loop = Task.Run(async () =>
{
await HandOverAsync().ConfigureAwait(false);
await RunAsync(_stop.Token).ConfigureAwait(false);
});
/// <summary>
/// S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would otherwise
/// race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). The
/// materialised set moves over only after the predecessor stopped. Verification r2 N1: the predecessor reference is
/// dropped once the hand-over is done (its own method, so no hoisted local outlives it either) — otherwise every
/// linger expiry or mapping change would add a link to a chain that keeps each old runner reachable.
/// </summary>
private async Task HandOverAsync()
{
var previous = _predecessor;
if (previous is null) return;
try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); }
_materialised = previous._materialised;
previous._materialised = new HashSet<string>(StringComparer.Ordinal);
_predecessor = null;
}
public void Stop(bool removeConditions)
{
_stop.Cancel();
Volatile.Write(ref _serving, null);
lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; }
_stopped = _loop.ContinueWith(_ =>
{
// Verification r2 N1: a stopped runner keeps no stream's record sets (it may sit in _stopping until the next demand).
lock (_statusGate) _states = [];
if (!removeConditions) return;
var keys = _materialised.ToArray();
if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys);
_materialised.Clear();
_owner._ledger.ResetClaims(ConnectionId);
_owner._ledger.SetMaterialised(ConnectionId, 0);
}, TaskScheduler.Default);
}
private async Task RunAsync(CancellationToken ct)
{
var epoch = 0L;
while (!ct.IsCancellationRequested)
{
epoch++;
try { await RunStreamAsync(epoch, ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception ex)
{
_owner._log.LogInformation(ex, "Imported conditions: stream for connection {Connection} ended; re-snapshotting", ConnectionId);
}
finally { Volatile.Write(ref _serving, null); }
// §5.5 lifetime rule: a stream end is "re-snapshot", never "conditions removed". Arm staleness instead.
ArmStale();
OtOpcUaTelemetry.DataConnConditionResyncs.Add(1);
try { await Task.Delay(_owner._options.ReconnectDelay, _owner._clock, ct).ConfigureAwait(false); }
catch (OperationCanceledException) { return; }
}
}
private void ArmStale()
{
lock (_staleGate)
{
if (_stale is not null || _materialised.Count == 0 || _stop.IsCancellationRequested) return;
var generation = _staleGeneration;
var timeout = TimeSpan.FromMilliseconds(Math.Max(1, _mappings.Min(x => x.Mapping.ConditionStaleTimeoutMilliseconds)));
_stale = _owner._clock.CreateTimer(_ =>
{
// NIT (review r1): a callback already in flight cannot land after a fresh barrier — the barrier bumps the
// generation under the same gate this mark runs under, so it either waits for the mark or wins the check.
lock (_staleGate)
if (generation == _staleGeneration && !_stop.IsCancellationRequested) _owner._sink()?.MarkConnectionStale(ConnectionId);
}, null, timeout, Timeout.InfiniteTimeSpan);
}
}
private void DisarmStale()
{
lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; }
}
private async Task RunStreamAsync(long epoch, CancellationToken ct)
{
var states = _mappings.Select(x => new MappingState(x)).ToArray();
lock (_statusGate) _states = states;
_owner._ledger.ResetClaims(ConnectionId);
await using var lease = await _owner._connections.AcquireAsync(ConnectionId, ct).ConfigureAwait(false)
?? throw new InvalidOperationException("Connection unavailable.");
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease.CancellationToken);
var token = linked.Token;
var connection = lease.Connection;
// The remote root's origin subject: placement addresses are made relative to it (SourceName, folder subject).
// S6: a root whose metadata fails is Unavailable (its item is not opened — a root item without the origin's own
// view is refused, and placements made relative to a missing root subject would be wrong).
try
{
var budget = new DataBudget(TimeSpan.FromSeconds(10), Math.Max(1, states.Length), 1024 * 1024);
var metadata = await connection.GetMetadataAsync(new MetadataRequest(states.Select(x => x.Root).ToArray(), budget), token)
.ConfigureAwait(false);
for (var i = 0; i < states.Length; i++)
{
if (i < metadata.Count && metadata[i] is { Status: DataItemStatus.Good, Value: { } root })
{
states[i].RootSubject = root.View.Subject;
states[i].RootView = root.View;
continue;
}
MarkRefused(states[i]);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} root metadata unavailable ({Status}) — Unavailable, retried on a new stream",
states[i].MappingId, i < metadata.Count ? metadata[i].Status : DataItemStatus.Unavailable);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
foreach (var state in states) MarkRefused(state);
_owner._log.LogWarning(ex, "Imported conditions: connection {Connection} root metadata failed — every mapping Unavailable", ConnectionId);
}
var open = states.Where(x => !x.Refused).ToArray();
if (open.Length == 0) throw new InvalidOperationException("No condition-bearing mapping root resolved.");
// Deviation 9: condition items are served by the origin's Primary only (a Secondary advertises but refuses, A2 N7).
await using var subscription = connection is IDataPrimarySubscriptionSource primary
? await primary.SubscribePrimaryAsync(token).ConfigureAwait(false)
: await connection.SubscribeAsync(token).ConfigureAwait(false);
var serving = (subscription as IDataSubscriptionProvenance)?.Serving;
if (serving is not null && !string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"Condition stream served by a {serving.Role} ({serving.NodeId}); conditions are pinned to the Primary.");
Volatile.Write(ref _serving, serving);
_owner._log.LogInformation("Imported conditions: stream {Epoch} for connection {Connection} opened ({Mappings} mapping(s), serving {Serving})",
epoch, ConnectionId, open.Length, Serving?.NodeId ?? "(no provenance)");
var subscriptionId = "conditions-" + Guid.NewGuid().ToString("N");
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var items = open.Select(x => new DataSubscriptionItem(x.MappingId, x.RootView ?? x.Root, settings, new DataConditionScope(IncludeInfo: true))).ToArray();
await subscription.SendAsync(new OpenSubscription(subscriptionId, epoch, "open", TimeSpan.FromSeconds(30), items, false,
TimeSpan.FromMinutes(60), new DataBudget(TimeSpan.FromSeconds(30), 1000, 4 * 1024 * 1024)), token).ConfigureAwait(false);
var snapshotTimeout = TimeSpan.FromMilliseconds(Math.Max(1, states.Max(x => x.Placement.Mapping.ConditionSnapshotTimeoutMilliseconds)));
var barrierPassed = false;
var timeout = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var barrierTimer = _owner._clock.CreateTimer(_ => timeout.TrySetResult(), null, snapshotTimeout, Timeout.InfiniteTimeSpan);
// B2: a mapping still Unavailable a bounded wait after the barrier ends the stream (a fresh stream retries it).
var retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
ITimer? retryTimer = null;
var context = new StreamContext(subscription, subscriptionId, epoch, token);
try
{
await using var frames = subscription.ReadAllAsync(token).GetAsyncEnumerator(token);
Task<bool>? next = null;
while (true)
{
if (!barrierPassed && timeout.Task.IsCompleted)
{
// ConditionSnapshotTimeoutMilliseconds: the incomplete mappings are Unavailable and the rest proceed; a
// late completion still swaps in and re-runs the merge (B2).
lock (_statusGate)
foreach (var s in states.Where(s => s.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting))
s.Status = ProjectedConditionMappingStatus.Unavailable;
barrierPassed = TryPassBarrier(states, timedOut: true);
}
if (barrierPassed)
{
var unavailable = states.Any(x => x.Status == ProjectedConditionMappingStatus.Unavailable);
if (retry.Task.IsCompleted && unavailable)
{
_consecutiveRetries++;
_owner._log.LogWarning("Imported conditions: connection {Connection} mapping(s) {Mappings} still Unavailable — ending the stream to retry",
ConnectionId, string.Join(", ", states.Where(x => x.Status == ProjectedConditionMappingStatus.Unavailable).Select(x => x.MappingId)));
return;
}
if (!unavailable)
{
retryTimer?.Dispose(); retryTimer = null; _consecutiveRetries = 0;
if (retry.Task.IsCompleted) retry = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
else if (retryTimer is null)
{
var wait = snapshotTimeout * Math.Min(1 << Math.Min(_consecutiveRetries, 3), 8);
var signal = retry;
retryTimer = _owner._clock.CreateTimer(_ => signal.TrySetResult(), null, wait, Timeout.InfiniteTimeSpan);
}
}
next ??= frames.MoveNextAsync().AsTask();
if (!next.IsCompleted)
{
var wake = barrierPassed ? retry.Task : timeout.Task;
if (await Task.WhenAny(next, wake).ConfigureAwait(false) != next) continue;
}
if (!await next.ConfigureAwait(false)) return;
next = null;
var outcome = await ProcessAsync(frames.Current, states, context).ConfigureAwait(false);
if (!barrierPassed) { barrierPassed = TryPassBarrier(states, timedOut: false); continue; }
if (outcome.Changed.Count > 0 || outcome.Reconcile) Reconcile(states, outcome.Changed, outcome.Reconcile);
if (outcome.Refresh) _owner._sink()?.RequireRefresh(ConnectionId);
}
}
finally { retryTimer?.Dispose(); }
}
private sealed record StreamContext(IDataSubscription Subscription, string SubscriptionId, long Epoch, CancellationToken Token);
private sealed record FrameOutcome(HashSet<string> Changed, bool Reconcile, bool Refresh);
private void MarkRefused(MappingState state)
{
lock (_statusGate)
{
state.Refused = true;
if (state.Status != ProjectedConditionMappingStatus.ConditionCapacity) state.Status = ProjectedConditionMappingStatus.Unavailable;
}
}
private bool TryPassBarrier(MappingState[] states, bool timedOut)
{
lock (_statusGate)
if (states.Any(x => x.Status is ProjectedConditionMappingStatus.Pending or ProjectedConditionMappingStatus.Snapshotting)) return false;
Interlocked.Increment(ref _barriers);
DisarmStale();
var incomplete = states.Any(x => !x.Known);
_owner._log.LogInformation("Imported conditions: connection {Connection} snapshot barrier passed ({Statuses}; {Records} record(s){TimedOut})",
ConnectionId, string.Join(", ", states.Select(x => x.MappingId + "=" + x.Status)), states.Where(x => x.Contributes).Sum(x => x.Live!.Records.Count),
timedOut ? "; snapshot timed out" : "");
Reconcile(states, states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal), full: true);
// S7: an incomplete (re)snapshot — a timeout OR a refused item — tells clients to refresh.
if (incomplete) _owner._sink()?.RequireRefresh(ConnectionId);
return true;
}
private async Task<FrameOutcome> ProcessAsync(DataSubscriptionFrame frame, MappingState[] states, StreamContext context)
{
var changed = new HashSet<string>(StringComparer.Ordinal);
var reconcile = false;
var refresh = false;
switch (frame)
{
case DataSubscriptionAck ack:
foreach (var itemAck in ack.Items)
{
var state = states.FirstOrDefault(x => x.MappingId == itemAck.ClientItemId);
if (state is null) continue;
if (itemAck.Status == DataItemStatus.Good && itemAck.Handle is { } handle)
{
lock (_statusGate) { state.Handle = handle.Handle; state.ItemHandle = handle; }
continue;
}
MarkRefused(state);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} item refused by the origin ({Status}: {Diagnostic})",
state.MappingId, itemAck.Status, itemAck.Diagnostic);
}
break;
case DataSubscriptionConditions conditions:
var mapping = states.FirstOrDefault(x => x.Handle == conditions.Handle.Handle);
if (mapping is null || mapping.Refused || mapping.Status == ProjectedConditionMappingStatus.ConditionCapacity) break;
var limit = mapping.Placement.Mapping.MaxConditions;
if (conditions.IsSnapshot && conditions.Total is { } total)
{
// A snapshot begin: decided before anything of it is materialised; buffered until snapshot_complete (B1),
// so the committed set (and what is materialised) is untouched while it streams.
if (total > limit || !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, Math.Max(total, mapping.Live?.Records.Count ?? 0), out var after))
{
await ResetToCapacityAsync(mapping, total, total > limit ? "over its MaxConditions" : "would cross the host condition caps",
changed, context).ConfigureAwait(false);
reconcile = refresh = true;
break;
}
if (_owner._ledger.HighWater(after))
_owner._log.LogWarning("Imported conditions: host condition budget above 80% ({Count} conditions)", after);
mapping.Buffer = new ConditionSet(total);
lock (_statusGate)
if (mapping.Live is null && mapping.Status == ProjectedConditionMappingStatus.Pending) mapping.Status = ProjectedConditionMappingStatus.Snapshotting;
}
foreach (var record in conditions.Items)
{
if (!ImportedConditionIds.IsWellFormedConditionKey(record.ConditionKey)) continue;
if (mapping.Live is { } live && !conditions.IsSnapshot)
{
// A delta: applied to the committed set (published) and to any buffer, so the swap is current.
live.Apply(record, changed);
mapping.Buffer?.Apply(record, null);
}
else mapping.Buffer?.Apply(record, null);
}
// B4: records past the begin's total or the mapping limit, or committed growth past the node-wide caps.
string? over = null;
if (mapping.Buffer is { } buffer && buffer.Records.Count > Math.Min(buffer.Total, limit)) over = "listed more records than its snapshot total";
else if (mapping.Live is { } grown && grown.Records.Count > limit) over = "grew past its MaxConditions";
else if (mapping.Live is not null && !_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, mapping.Claim, out _)) over = "grew past the host condition caps";
if (over is not null)
{
await ResetToCapacityAsync(mapping, mapping.Claim, over, changed, context).ConfigureAwait(false);
reconcile = refresh = true;
break;
}
if (conditions.SnapshotComplete && mapping.Buffer is { } done)
{
// The swap: old ∪ new keys are re-merged — a key only the old set listed is removed (if nothing else
// lists it and every mapping is known), every other key keeps its node.
if (mapping.Live is { } old) changed.UnionWith(old.Records.Keys);
changed.UnionWith(done.Records.Keys);
mapping.Live = done;
mapping.Buffer = null;
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.Complete;
_owner._ledger.TryClaim(ConnectionId, mapping.MappingId, done.Records.Count, out _); // ≤ the admitted total
reconcile = true;
}
break;
}
return new FrameOutcome(changed, reconcile, refresh);
}
/// <summary>§5.5 Unavailable(ConditionCapacity): the item is removed and the mapping contributes nothing (all-or-nothing).</summary>
private async Task ResetToCapacityAsync(MappingState mapping, int observed, string reason, HashSet<string> changed, StreamContext context)
{
lock (_statusGate) mapping.Status = ProjectedConditionMappingStatus.ConditionCapacity;
if (mapping.Live is { } live) changed.UnionWith(live.Records.Keys);
mapping.Live = null;
mapping.Buffer = null;
_owner._ledger.Release(ConnectionId, mapping.MappingId);
OtOpcUaTelemetry.DataConnConditionCapacityRejections.Add(1);
_owner._log.LogWarning("Imported conditions: mapping {Mapping} ({Count} conditions) {Reason} (MaxConditions {Max}) — Unavailable(ConditionCapacity)",
mapping.MappingId, observed, reason, mapping.Placement.Mapping.MaxConditions);
// §5.5: the over-limit item is REMOVED (it costs an item slot and the origin's re-listing).
if (mapping.ItemHandle is { } handle)
await context.Subscription.SendAsync(new RemoveSubscriptionItems(context.SubscriptionId, context.Epoch, "remove-" + mapping.MappingId,
TimeSpan.FromSeconds(30), [handle]), context.Token).ConfigureAwait(false);
}
/// <summary>
/// Publishes <paramref name="keys"/> across the connection's committed sets. <paramref name="full"/> also re-diffs
/// everything materialised against the union (the barrier, a swap, a capacity reset, a late completion).
/// A key no contributing mapping lists is removed only when every mapping's set is known; while any is unknown
/// (Unavailable, not yet complete) it is kept with <c>BadNoCommunication</c> (unknown ≠ gone, §5.1 T2, B2).
/// </summary>
private void Reconcile(MappingState[] states, HashSet<string> keys, bool full)
{
if (_owner._sink() is not { } sink) return;
if (full)
{
var listed = states.Where(x => x.Contributes).SelectMany(x => x.Live!.Records.Keys).ToHashSet(StringComparer.Ordinal);
foreach (var key in _materialised) if (!listed.Contains(key)) keys.Add(key);
}
var unknown = states.Any(x => !x.Known);
var updates = new List<ImportedConditionUpdate>();
var removals = new List<string>();
var stale = new List<string>();
foreach (var key in keys)
{
var update = Merge(states, key);
if (update is not null) { updates.Add(update); _materialised.Add(key); continue; }
if (!_materialised.Contains(key)) continue;
if (unknown) stale.Add(key);
else { _materialised.Remove(key); removals.Add(key); }
}
if (removals.Count > 0) sink.RemoveConditions(ConnectionId, removals);
if (stale.Count > 0) sink.MarkConditionsStale(ConnectionId, stale);
if (updates.Count > 0) sink.ApplyConditions(updates);
_owner._ledger.SetMaterialised(ConnectionId, _materialised.Count);
if (updates.Count + removals.Count + stale.Count > 0)
_owner._log.LogDebug("Imported conditions: connection {Connection} applied {Updates} update(s), {Removals} removal(s), {Stale} kept stale",
ConnectionId, updates.Count, removals.Count, stale.Count);
}
/// <summary>One key across the connection's complete mappings: placements (primary first), latest record, SourceName.</summary>
private ImportedConditionUpdate? Merge(MappingState[] states, string key)
{
DataConditionState? latest = null;
DataConditionInfo? info = null;
var placements = new List<(int Order, ImportedConditionPlacement Placement)>();
for (var i = 0; i < states.Length; i++)
{
var state = states[i];
if (!state.Contributes || !state.Live!.Records.TryGetValue(key, out var record)) continue;
if (latest is null || record.Version > latest.Version) latest = record;
if (!state.Live.Infos.TryGetValue(key, out var placementInfo)) continue;
info ??= placementInfo;
foreach (var view in placementInfo.Placements.Where(p => p.Realm == state.Placement.Mapping.Realm)
.OrderBy(p => p.Address.Identifier, StringComparer.Ordinal))
placements.Add((i, ToPlacement(state, view)));
}
if (latest is null || placements.Count == 0) return null;
var ordered = placements.OrderBy(x => x.Order).Select(x => x.Placement).ToArray();
var primary = ordered[0];
var anchor = states[placements.Min(x => x.Order)].Placement.Anchor.Subject;
return new ImportedConditionUpdate(ConnectionId, latest, info, ordered, anchor + "/" + primary.RelativePath);
}
private static ImportedConditionPlacement ToPlacement(MappingState state, DataView view)
{
var relative = view.Subject;
if (state.RootSubject is { Length: > 0 } root && relative.StartsWith(root + "/", StringComparison.Ordinal))
relative = relative[(root.Length + 1)..];
var cut = relative.LastIndexOf('/');
var anchor = state.Placement.Anchor.Subject;
var folder = cut < 0 ? anchor : anchor + "/" + relative[..cut];
return new ImportedConditionPlacement(state.MappingId, state.Placement.Mapping.Realm, view, folder, relative);
}
}
}
@@ -0,0 +1,326 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>A3: the deployed mapping placements the condition runtime reads (an adapter over <see cref="ProjectedMappingDeploymentRuntime"/>).</summary>
public interface IProjectedConditionMappings
{
/// <summary>The currently published placements (copies; read on change only).</summary>
IReadOnlyList<ProjectedMappingPlacement> Current { get; }
/// <summary>Raised after the published placement set changes.</summary>
event Action? Changed;
}
/// <summary>The production adapter over <see cref="ProjectedMappingDeploymentRuntime"/>.</summary>
public sealed class DeployedConditionMappings : IProjectedConditionMappings
{
private readonly ProjectedMappingDeploymentRuntime _runtime;
private volatile IReadOnlyList<ProjectedMappingPlacement> _current;
public DeployedConditionMappings(ProjectedMappingDeploymentRuntime runtime)
{
_runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
_current = runtime.Active;
runtime.Changed += placements => { _current = placements; Changed?.Invoke(); };
}
public IReadOnlyList<ProjectedMappingPlacement> Current => _current;
public event Action? Changed;
}
/// <summary>A3 host limits (§5.5 "Budget").</summary>
/// <param name="Linger">How long a connection's condition items stay open after the last event item goes (default 30 s).</param>
/// <param name="MaxImportedConditionNodes">Per consumer node (default 122,500 = 2,500 × 49).</param>
/// <param name="MaxImportedConditionBytes">Per consumer node (default = L2-measured <see cref="BytesPerCondition"/> × 2,500 ≈ 381 MiB).</param>
/// <param name="ReconnectDelay">Pause before re-opening an ended condition stream.</param>
public sealed record ProjectedConditionOptions(TimeSpan Linger, int MaxImportedConditionNodes, long MaxImportedConditionBytes,
TimeSpan ReconnectDelay)
{
/// <summary>Counted, not estimated (plan §5.5 table): the worst case per condition.</summary>
public const int NodesPerCondition = 49;
/// <summary>
/// Retained managed bytes per imported condition, measured by the A3 L2 harness (1,000 conditions in one mapping on a
/// running SDK 2.0.1 server: node + children + ids + registry/indexes + EventId registry + verdict cache; X0's
/// node-only harness measured 160,997). A3b review S5: the WORST case — two placements, every EventId slot, three
/// event items, the runner's Live + Buffer records. A3 review round 2: measured with the retained heap
/// (<c>GCMemoryInfo</c>, not <c>GC.GetTotalMemory</c>, which counted ~125 MiB of committed-but-free regions) and the
/// settled working set, 8 EventId slots (§5.6): max of three runs = 158,629 B (working set; heap 111,715 B), rounded up.
/// </summary>
public const long BytesPerCondition = 160_000;
/// <summary>§9.3 L2: the host byte cap = measured per-condition bytes × 2,500 (the host condition cap).</summary>
public const long DefaultMaxImportedConditionBytes = BytesPerCondition * 2_500;
public static ProjectedConditionOptions Default { get; } =
new(TimeSpan.FromSeconds(30), 122_500, DefaultMaxImportedConditionBytes, TimeSpan.FromSeconds(1));
}
/// <summary>Why a condition-bearing mapping is not contributing conditions.</summary>
public enum ProjectedConditionMappingStatus { Pending, Snapshotting, Complete, Unavailable, ConditionCapacity }
/// <summary>
/// A3 (plan §5.4, §5.5): the consumer's condition runtime.
/// <list type="bullet">
/// <item><b>Gate</b> (<see cref="CanSee"/>): the mapping gate for <c>CreateMonitoredItems</c> on ANY current placement
/// mapping — the mapping's Subscribe + AlarmSubscribe bits and a local Subscribe grant on the placement folder's local
/// scope — regardless of <c>Security:Acl:Enabled</c>.</item>
/// <item><b>Demand</b>: the first admitted event item opens, per condition-bearing connection, ONE stream with one
/// root-scoped condition item per enabled condition-bearing mapping (under the connection's service principal);
/// they close together after the last item goes plus <see cref="ProjectedConditionOptions.Linger"/>.</item>
/// <item><b>Barrier + budget</b>: <c>total &gt; MaxConditions</c> ⇒ that mapping is
/// <see cref="ProjectedConditionMappingStatus.ConditionCapacity"/> and its item removed before anything is
/// materialised; host caps reject the mappings that would cross them, in deployed order; conditions are materialised
/// only after every mapping completed its snapshot (or timed out ⇒ Unavailable).</item>
/// <item><b>Versions</b>: per key and epoch; a <c>removed</c> record and a snapshot begin bypass the gate; a removal is
/// applied unconditionally and forgets the key's version.</item>
/// <item><b>Lifetime</b>: a stream end is "re-snapshot", never "conditions removed"; only a COMPLETE re-snapshot that
/// no longer lists a key removes it. Past <c>ConditionStaleTimeoutMilliseconds</c> without a stream the conditions go
/// <c>BadNoCommunication</c> (one event each) — never "known inactive" (§5.1 T2).</item>
/// </list>
/// </summary>
public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess, IDisposable
{
private readonly IProjectedConditionMappings _mappings;
private readonly IGrpcDataAdapterConnectionSource _connections;
private readonly DataOperationPolicy _policy;
private readonly Func<IProjectedConditionSink?> _sink;
private readonly TimeProvider _clock;
private readonly ProjectedConditionOptions _options;
private readonly ILogger _log;
private readonly object _gate = new();
private readonly Dictionary<string, ConnectionRunner> _runners = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Review r1 S3/S4: a stopped runner's completion (its loop AND its removal) per connection; the next runner of
/// that connection awaits it before opening a stream or taking the materialised set, so the two never overlap.</summary>
private readonly Dictionary<string, ConnectionRunner> _stopping = new(StringComparer.OrdinalIgnoreCase);
private readonly ConditionLedger _ledger;
private int _demand;
private long _mappingVersion = 1;
private ITimer? _linger;
private bool _disposed;
public ProjectedConditionAccess(IProjectedConditionMappings mappings, IGrpcDataAdapterConnectionSource connections,
DataOperationPolicy policy, Func<IProjectedConditionSink?>? sink, TimeProvider clock, ProjectedConditionOptions? options = null,
ILogger? logger = null)
{
_mappings = mappings ?? throw new ArgumentNullException(nameof(mappings));
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_policy = policy ?? throw new ArgumentNullException(nameof(policy));
_sink = sink ?? (() => Sink);
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_options = options ?? ProjectedConditionOptions.Default;
_log = logger ?? NullLogger.Instance;
_ledger = new ConditionLedger(_options);
_mappings.Changed += OnMappingsChanged;
}
/// <summary>The node manager the host binds once the server is up (used when no sink delegate was supplied).</summary>
public IProjectedConditionSink? Sink { get; set; }
/// <summary>Whether a mapping is condition-bearing: enabled, Subscribe + AlarmSubscribe granted.</summary>
public static bool IsConditionBearing(RemoteNamespaceMapping mapping) =>
mapping.Enabled && (mapping.AllowedOperations & (DataOperations.Subscribe | DataOperations.AlarmSubscribe))
== (DataOperations.Subscribe | DataOperations.AlarmSubscribe);
/// <inheritdoc />
/// <remarks>Review r1 S2: also folds each current mapping's <c>Authority.IsActive</c>, which flips without a deploy.</remarks>
public long AuthorityGeneration
{
get
{
var active = 17L;
foreach (var mapping in _mappings.Current) active = unchecked(active * 31 + (mapping.Authority.IsActive ? 1 : 2));
return unchecked((Interlocked.Read(ref _mappingVersion) << 32) ^ _policy.AuthorityEpoch ^ (active << 1));
}
}
/// <inheritdoc />
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements)
{
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || placements.Count == 0) return false;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
var current = _mappings.Current;
foreach (var placement in placements)
if (Gate(identity, current, placement.MappingId, placement.Realm, placement.FolderLocalSubject)) return true;
return false;
}
/// <inheritdoc />
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject)
{
if (caller is null || string.IsNullOrWhiteSpace(caller.Principal)) return false;
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
return Gate(identity, _mappings.Current, mappingId, null, folderLocalSubject);
}
/// <inheritdoc />
public bool IsConditionBearingMapping(string mappingId) =>
_mappings.Current.Any(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase)
&& x.Authority.IsActive && IsConditionBearing(x.Mapping));
/// <summary>The mapping gate for one (mapping, folder) placement; <paramref name="realm"/> null = the mapping's own.</summary>
private bool Gate(DataCallerIdentity identity, IReadOnlyList<ProjectedMappingPlacement> current, string mappingId, DataRealm? realm,
string folderLocalSubject)
{
var mapping = current.FirstOrDefault(x => string.Equals(x.Mapping.RemoteNamespaceMappingId, mappingId, StringComparison.OrdinalIgnoreCase));
if (mapping is null || !mapping.Authority.IsActive || !IsConditionBearing(mapping.Mapping) || (realm is { } r && mapping.Mapping.Realm != r))
return false;
if (!TryFolderScope(mapping, folderLocalSubject, out var scope)) return false;
try { return _policy.AuthorizeLocal(identity, OpcUaOperation.CreateMonitoredItems, scope); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; }
}
/// <summary>The local scope of a placement's folder: the mapping's local scope plus the folder's path below the anchor.</summary>
internal static bool TryFolderScope(ProjectedMappingPlacement mapping, string folderLocalSubject, out NodeScope scope)
{
scope = mapping.Scope;
var anchor = string.Join('/', mapping.Scope.Segments);
if (string.Equals(folderLocalSubject, anchor, StringComparison.Ordinal)) return true;
if (!folderLocalSubject.StartsWith(anchor + "/", StringComparison.Ordinal)) return false;
var below = folderLocalSubject[(anchor.Length + 1)..].Split('/');
if (below.Any(string.IsNullOrEmpty)) return false;
scope = mapping.Scope with { Segments = Array.AsReadOnly(mapping.Scope.Segments.Concat(below).ToArray()) };
return true;
}
/// <inheritdoc />
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
{
lock (_gate)
{
if (_disposed) return null;
_demand++;
_linger?.Dispose(); _linger = null;
ReconcileRunners();
}
return new DemandLease(this);
}
private void ReleaseDemand()
{
lock (_gate)
{
if (_disposed || --_demand > 0) return;
_linger?.Dispose();
_linger = _clock.CreateTimer(_ => OnLingerExpired(), null, _options.Linger, Timeout.InfiniteTimeSpan);
}
}
private void OnLingerExpired()
{
List<ConnectionRunner> stopped;
lock (_gate)
{
if (_disposed || _demand > 0) return;
stopped = _runners.Values.ToList();
_runners.Clear();
foreach (var runner in stopped) { runner.Stop(removeConditions: true); _stopping[runner.ConnectionId] = runner; }
}
}
private void OnMappingsChanged()
{
Interlocked.Increment(ref _mappingVersion);
lock (_gate)
{
if (_disposed) return;
ReconcileRunners();
}
}
/// <summary>Starts a runner per condition-bearing connection while demand exists; restarts one whose mapping set changed. Under _gate.</summary>
private void ReconcileRunners()
{
if (_demand <= 0) return;
var byConnection = _mappings.Current.Where(x => x.Authority.IsActive && IsConditionBearing(x.Mapping))
.GroupBy(x => x.Mapping.DataConnectionId, StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => OrderMappings(x).ToArray(), StringComparer.OrdinalIgnoreCase);
foreach (var id in _runners.Keys.Where(id => !byConnection.ContainsKey(id)).ToList())
{
_runners.Remove(id, out var gone);
gone!.Stop(removeConditions: true);
_stopping[id] = gone;
}
foreach (var (id, mappings) in byConnection)
{
var signature = Signature(mappings);
if (_runners.TryGetValue(id, out var running))
{
if (running.Signature == signature) continue;
// A changed mapping set: a new stream with a complete snapshot. ConditionIds never change (N4); placements,
// notifiers and SourceName follow the new set at its barrier.
running.Stop(removeConditions: false);
}
// S3/S4: the predecessor (still running or still removing) hands over only after it has fully stopped.
var predecessor = running ?? (_stopping.Remove(id, out var stopping) ? stopping : null);
var runner = new ConnectionRunner(this, id, mappings, signature, predecessor);
_runners[id] = runner;
runner.Start();
}
}
/// <summary>§5.2: Raw mappings before UNS, then mapping id ordinal (deployed configuration only).</summary>
internal static IEnumerable<ProjectedMappingPlacement> OrderMappings(IEnumerable<ProjectedMappingPlacement> mappings) =>
mappings.OrderBy(x => x.Mapping.Realm == DataRealm.Raw ? 0 : 1)
.ThenBy(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.Ordinal);
private static string Signature(IEnumerable<ProjectedMappingPlacement> mappings) =>
string.Join('|', mappings.Select(x => $"{x.Mapping.RemoteNamespaceMappingId}:{x.Mapping.Revision}:{x.Mapping.MaxConditions}:{x.Anchor.Subject}"));
/// <summary>Test/diagnostic observation: a connection's mapping statuses (null when no runner).</summary>
public IReadOnlyDictionary<string, ProjectedConditionMappingStatus>? MappingStatuses(string connectionId)
{
lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Statuses : null;
}
/// <summary>Test/diagnostic observation: imported conditions charged against the node-wide host caps (review r1 B4).</summary>
public long ChargedConditions => _ledger.Total;
/// <summary>Test observation: whether a connection has an open runner.</summary>
public bool IsRunning(string connectionId)
{
lock (_gate) return _runners.ContainsKey(connectionId);
}
/// <summary>Test observation (verification r2 N1): a weak reference to the connection's current (or still stopping) runner.</summary>
public WeakReference? RunnerReference(string connectionId)
{
lock (_gate)
return _runners.TryGetValue(connectionId, out var runner) || _stopping.TryGetValue(connectionId, out runner) ? new WeakReference(runner) : null;
}
/// <summary>Test observation: snapshot barriers a connection completed.</summary>
public int BarriersCompleted(string connectionId)
{
lock (_gate) return _runners.TryGetValue(connectionId, out var runner) ? runner.Barriers : 0;
}
public void Dispose()
{
List<ConnectionRunner> runners;
lock (_gate)
{
if (_disposed) return;
_disposed = true;
_linger?.Dispose();
runners = _runners.Values.ToList();
_runners.Clear();
}
_mappings.Changed -= OnMappingsChanged;
foreach (var runner in runners) runner.Stop(removeConditions: false);
}
private sealed class DemandLease(ProjectedConditionAccess owner) : IDisposable
{
private int _disposed;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.ReleaseDemand(); }
}
}
@@ -115,6 +115,32 @@ public sealed class GrpcDataV1CompatibilityTests
else cases.ShouldNotContain(W.SubscriptionFrame.FrameOneofCase.ConditionStates);
}
/// <summary>
/// A3: the fake origin now emits what the consumer registry consumes (begin with <c>total</c>, an info-carrying record,
/// <c>snapshot_complete</c>, a <c>removed</c> delta). A header-less caller — even one whose item carries a condition
/// scope — still gets the golden v1 bytes; the negotiated stream carries all three condition frames.
/// </summary>
[Fact]
[Trait("Phase", "A3")]
public async Task A3_consumer_condition_shapes_reach_only_a_negotiated_stream_and_v1_bytes_are_unchanged()
{
var open = W.SubscriptionCommand.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"]));
open.Open.Items[0].ConditionScope = new W.ConditionScope { IncludeInfo = true };
(await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: open.ToByteArray()))
.ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"]);
(await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata(), request: Convert.FromHexString(GrpcDataV1Goldens.Requests["Subscribe"])))
.ShouldBe(GrpcDataV1Goldens.Responses["Subscribe"]);
var negotiated = (await V1CompatibilityHarness.DriveAsync("Subscribe", new Metadata { { "x-otopcua-data-features", "conditions" } },
request: open.ToByteArray())).Split('|').Select(f => W.SubscriptionFrame.Parser.ParseFrom(Convert.FromHexString(f)))
.Where(f => f.FrameCase == W.SubscriptionFrame.FrameOneofCase.ConditionStates)
.Select(ZB.MOM.WW.OtOpcUa.Commons.DataConnections.DataConditionProtoMapper.DecodeFrame).ToArray();
negotiated.Length.ShouldBe(3);
negotiated[0].Total.ShouldBe(1);
negotiated[1].SnapshotComplete.ShouldBeTrue();
negotiated[1].Items.Single().Info!.Placements.Single().Address.Identifier.ShouldBe("Plant/dev1/HR200");
negotiated[2].Items.Single().Removed.ShouldBeTrue();
}
[Fact]
public async Task H2_a_history_capable_origin_shows_history_shapes_only_with_the_header()
{
@@ -432,7 +458,21 @@ internal static class V1CompatibilityHarness
[new(0, 3)], 1, 1, "done"), token);
// A2a new-shape data: a condition-scoped item gets a snapshot-begin condition frame (arm 9).
if (open.Items[0].ConditionScope is not null)
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 5, handle, true, 0, [], true), token);
{
// A3 new-shape data (what the consumer registry consumes): begin with `total`, a record with info and a
// placement, snapshot_complete, then a delta `removed` record at the hub watermark.
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 5, handle, true, 1, [], false), token);
var placement = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"),
DataRealm.Raw, null, 0, "Plant/dev1/HR200");
var key = new string('A', 43);
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 6, handle, true, null,
[new DataConditionState(key, 3, false, true, new DataConditionInfo("AlarmConditionType", "HR200",
DataConditionSourceKind.Native, [placement], 3), true, false, true, true, 0, 777, "high", 0, null, 0,
Source, true, new DataActivationMarker("inc", 1))], true), token);
await Emit(sink, new DataSubscriptionConditions(open.SubscriptionId, open.StreamEpoch, 7, handle, false, null,
[new DataConditionState(key, 3, true, false, null, false, false, false, false, 0, 0, "", 0, null, 0, null, false, null)],
false), token);
}
}
private static async Task Emit(IDataSubscriptionDeliverySink sink, DataSubscriptionFrame frame, CancellationToken token)
{
@@ -0,0 +1,593 @@
using System.Security.Cryptography;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// A3a over the wire (plan §5.2–§5.5): imported conditions materialised by the consumer's registry in the
/// <c>mapped/conditions</c> namespace reach a projected placement folder and the Server object (<c>i=2253</c>) as exactly
/// one event per origin transition, carry the §5.2 identity fields, are gated by the mapping gate with ACLs OFF (A3-SEC),
/// keep their ConditionId when placements change (N4), wire/unwire notifiers lazily and symmetrically (N7), and never
/// tell a client "known inactive" on staleness (T2). Every absence assertion follows a must-arrive sentinel.
/// </summary>
[Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionEventWireTests
{
private const string Connection = "conn-a";
private const string MappingA = "map-a";
private const string MappingB = "map-b";
private const string Granted = ServerEventRig.KeyPrincipal;
private static readonly string Key1 = KeyOf("cond-1");
private static readonly string Key2 = KeyOf("cond-2");
// Select clauses: EventId, SourceNode, SourceName, Message, Severity, ConditionName, ActiveState/Id, AckedState/Id,
// Quality, ConditionId (ConditionType NodeId attribute), EventType.
private const int EventIdF = 0, SourceNodeF = 1, SourceNameF = 2, MessageF = 3, SeverityF = 4, ConditionNameF = 5,
ActiveF = 6, AckedF = 7, QualityF = 8, ConditionIdF = 9, EventTypeF = 10;
[Fact]
public async Task Exactly_one_event_per_origin_transition_at_both_placement_folders_and_the_Server_object_with_identity_fields()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-once", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
using var session = await rig.ConnectAsync(anonymous: false, ct);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
var device = AddItem(subscription, f.DeviceFolder);
var anchor = AddItem(subscription, f.Anchor);
await subscription.ApplyChangesAsync(ct);
new[] { server, device, anchor }.ShouldAllBe(i => StatusCode.IsGood(i.Status.Error == null ? StatusCodes.Good : i.Status.Error.StatusCode));
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "acked"));
f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "sentinel"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel") && events.Of(device).Any(e => Message(e) == "sentinel")
&& events.Of(anchor).Any(e => Message(e) == "sentinel"));
foreach (var item in new[] { server, device, anchor })
{
events.Of(item).Count(e => Message(e) == "acked").ShouldBe(1, $"exactly one event per transition at {item.StartNodeId}");
events.Of(item).Count(e => Message(e) == "sentinel").ShouldBe(1);
}
// §5.2 identity: ConditionId = SourceNode = the opaque (connection, key) id in mapped/conditions; SourceName = the
// primary placement's local display path; Severity verbatim; ConditionName from the origin.
var e0 = events.Of(server).First(e => Message(e) == "acked");
var expectedId = new NodeId(ImportedConditionIds.Identifier(Connection, Key1),
(ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri));
e0[SourceNodeF].GetNodeId().ShouldBe(expectedId);
e0[ConditionIdF].GetNodeId().ShouldBe(expectedId);
e0[SourceNameF].GetString().ShouldBe("Plant/remote-a/dev1/HR200");
e0[SeverityF].GetUInt16().ShouldBe((ushort)777);
e0[ConditionNameF].GetString().ShouldBe("HR200");
e0[AckedF].GetBoolean().ShouldBeTrue();
e0[ActiveF].GetBoolean().ShouldBeTrue();
rig.Nm.ImportedConditionCount.ShouldBe(1);
}
[Fact]
public async Task A3_SEC_with_ACLs_off_a_session_without_the_mapping_grant_receives_nothing_at_i2253_on_a_folder_or_on_refresh()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-sec", encrypted: false, ct);
var f = Fixture.Install(rig, Granted); // the anonymous principal holds no grant; ACL enforcement is OFF in this rig
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var allowedEvents = new Events();
var deniedEvents = new Events();
var allowedSub = await SubscribeAsync(allowed, allowedEvents, ct);
var deniedSub = await SubscribeAsync(denied, deniedEvents, ct);
var allowedServer = AddItem(allowedSub, ObjectIds.Server);
var deniedServer = AddItem(deniedSub, ObjectIds.Server);
var deniedFolder = AddItem(deniedSub, f.DeviceFolder);
await allowedSub.ApplyChangesAsync(ct);
await deniedSub.ApplyChangesAsync(ct);
deniedFolder.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code,
"a projected notifier admits only a caller who sees a condition wired there");
await allowedSub.ConditionRefreshAsync(ct);
await deniedSub.ConditionRefreshAsync(ct);
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "sentinel"));
await Events.WaitUntilAsync(() => allowedEvents.Of(allowedServer).Any(e => Message(e) == "sentinel"));
// Positive control: the granted session got the refresh replay AND the transition.
allowedEvents.Of(allowedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(2);
// Must-arrive sentinel on the denied session's own subscription (a non-condition event every session receives):
// RefreshStart/End of its own refresh arrived, so its queue was published after the transition.
await Events.WaitUntilAsync(() => deniedEvents.Of(deniedServer).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType));
deniedEvents.Of(deniedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(0, "no imported condition event, live or refreshed");
// Revocation reaches a queued event at publish time: the marker re-checks the gate.
f.Access.Allowed.Clear();
Interlocked.Increment(ref f.Access.Generation); // a revocation moves the authority generation (verdict caches key on it)
f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "after-revoke"));
await Task.Delay(500, ct);
allowedEvents.Of(allowedServer).Count(e => Message(e) == "after-revoke").ShouldBe(0);
}
[Fact]
public async Task A_condition_child_Read_is_authorized_through_the_condition_and_methods_are_refused_unapplied()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-child", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var ns = (ushort)allowed.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri);
var id = ImportedConditionIds.Identifier(Connection, Key1);
var child = new NodeId(ImportedConditionIds.ChildIdentifier(id, "ActiveState/Id"), ns);
rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.NodeId.ShouldBe(child, "children are instance-scoped (#629) in mapped/conditions");
var good = await allowed.ReadValueAsync(child, ct);
StatusCode.IsGood(good.StatusCode).ShouldBeTrue();
good.WrappedValue.GetBoolean().ShouldBeTrue();
var refused = await Should.ThrowAsync<ServiceResultException>(() => denied.ReadValueAsync(child, ct));
refused.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
// A3a: no local apply of a remote method — the condition stays unacknowledged (A3b dispatches to the origin).
var eventId = rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value;
await Should.ThrowAsync<ServiceResultException>(() => allowed.CallAsync(new NodeId(id, ns), MethodIds.AcknowledgeableConditionType_Acknowledge,
ct, eventId, new LocalizedText("x")));
rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value.ShouldBeFalse();
}
[Fact]
public async Task Disabling_the_primary_placement_mapping_moves_only_notifiers_and_SourceName_and_a_later_mapping_changes_no_NodeId()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-n4", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
var before = rig.Nm.FindImportedCondition(Connection, Key1)!;
var id = before.NodeId;
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
// The primary (dev1, map-a) disappears; only the mapping-B anchor placement remains.
f.Apply(Update(Key1, version: 4, active: true, acked: true, [f.BPlacement()], message: "moved"));
var after = rig.Nm.FindImportedCondition(Connection, Key1)!;
after.NodeId.ShouldBe(id, "ConditionId is keyed on (connection, condition_key) only");
ReferenceEquals(after, before).ShouldBeTrue("the same condition instance");
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the old placement folder is unwired symmetrically");
rig.Nm.IsImportedNotifierWired(f.AnchorB).ShouldBeTrue();
after.SourceName!.Value.ShouldBe("Plant/remote-b/HR200");
// A second mapping opened later (adds placements back): no NodeId changes.
f.Apply(Update(Key1, version: 5, active: true, acked: true, [.. f.TwoPlacements(), f.BPlacement()], message: "added"));
rig.Nm.FindImportedCondition(Connection, Key1)!.NodeId.ShouldBe(id);
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
}
[Fact]
public async Task A_retired_placement_folder_is_unwired_and_a_folder_holding_an_event_item_is_not_retired()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-n7", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var item = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
var sink = (IProjectedNamespacePageSink)rig.Nm;
sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeFalse("pinned by the admitted event item");
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
subscription.RemoveItem(item);
await subscription.ApplyChangesAsync(ct);
sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeTrue();
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("retirement unwires the notifier");
}
[Fact]
public async Task A_resync_of_unchanged_state_reports_nothing_and_the_next_real_transition_arrives_exactly_once()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-resync", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
var reported = rig.Nm.ImportedEventsReported;
// A re-snapshot after a stream end re-states the same state under new versions (a new epoch): the shared delta gate
// suppresses it.
f.Apply(Update(Key1, version: 10, active: true, acked: false, f.TwoPlacements()));
f.Apply(Update(Key1, version: 11, active: true, acked: false, f.TwoPlacements()));
rig.Nm.ImportedEventsReported.ShouldBe(reported);
// Positive control: a real transition after it must arrive, once.
f.Apply(Update(Key1, version: 12, active: true, acked: true, f.TwoPlacements(), message: "real"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "real"));
events.Of(server).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(1);
}
[Fact]
public async Task Staleness_is_BadNoCommunication_once_per_condition_and_never_known_inactive_and_unknown_records_change_nothing()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-stale", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
f.Apply(Update(Key2, version: 3, active: false, acked: true, f.TwoPlacements(), known: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
// T2: a state-unknown record never states "inactive" — the never-known condition is Uncertain, not Good.
rig.Nm.FindImportedCondition(Connection, Key2)!.Quality!.Value.Code.ShouldBe(StatusCodes.UncertainInitialValue.Code);
f.Apply(Update(Key1, version: 4, active: false, acked: true, f.TwoPlacements(), known: false));
rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.Value.ShouldBeTrue("an unknown record never changes the last state");
rig.Nm.MarkConnectionStale(Connection);
rig.Nm.MarkConnectionStale(Connection); // idempotent: the delta gate reports the Quality change once
f.Apply(Update(Key1, version: 5, active: true, acked: true, f.TwoPlacements(), message: "sentinel"));
await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel"));
var stale = events.Of(server).Where(e => e[QualityF].TryGetValue(out StatusCode q) && q.Code == StatusCodes.BadNoCommunication.Code).ToList();
stale.Count.ShouldBe(2, "one BadNoCommunication event per condition");
stale.ShouldContain(e => e[ActiveF].GetBoolean(), "the active condition stays active while stale");
}
// ---------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------
// Review round 1 (a3a-review-round1.md)
// ---------------------------------------------------------------------------------------------------------------------
private static bool IsRefreshRequired(ArrayOf<Variant> e) => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshRequiredEventType;
[Fact]
public async Task B3_revalidation_keeps_an_admitted_folder_item_and_deleting_a_stood_down_item_releases_its_demand()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-reval", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var folder = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
f.Access.Outstanding.ShouldBe(1, "the admitted folder item opened demand");
rig.Nm.RevalidateMonitoredItems(); // the ACL timer tick / a deploy
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-revalidation"));
await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-revalidation"));
// A revocation stands the item down; the client's later delete must still release the lease.
f.Access.Allowed.Clear();
Interlocked.Increment(ref f.Access.Generation);
rig.Nm.RevalidateMonitoredItems();
subscription.RemoveItem(folder);
await subscription.ApplyChangesAsync(ct);
f.Access.Outstanding.ShouldBe(0, "a stood-down item's delete releases its condition demand");
}
[Fact]
public async Task S1_a_full_rebuild_unwires_and_the_re_created_folder_is_promoted_and_delivers_again()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-rebuild", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue();
rig.Nm.RebuildAddressSpace();
rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the rebuild discarded the folder: its wiring goes with it");
f.Rematerialise(); // the same NodeIds, new FolderState instances
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var folder = AddItem(subscription, f.DeviceFolder);
await subscription.ApplyChangesAsync(ct);
(folder.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code, "the new folder is an event notifier again");
f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "after-rebuild"));
await Events.WaitUntilAsync(() => events.Of(folder).Any(e => Message(e) == "after-rebuild"));
}
[Fact]
public async Task Deviation3_a_folder_only_client_opens_demand_on_a_projected_folder_with_no_condition_wired_yet()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-folderdemand", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
rig.Nm.ImportedConditionCount.ShouldBe(0, "nothing materialised (after a restart or a linger)");
using var granted = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var events = new Events();
var grantedSub = await SubscribeAsync(granted, events, ct);
var deniedSub = await SubscribeAsync(denied, new Events(), ct);
var grantedItem = AddItem(grantedSub, f.AnchorB);
var deniedItem = AddItem(deniedSub, f.AnchorB);
await grantedSub.ApplyChangesAsync(ct);
await deniedSub.ApplyChangesAsync(ct);
(grantedItem.Status.Error?.StatusCode ?? StatusCodes.Good).Code.ShouldBe(StatusCodes.Good.Code);
deniedItem.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, "the mapping gate still decides");
f.Access.Outstanding.ShouldBe(1, "the folder-only client opened condition demand");
// The condition that demand brings in is delivered to that folder item.
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "arrived"));
await Events.WaitUntilAsync(() => events.Of(grantedItem).Any(e => Message(e) == "arrived"));
}
[Fact]
public async Task Deviation6_removing_an_imported_condition_sends_RefreshRequired_only_to_the_items_that_could_see_it()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-remove", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements()));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
var device = AddItem(subscription, f.DeviceFolder);
var other = AddItem(subscription, f.AnchorB); // map-b: Key1 is never wired here
await subscription.ApplyChangesAsync(ct);
var before = rig.Nm.ImportedRefreshRequiredQueued;
rig.Nm.RemoveConditions(Connection, [Key1]);
rig.Nm.ImportedConditionCount.ShouldBe(0);
await Events.WaitUntilAsync(() => events.Of(server).Any(IsRefreshRequired) && events.Of(device).Any(IsRefreshRequired));
(rig.Nm.ImportedRefreshRequiredQueued - before).ShouldBe(2, "one per item that held it");
// Must-arrive control on the map-b item, queued AFTER the removal.
f.Apply(Update(Key2, version: 3, active: true, acked: false, [f.BPlacement()], message: "control"));
await Events.WaitUntilAsync(() => events.Of(other).Any(e => Message(e) == "control"));
events.Of(other).Any(IsRefreshRequired).ShouldBeFalse("an item that never saw the removed condition is not told to refresh");
}
[Fact]
public async Task Deviation8_ConditionRefresh_replays_hundreds_of_imported_conditions_in_chunks_between_RefreshStart_and_RefreshEnd()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-replay", encrypted: false, ct);
var f = Fixture.Install(rig, Granted);
const int count = 300; // > 2 × the 128-condition chunk
rig.Nm.ApplyConditions(Enumerable.Range(0, count)
.Select(i => Update(KeyOf("bulk-" + i), version: 3, active: true, acked: false, f.TwoPlacements(), message: "bulk")).ToList());
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new Events();
var subscription = await SubscribeAsync(session, events, ct);
var server = AddItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
await subscription.ConditionRefreshAsync(ct);
await Events.WaitUntilAsync(() => events.Of(server).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType));
var list = events.Of(server).ToList();
var startAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshStartEventType);
var endAt = list.FindIndex(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType);
list.Skip(startAt + 1).Take(endAt - startAt - 1).Count(e => Message(e) == "bulk")
.ShouldBe(count, "every retained imported condition once, inside the refresh bracket");
}
private static string KeyOf(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static ImportedConditionUpdate Update(string key, long version, bool active, bool acked,
IReadOnlyList<ImportedConditionPlacement> placements, string message = "HR200 high", bool known = true)
{
var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", DataConditionSourceKind.Native,
placements.Select(p => p.Placement).ToArray(), (uint)DataConditionMethodSets.Native);
var state = new DataConditionState(key, version, false, known, info, active, acked, true, true, 0, 777, message,
StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, active || !acked, new DataActivationMarker("inc", 1));
var sourceName = (placements[0].MappingId == MappingA ? "Plant/remote-a/" : "Plant/remote-b/") + placements[0].RelativePath;
return new ImportedConditionUpdate(Connection, state, info, placements, sourceName);
}
private static string? Message(ArrayOf<Variant> e) => e[MessageF].GetLocalizedText().Text;
private static async Task<Subscription> SubscribeAsync(ISession session, Events events, CancellationToken ct)
{
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
subscription.FastEventCallback = events.OnEvents;
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
return subscription;
}
private static SdkMonitoredItem AddItem(Subscription subscription, NodeId source)
{
var filter = new EventFilter();
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventId));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceNode));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceName));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message));
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Severity));
filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.ConditionName));
filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AlarmConditionType,
[QualifiedName.From(BrowseNames.ActiveState), QualifiedName.From(BrowseNames.Id)]);
filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AcknowledgeableConditionType,
[QualifiedName.From(BrowseNames.AckedState), QualifiedName.From(BrowseNames.Id)]);
filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.Quality));
filter.SelectClauses += new SimpleAttributeOperand { TypeDefinitionId = ObjectTypeIds.ConditionType, AttributeId = Attributes.NodeId };
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventType));
var item = new SdkMonitoredItem(subscription.DefaultItem)
{
StartNodeId = source, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0,
};
subscription.AddItem(item);
return item;
}
private sealed class Events
{
private readonly object _gate = new();
private readonly List<(uint Handle, ArrayOf<Variant> Fields)> _events = [];
public void OnEvents(Subscription subscription, EventNotificationList notification, ArrayOf<string> stringTable)
{
lock (_gate) foreach (var e in notification.Events) _events.Add((e.ClientHandle, e.EventFields));
}
public IReadOnlyList<ArrayOf<Variant>> Of(SdkMonitoredItem item)
{
lock (_gate) return _events.Where(e => e.Handle == item.ClientHandle).Select(e => e.Fields).ToList();
}
public static Task WaitUntilAsync(Func<bool> condition) => RecordedEvents.WaitUntilAsync(condition);
}
/// <summary>The fake §5.4 gate: a principal set (ACL enforcement stays OFF in the rig).</summary>
internal sealed class FakeConditionAccess : IProjectedConditionAccess
{
public HashSet<string> Allowed { get; } = new(StringComparer.Ordinal);
public int Demands;
public long Generation = 1;
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) =>
caller is not null && Allowed.Contains(caller.Principal);
public long AuthorityGeneration => Interlocked.Read(ref Generation);
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) =>
caller is not null && Allowed.Contains(caller.Principal);
public bool IsConditionBearingMapping(string mappingId) => true;
/// <summary>Leases currently held (acquired minus released).</summary>
public int Outstanding;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller)
{
Interlocked.Increment(ref Demands);
Interlocked.Increment(ref Outstanding);
return new Lease(this);
}
private sealed class Lease(FakeConditionAccess owner) : IDisposable
{
private int _disposed;
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) Interlocked.Decrement(ref owner.Outstanding); }
}
}
/// <summary>A local parent, two mapping anchors (map-a, map-b) and one projected device folder under map-a.</summary>
private sealed class Fixture
{
public required ServerEventRig Rig { get; init; }
public required FakeConditionAccess Access { get; init; }
public required NodeId Anchor { get; init; }
public required NodeId AnchorB { get; init; }
public required NodeId DeviceFolder { get; init; }
public required ProjectedVariableDefinition DeviceDefinition { get; init; }
public static Fixture Install(ServerEventRig rig, string grantedPrincipal)
{
var access = new FakeConditionAccess();
access.Allowed.Add(grantedPrincipal);
rig.Nm.ProjectedConditionAccess = access; // bound before projections materialise, as the host does
var (anchor, anchorB, device, definition) = Materialise(rig.Nm);
return new Fixture { Rig = rig, Access = access, Anchor = anchor, AnchorB = anchorB, DeviceFolder = device, DeviceDefinition = definition };
}
/// <summary>Re-creates the same projected folders (new instances, same NodeIds) — e.g. after a full rebuild.</summary>
public void Rematerialise() => Materialise(Rig.Nm);
private static (NodeId Anchor, NodeId AnchorB, NodeId Device, ProjectedVariableDefinition Definition) Materialise(OtOpcUaNodeManager nm)
{
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
var rootB = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Other");
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, rootA), parent,
"remote-a", "Plant/remote-a", MappingA, 1, () => true), out var anchor).ShouldBeTrue();
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, rootB), parent,
"remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue();
var devAddress = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1");
var metadata = new DataMetadata(new DataView(devAddress, DataRealm.Raw, MappingA, 1, "Plant/remote-a/dev1"), "dev1", "Folder",
DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false);
var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value,
metadata, 1, () => true);
nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue();
return (anchor.Value, anchorB!.Value, device!.Value, definition);
}
/// <summary>Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root.</summary>
public IReadOnlyList<ImportedConditionPlacement> TwoPlacements() =>
[
new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a/dev1", "dev1/HR200"),
new(MappingA, DataRealm.Raw, View("Plant/HR200"), "Plant/remote-a", "HR200"),
];
public ImportedConditionPlacement BPlacement() =>
new(MappingB, DataRealm.Raw, View("Other/HR200"), "Plant/remote-b", "HR200");
private static DataView View(string path) =>
new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path);
public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]);
}
}
/// <summary>
/// Review r1 (test adequacy): A3-SEC with the DELIVERY gate isolated — on the denied path nothing is queued at all, so the
/// publish-time marker re-check (the second layer) has nothing to drop: <c>ProjectedEventFieldList.DroppedOnPublish</c>
/// does not move. Non-parallel: the counter is process-wide.
/// </summary>
[Collection(ImportedDeliveryGateCollection.Name)]
[Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionDeliveryGateTests
{
[Fact]
public async Task A3_SEC_the_delivery_gate_alone_withholds_a_denied_sessions_event_nothing_is_dropped_on_publish()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-r1-gate", encrypted: false, ct);
var nm = rig.Nm;
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(ServerEventRig.KeyPrincipal);
nm.ProjectedConditionAccess = access;
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var received = new System.Collections.Concurrent.ConcurrentBag<(string Who, uint Handle, string? Message)>();
async Task<Subscription> Subscribe(ISession session, string who)
{
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
subscription.FastEventCallback = (_, n, _) =>
{
foreach (var e in n.Events)
received.Add((who, e.ClientHandle, e.EventFields[0].TryGetValue(out LocalizedText text) ? text.Text : null));
};
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
var filter = new EventFilter();
filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message));
subscription.AddItem(new SdkMonitoredItem(subscription.DefaultItem)
{ StartNodeId = ObjectIds.Server, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0 });
await subscription.ApplyChangesAsync(ct);
return subscription;
}
await Subscribe(allowed, "allowed");
var deniedSub = await Subscribe(denied, "denied");
var dropped = ProjectedEventFieldList.DroppedOnPublish;
var key = Convert.ToBase64String(SHA256.HashData("gate"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_');
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR");
var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR");
var info = new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native, [view], 3);
var state = new DataConditionState(key, 1, false, true, info, true, false, true, true, 0, 500, "gated", 0, null, 0,
DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1));
nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, info, [placement], "Plant/remote-a/dev1/HR")]);
await RecordedEvents.WaitUntilAsync(() => received.Any(r => r.Who == "allowed" && r.Message == "gated")); // positive control
await deniedSub.ConditionRefreshAsync(ct); // must-arrive on the denied session: its own RefreshStart/End
await RecordedEvents.WaitUntilAsync(() => received.Count(r => r.Who == "denied") >= 2);
received.ShouldNotContain(r => r.Who == "denied" && r.Message == "gated");
(ProjectedEventFieldList.DroppedOnPublish - dropped).ShouldBe(0, "the delivery gate withheld it; nothing reached the publish-time drop");
}
}
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class ImportedDeliveryGateCollection
{
public const string Name = "Imported delivery gate (process-wide counter)";
}
@@ -0,0 +1,163 @@
using System.Diagnostics;
using System.Security.Cryptography;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// §9.3 L2 (A3 exit, m-T7) in-process measurement harness: consumer memory with 1,000 imported conditions in ONE mapping,
/// materialised through the real <see cref="IProjectedConditionSink"/> of a running SDK server — condition nodes and their
/// instance-scoped children, ids, the registry and its folder/notifier indexes, the verdict cache and the EventId registry
/// (every condition reports one event, filling its N6 slot) — plus the updates the runtime keeps per key (records + infos).
/// Opt-in: <c>OTOPCUA_A3_L2=1</c> (it forces full GCs and is not a unit gate). Pass criterion: working-set growth ≤ 200 MiB.
/// </summary>
[Trait("Feature", "GrpcData"), Trait("Phase", "A3"), Trait("Category", "Perf")]
public sealed class ImportedConditionMemoryMeasurementTests
{
private const string Connection = "conn-l2";
private const string Mapping = "map-l2";
private const string MappingB = "map-l2b";
private const int Conditions = 1_000;
[Fact]
public async Task L2_one_thousand_imported_conditions_in_one_mapping_grow_the_working_set_by_at_most_200_MiB()
{
if (Environment.GetEnvironmentVariable("OTOPCUA_A3_L2") != "1") Assert.Skip("Set OTOPCUA_A3_L2=1 to run the A3 L2 memory measurement.");
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3-l2", encrypted: false, ct);
var nm = rig.Nm;
// Access first: a condition-bearing mapping's anchor folders are event notifiers from materialisation.
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(ServerEventRig.KeyPrincipal);
nm.ProjectedConditionAccess = access;
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
// A3b review S5: worst case — TWO placements per condition (two mappings, two folders it is wired into).
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(Mapping, root), parent,
"remote", "Plant/remote", Mapping, 1, () => true), out var anchorA).ShouldBeTrue();
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, root), parent,
"remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue();
// Event items: the Server object and both placement folders, publishing OFF so the server-side queues hold their events.
using var session = await rig.ConnectAsync(anonymous: false, ct);
var subscription = new Opc.Ua.Client.Subscription(session.DefaultSubscription) { PublishingInterval = 1000, PublishingEnabled = false };
session.AddSubscription(subscription);
await subscription.CreateAsync(ct);
foreach (var source in new[] { ObjectIds.Server, Local(session, anchorA!.Value), Local(session, anchorB!.Value) })
{
var item = new Opc.Ua.Client.MonitoredItem(subscription.DefaultItem)
{
StartNodeId = source, AttributeId = Attributes.EventNotifier, QueueSize = 1000,
Filter = new EventFilter { SelectClauses = [new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.EventId)),
new SimpleAttributeOperand(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.Message))] },
};
subscription.AddItem(item);
}
await subscription.ApplyChangesAsync(ct);
subscription.MonitoredItems.All(m => ServiceResult.IsGood(m.Status.Error)).ShouldBeTrue("all three event items are admitted");
var (heap0, ws0) = Measure();
var totalMemory0 = GC.GetTotalMemory(forceFullCollection: true);
var keys = Enumerable.Range(0, Conditions).Select(i => KeyOf("l2-" + i)).ToArray();
// Runner state (worst case): the committed Live records AND a full re-snapshot Buffer of the same keys.
var live = keys.Select((k, i) => Update(k, i, 3, active: true, acked: false, sequence: 1)).ToList();
var sw = Stopwatch.StartNew();
nm.ApplyConditions(live);
var materialise = sw.Elapsed;
var (heapMid, _) = Measure();
// Every N6 EventId slot filled: RecentEventIds transitions per condition, each a reported event minting an EventId.
List<ImportedConditionUpdate> buffer = [];
sw.Restart();
for (var t = 0; t < OpcUaServer.ProjectedConditionRegistry.RecentEventIds; t++)
{
buffer = keys.Select((k, i) => Update(k, i, 4 + t, active: true, acked: t % 2 == 0, sequence: (ulong)(2 + t / 2))).ToList();
nm.ApplyConditions(buffer);
}
var transition = sw.Elapsed;
nm.ImportedConditionCount.ShouldBe(Conditions);
var slots = nm.FindImportedConditionRecentEventCount(Connection, keys[0]);
slots.ShouldBe(OpcUaServer.ProjectedConditionRegistry.RecentEventIds, "every N6 slot is in use");
// Exercise the verdict cache once per condition (one identity).
var identity = new Security.RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [], ServerEventRig.KeyPrincipal,
"k", null, null);
foreach (var k in keys)
nm.AuthorizeImportedCondition(identity, Core.Abstractions.OpcUaOperation.Read, nm.ImportedConditionNodeId(Connection, k)).ShouldBeTrue();
var (heap1, ws1) = Measure();
var (reportedHeap0, reportedHeap1) = (totalMemory0, GC.GetTotalMemory(forceFullCollection: true));
GC.KeepAlive(live);
GC.KeepAlive(buffer);
GC.KeepAlive(subscription);
var heapGrowth = heap1 - heap0;
var wsGrowth = ws1 - ws0;
var line = $"L2 (worst case: 2 placements, {slots} EventId slots, 3 event items, Live+Buffer records): {Conditions} conditions: " +
$"managed heap +{heapGrowth / 1048576.0:F1} MiB ({heapGrowth / Conditions:N0} B/condition; after materialise {(heapMid - heap0) / Conditions:N0}), " +
$"working set +{wsGrowth / 1048576.0:F1} MiB ({wsGrowth / Conditions:N0} B/condition); materialise {materialise.TotalMilliseconds:F0} ms, " +
$"{OpcUaServer.ProjectedConditionRegistry.RecentEventIds} transitions {transition.TotalMilliseconds:F0} ms; events reported {nm.ImportedEventsReported}; " +
$"GC.GetTotalMemory delta (not used, see Measure) +{(reportedHeap1 - reportedHeap0) / 1048576.0:F1} MiB";
TestContext.Current.TestOutputHelper?.WriteLine(line);
if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine);
wsGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024);
heapGrowth.ShouldBeLessThanOrEqualTo(200L * 1024 * 1024, "the retained managed heap is under the same bound");
}
private static NodeId Local(Opc.Ua.Client.ISession session, NodeId serverId) =>
new(serverId.IdentifierAsString, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri));
/// <summary>
/// Retained managed heap and settled working set after forced compacting GCs.
/// </summary>
/// <remarks>
/// A3 review round 2: <c>GC.GetTotalMemory</c> is NOT the retained heap on this runtime (.NET 10, regions). In the same
/// process state it reported either +92 MiB or +218 MiB (bimodal, run to run) while <c>GC.GetGCMemoryInfo</c>'s heap size
/// was 135.5 MB in both, and a heap dump of a "+218 MiB" run held 136 MB of objects in total (<c>eeheap -gc</c>: allocated
/// 136,318,696, committed 236,208,128) — the extra ~125 MiB was committed-but-free region space. The live heap is therefore
/// taken from the last full blocking GC's <c>HeapSizeBytes − FragmentedBytes</c>, and the working set is sampled until the GC
/// has decommitted those free regions (two samples 500 ms apart within 1 MiB, at most 10 s): the instant after the forced
/// GCs it still counts them (+214 MiB seen; +133 MiB two seconds later in the same run).
/// </remarks>
private static (long Heap, long WorkingSet) Measure()
{
for (var i = 0; i < 3; i++) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true); GC.WaitForPendingFinalizers(); }
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true, compacting: true);
var info = GC.GetGCMemoryInfo(GCKind.FullBlocking);
using var process = Process.GetCurrentProcess();
process.Refresh();
var ws = process.WorkingSet64;
var settle = Stopwatch.StartNew();
while (settle.Elapsed < TimeSpan.FromSeconds(10))
{
Thread.Sleep(500);
process.Refresh();
var next = process.WorkingSet64;
var stable = Math.Abs(next - ws) < 1024 * 1024;
ws = next;
if (stable) break;
}
return (info.HeapSizeBytes - info.FragmentedBytes, ws);
}
private static string KeyOf(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static ImportedConditionUpdate Update(string key, int index, long version, bool active, bool acked, ulong sequence)
{
var path = $"Plant/dev{index / 10}/HR{index}";
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path);
var placements = new[]
{
new ImportedConditionPlacement(Mapping, DataRealm.Raw, view, "Plant/remote", path["Plant/".Length..]),
new ImportedConditionPlacement(MappingB, DataRealm.Raw, view, "Plant/remote-b", path["Plant/".Length..]),
};
var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", $"HR{index}", DataConditionSourceKind.Native,
[view], (uint)DataConditionMethodSets.Native);
var state = new DataConditionState(key, version, false, true, info, active, acked, true, true, 0, 500, $"HR{index} high",
StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", sequence));
return new ImportedConditionUpdate(Connection, state, info, placements, "Plant/remote/" + placements[0].RelativePath);
}
}
@@ -0,0 +1,716 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Security.Cryptography;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// A3b over the wire (plan §5.6): Part 9 methods on an imported condition are claimed by the node manager's
/// <see cref="ICallAsyncNodeManager"/> implementation and dispatched to the origin through the
/// <see cref="IProjectedConditionMethods"/> port — never under the node manager's <c>Lock</c>, never applied locally (the
/// node changes only when the origin's record arrives), gated per local caller, with the EventId checked against this
/// consumer's own registry. The port here stands in for the origin (its handler can be stalled, can time out, can join).
/// </summary>
[Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionMethodWireTests
{
private const string Connection = "conn-a";
private const string MappingA = "map-a";
private const string Granted = ServerEventRig.KeyPrincipal;
private static readonly string Key1 = KeyOf("cond-1");
private static readonly DataActivationMarker Marker1 = new("inc", 1);
[Fact]
public async Task A_remote_Acknowledge_reaches_the_origin_once_a_duplicate_joins_and_local_state_changes_only_with_the_origin_record()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-ack", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Port.Handler = async (_, _) => { await release.Task; return Applied(); };
var eventId = f.CurrentEventId();
var first = CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "op ack", ct);
await WaitUntilAsync(() => f.Port.Calls.Count == 1);
var duplicate = CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "op ack", ct);
await WaitUntilAsync(() => rig.Nm.ImportedMethodsJoined == 1);
f.Acked().ShouldBeFalse("nothing is applied locally while the origin has not answered");
release.SetResult();
(await first).ShouldBe(StatusCodes.Good);
(await duplicate).ShouldBe(StatusCodes.Good, "a duplicate of an in-flight call joins it and gets the same answer");
f.Port.Calls.Count.ShouldBe(1, "the origin is called once");
f.Acked().ShouldBeFalse("Good from the origin is not the confirming record: still unacknowledged locally");
var call = f.Port.Calls.Single();
call.Method.ShouldBe(DataConditionMethods.Acknowledge);
call.ConnectionId.ShouldBe(Connection);
call.ConditionKey.ShouldBe(Key1);
call.Placement.ShouldBe(f.Placements[0], "the primary placement the caller passed the gate on");
call.ExpectedActivation.ShouldBe(Marker1);
call.Comment.ShouldBe("op ack");
call.OnBehalfOf.ShouldBe(Granted);
call.OperationId.ShouldStartWith("a3-");
call.RemainingBudget.ShouldBeLessThanOrEqualTo(f.Port.Timeout);
// The origin's record arrives on the stream: only now does the local node change (positive control).
f.Apply(Update(version: 4, active: true, acked: true));
f.Acked().ShouldBeTrue();
// A later call (nothing in flight) is a NEW dispatch with a fresh operation id — no retry, no stale join.
(await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "note", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Count.ShouldBe(2);
f.Port.Calls.Select(c => c.OperationId).Distinct().Count().ShouldBe(2);
f.Port.Calls.Last().Method.ShouldBe(DataConditionMethods.AddComment);
}
[Fact]
public async Task A_child_method_Call_is_authorized_through_the_condition_and_a_caller_without_the_grant_is_denied_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-child", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var allowed = await rig.ConnectAsync(anonymous: false, ct);
using var denied = await rig.ConnectAsync(anonymous: true, ct);
var ns = (ushort)allowed.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri);
var childMethod = new NodeId(ImportedConditionIds.ChildIdentifier(f.Identifier, "Acknowledge"), ns);
rig.Nm.FindImportedCondition(Connection, Key1)!.Acknowledge!.NodeId.ShouldBe(childMethod, "the instance-scoped method node (#629)");
(await CallAsync(denied, f.ConditionId(denied), childMethod, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
(await CallAsync(denied, f.ConditionId(denied), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.BadUserAccessDenied);
f.Port.Calls.ShouldBeEmpty("a caller without the grant sends nothing");
f.Port.AuthorizedFor.ShouldContain(("anonymous", DataConditionMethods.Acknowledge), "re-gated per LOCAL caller");
// The grant is per method: AlarmAcknowledge does not authorize Confirm.
f.Port.GrantedMethods = DataConditionMethods.Acknowledge | DataConditionMethods.AddComment;
f.Apply(Update(version: 4, active: true, acked: false, native: false, message: "scripted"));
(await CallAsync(allowed, f.ConditionId(allowed), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(), "c", ct))
.ShouldBe(StatusCodes.BadUserAccessDenied);
f.Port.Calls.ShouldBeEmpty();
// Positive control: the granted caller's child Call reaches the origin.
(await CallAsync(allowed, f.ConditionId(allowed), childMethod, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Acknowledge);
f.Acked().ShouldBeFalse();
}
[Fact]
public async Task An_unknown_or_superseded_EventId_is_BadEventIdUnknown_and_a_native_Confirm_or_a_shelve_is_BadNotSupported_all_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-eventid", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var id = f.ConditionId(session);
var old = f.CurrentEventId();
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, Guid.NewGuid().ToByteArray(), "x", ct))
.ShouldBe(StatusCodes.BadEventIdUnknown);
// A new occurrence (Acked true→false bumps the marker at the origin): the old EventId no longer binds.
f.Apply(Update(version: 4, active: true, acked: true));
f.Apply(Update(version: 5, active: true, acked: false, marker: new DataActivationMarker("inc", 2), message: "again"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, old, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown);
// Native Confirm has no upstream path; shelving is not imported at all.
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadNotSupported);
var shelve = await session.CallAsync(null, [new CallMethodRequest { ObjectId = id, MethodId = MethodIds.AlarmConditionType_ShelvingState_OneShotShelve }], ct);
shelve.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadNotSupported.Code);
f.Port.Calls.ShouldBeEmpty("every refusal above is local and sends nothing");
// Positive control: the current EventId (new marker) reaches the origin with the CURRENT marker.
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker("inc", 2));
}
[Fact]
public async Task A_resync_with_a_new_marker_re_binds_EventIds_only_when_time_is_unchanged_else_RefreshRequired_and_a_fresh_ackable_EventId()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-rebind", encrypted: false, ct);
var f = Fixture.Install(rig);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
f.Apply(Update(version: 3, active: true, acked: false, time: t0));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var id = f.ConditionId(session);
var before = f.CurrentEventId();
// Origin restart, same state, same time ⇒ re-bound (F6): the pre-resync EventId still acknowledges.
f.Apply(Update(version: 1, active: true, acked: false, time: t0, marker: new DataActivationMarker("inc-b", 7)));
f.CurrentEventId().ShouldBe(before, "no event, no new EventId");
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-b", 7));
// Another resync whose time differs (a clear + re-raise may have happened in the gap) ⇒ NOT re-bound.
var refresh = rig.Nm.ImportedRefreshRequiredQueued;
f.Apply(Update(version: 1, active: true, acked: false, time: t0.AddSeconds(5), marker: new DataActivationMarker("inc-c", 9)));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown);
var fresh = f.CurrentEventId();
fresh.ShouldNotBe(before, "a fresh EventId bound to the new marker — what a ConditionRefresh now returns");
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Count.ShouldBe(2);
f.Port.Calls.Last().ExpectedActivation.ShouldBe(new DataActivationMarker("inc-c", 9));
_ = refresh; // review S6: the RefreshRequired itself is pinned over the wire by A_resync_that_cannot_re_bind_…
}
/// <summary>
/// §5.6 step 6 / §9.3 L3 (hard gate): the origin's method handler stalls 5 s. Read, Browse and a data Publish on the
/// consumer complete in &lt; 200 ms meanwhile, the node manager's <c>Lock</c> is free, and no acknowledged state is
/// observable before the origin's record (positive control: it arrives after release).
/// </summary>
/// <param name="realPath">
/// Review S5: false = the stall sits at the consumer's port (the original measurement); true = behind a REAL
/// <c>ProjectedConditionAccess</c> + lease + <c>GrpcDataConnection</c>, the in-process origin's handler stalling 5 s.
/// </param>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Lock_freedom_a_5s_stalled_origin_method_delays_no_Read_Browse_or_data_Publish_and_applies_nothing_before_the_record(bool realPath)
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-l3", encrypted: false, ct);
var f = Fixture.Install(rig);
await using var real = realPath ? new RealConditionMethodPath(Connection, MappingA, f.Port, TimeSpan.FromSeconds(5)) : null;
if (real is not null)
{
rig.Nm.ProjectedConditionMethods = real.Port;
// The condition stream is open (its serving incarnation addresses the call) before anything is measured.
await WaitUntilAsync(() => real.Access.CallAsync(new ImportedConditionMethodCall(Connection, Key1, Fixture.DefaultPlacements[0],
DataConditionMethods.Acknowledge, Marker1, null, "probe", TimeSpan.Zero, null), ct).Result.StatusCode != 0x80310000u);
}
var tag = rig.EnsureRawVariable("l3", "Double", writable: false);
rig.Sink.WriteValue(tag, 0.0, 0, DateTime.UtcNow, AddressSpaceRealm.Raw);
f.Apply(Update(version: 3, active: true, acked: false));
using var caller = await rig.ConnectAsync(anonymous: false, ct);
using var observer = await rig.ConnectAsync(anonymous: false, ct);
var tagId = ExpandedNodeId.ToNodeId(ExpandedNodeId.Parse(ServerEventRig.RawNsu(tag)), observer.NamespaceUris);
var plant = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var plantId = new NodeId(plant.IdentifierAsString, (ushort)observer.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri));
var values = new ConcurrentDictionary<double, long>();
var subscription = new Subscription(observer.DefaultSubscription) { PublishingInterval = 20 };
observer.AddSubscription(subscription);
await subscription.CreateAsync(ct);
var item = new SdkMonitoredItem(subscription.DefaultItem) { StartNodeId = tagId, AttributeId = Attributes.Value, SamplingInterval = 0, QueueSize = 100 };
item.Notification += (mi, _) =>
{
var now = Stopwatch.GetTimestamp();
foreach (var v in mi.DequeueValues()) if (v.WrappedValue.TryGetValue(out double d)) values.TryAdd(d, now);
};
subscription.AddItem(item);
await subscription.ApplyChangesAsync(ct);
async Task<(double Read, double Browse, double Publish, double LockWait)> MeasureAsync(double value)
{
var sw = Stopwatch.StartNew();
(await observer.ReadValueAsync(tagId, ct)).StatusCode.ShouldBe(StatusCodes.Good);
var read = sw.Elapsed.TotalMilliseconds;
sw.Restart();
var browse = await observer.BrowseAsync(null, null, 0, [new BrowseDescription { NodeId = plantId, BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct);
StatusCode.IsGood(browse.Results[0].StatusCode).ShouldBeTrue();
var browseMs = sw.Elapsed.TotalMilliseconds;
var written = Stopwatch.GetTimestamp();
rig.Sink.WriteValue(tag, value, 0, DateTime.UtcNow, AddressSpaceRealm.Raw);
await WaitUntilAsync(() => values.ContainsKey(value));
var publish = Stopwatch.GetElapsedTime(written, values[value]).TotalMilliseconds;
sw.Restart();
var taken = Monitor.TryEnter(rig.Nm.Lock, TimeSpan.FromMilliseconds(200));
var lockWait = sw.Elapsed.TotalMilliseconds;
if (taken) Monitor.Exit(rig.Nm.Lock);
taken.ShouldBeTrue("the node manager Lock is free while the remote call is in flight");
return (read, browseMs, publish, lockWait);
}
var baseline = await MeasureAsync(1.0);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Port.Timeout = TimeSpan.FromSeconds(20);
f.Port.Handler = async (_, token) => { await Task.WhenAny(release.Task, Task.Delay(TimeSpan.FromSeconds(5), token)); return Applied(); };
var stall = Stopwatch.StartNew();
var ack = CallAsync(caller, f.ConditionId(caller), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "l3", ct);
await WaitUntilAsync(() => real is null ? f.Port.Calls.Count == 1 : Volatile.Read(ref real.Server.MethodCalls) == 1);
var during = new List<(double Read, double Browse, double Publish, double LockWait)>();
for (var i = 0; i < 10 && !ack.IsCompleted; i++)
{
during.Add(await MeasureAsync(100 + i));
f.Acked().ShouldBeFalse("no acknowledged state is observable before the origin's record");
await Task.Delay(200, ct);
}
ack.IsCompleted.ShouldBeFalse("the measurements ran while the remote call was stalled");
during.Count.ShouldBe(10);
(await ack).ShouldBe(StatusCodes.Good);
if (real is not null) Volatile.Read(ref real.Server.MethodAnswers).ShouldBe(1, "the origin's stalled handler answered once, after the stall");
var stalled = stall.Elapsed;
f.Acked().ShouldBeFalse();
f.Apply(Update(version: 4, active: true, acked: true));
f.Acked().ShouldBeTrue("positive control: the record applies after release");
var maxRead = during.Max(m => m.Read);
var maxBrowse = during.Max(m => m.Browse);
var maxPublish = during.Max(m => m.Publish);
var maxLock = during.Max(m => m.LockWait);
var line =
$"L3 ({(realPath ? "real ProjectedConditionAccess + GrpcDataConnection" : "port")}): stall {stalled.TotalMilliseconds:F0} ms; baseline read {baseline.Read:F1} browse {baseline.Browse:F1} publish {baseline.Publish:F1} lock {baseline.LockWait:F2}; " +
$"during (n={during.Count}) max read {maxRead:F1} browse {maxBrowse:F1} publish {maxPublish:F1} lock {maxLock:F2} ms";
TestContext.Current.TestOutputHelper?.WriteLine(line);
if (Environment.GetEnvironmentVariable("OTOPCUA_A3_MEASURE_OUT") is { Length: > 0 } outPath) File.AppendAllText(outPath, line + Environment.NewLine);
stalled.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(4.9));
maxRead.ShouldBeLessThan(200);
maxBrowse.ShouldBeLessThan(200);
maxPublish.ShouldBeLessThan(200);
}
[Fact]
public async Task One_Call_request_mixing_a_local_condition_and_an_imported_one_runs_the_local_one_through_base_Call_unchanged()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-mixed", encrypted: false, ct);
rig.Enforce(true, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(Granted, "acl-key", NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.MethodCall));
rig.MaterialiseNative();
var routed = 0;
rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routed);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(true, new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "local"));
await RecordedEvents.WaitUntilAsync(() => events.Has(serverItem, "local"));
var localEventId = events.LatestEventId(serverItem, "local");
var response = await session.CallAsync(null,
[
new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] },
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local native ack runs the SDK path (base.Call) unchanged");
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the imported one is claimed and dispatched");
Volatile.Read(ref routed).ShouldBe(1);
f.Port.Calls.Single().Comment.ShouldBe("remote ack");
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(serverItem, "local").Count >= 2);
events.ConditionEvents(serverItem, "local").Last()[RecordedEvents.AckedField].ClrValue()!.ShouldBe(true, "one local ack event (#587)");
f.Acked().ShouldBeFalse("the imported condition did not change locally");
}
[Fact]
public async Task A_timed_out_call_answers_BadTimeout_OutcomeUnknown_is_BadCommunicationError_and_a_refusal_passes_the_origins_status_nothing_applied()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-timeout", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var id = f.ConditionId(session);
// ConditionMethodTimeoutMilliseconds = 300 ms; the origin never answers.
f.Port.Timeout = TimeSpan.FromMilliseconds(300);
var cancelled = false;
f.Port.Handler = async (_, token) =>
{
try { await Task.Delay(Timeout.Infinite, token); }
catch (OperationCanceledException) { Volatile.Write(ref cancelled, true); throw; }
return Applied();
};
var sw = Stopwatch.StartNew();
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout);
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(3), "bounded by the mapping's method timeout (+ grace), not the request's");
// Review N1: the port's call is cancelled explicitly on the timeout (it used to rely on a timer sharing WaitAsync's due
// time, disposed unfired when WaitAsync won).
await WaitUntilAsync(() => Volatile.Read(ref cancelled));
f.Port.Calls.Count.ShouldBe(1, "dispatched once, never retried");
f.Acked().ShouldBeFalse();
f.Port.Timeout = TimeSpan.FromSeconds(5);
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadCommunicationError);
// Review S2: the transport's KNOWN timeout passes through (it used to be inferred from the consumer's own clock, so a
// deadline the transport hit before the consumer's budget elapsed read as BadCommunicationError).
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, "deadline"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadTimeout);
// Review S3: a definite failure at the origin is the origin's status, not "unknown".
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.DriverConfirmedFailure, StatusCodes.BadConditionAlreadyEnabled.Code, "refused"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadConditionAlreadyEnabled);
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadInvalidState.Code, "not Primary"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadInvalidState);
f.Port.Handler = (_, _) => Task.FromResult(new DataConditionMethodResult(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "No condition stream"));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.BadNoCommunication);
f.Acked().ShouldBeFalse("no outcome applies anything locally");
}
/// <summary>
/// A3b review S6 (non-vacuous RefreshRequired) + N2: a same-incarnation marker move at an unchanged time is a NEW
/// occurrence — not re-bound; the old EventId is unknown, a fresh one is ackable, and a subscriber that can see the
/// condition receives RefreshRequired over the wire.
/// </summary>
[Fact]
public async Task A_resync_that_cannot_re_bind_sends_RefreshRequired_to_a_subscriber_and_a_same_incarnation_bump_is_not_re_bound()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-refreshreq", encrypted: false, ct);
var f = Fixture.Install(rig);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
f.Apply(Update(version: 3, active: true, acked: false, time: t0));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
var id = f.ConditionId(session);
var before = f.CurrentEventId();
events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType).ShouldBeFalse();
// Same incarnation, sequence bumped, same time and state: by the origin's definition a new occurrence (review N2).
f.Apply(Update(version: 4, active: true, acked: false, time: t0, marker: new DataActivationMarker(Marker1.Incarnation, 2)));
await RecordedEvents.WaitUntilAsync(() => events.HasType(serverItem, ObjectTypeIds.RefreshRequiredEventType));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, before, "x", ct)).ShouldBe(StatusCodes.BadEventIdUnknown);
var fresh = f.CurrentEventId();
fresh.ShouldNotBe(before);
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, fresh, "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().ExpectedActivation.ShouldBe(new DataActivationMarker(Marker1.Incarnation, 2));
}
/// <summary>Review N3: a record that first carries a marker (the previous one had none) binds a fresh, ackable EventId.</summary>
[Fact]
public async Task A_marker_appearing_on_an_unchanged_state_mints_an_ackable_EventId()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-nullmarker", encrypted: false, ct);
var f = Fixture.Install(rig);
var t0 = DateTimeOffset.UtcNow.AddMinutes(-1);
f.Apply(Update(version: 3, active: true, acked: false, time: t0, noMarker: true));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var id = f.ConditionId(session);
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.BadEventIdUnknown, "no marker: nothing to address the origin's occurrence with");
f.Apply(Update(version: 4, active: true, acked: false, time: t0));
(await CallAsync(session, id, MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct)).ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().ExpectedActivation.ShouldBe(Marker1);
}
/// <summary>
/// Review S6: the native-Confirm guard and the supported-methods guard, each isolated — a native condition whose listing
/// DOES carry Confirm is still refused; a scripted one whose listing lacks it is refused; a scripted one with it dispatches.
/// </summary>
[Fact]
public async Task Native_Confirm_is_refused_even_when_listed_and_a_scripted_Confirm_follows_the_listing()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-confirm", encrypted: false, ct);
var f = Fixture.Install(rig);
var native = KeyOf("native-listed"); var scriptedNo = KeyOf("scripted-no"); var scriptedYes = KeyOf("scripted-yes");
var all = (uint)DataConditionMethodSets.All;
f.Apply(Update(version: 3, active: true, acked: true, key: native, methods: all));
f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedNo,
methods: (uint)(DataConditionMethods.Acknowledge | DataConditionMethods.AddComment)));
f.Apply(Update(version: 3, active: true, acked: true, native: false, key: scriptedYes, methods: all));
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await CallAsync(session, f.ConditionId(session, key: native), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: native), "c", ct))
.ShouldBe(StatusCodes.BadNotSupported, "native: no upstream confirm path, whatever the listing says");
(await CallAsync(session, f.ConditionId(session, key: scriptedNo), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedNo), "c", ct))
.ShouldBe(StatusCodes.BadNotSupported, "the origin's supported_methods lacks Confirm");
f.Port.Calls.ShouldBeEmpty();
(await CallAsync(session, f.ConditionId(session, key: scriptedYes), MethodIds.AcknowledgeableConditionType_Confirm, f.CurrentEventId(key: scriptedYes), "c", ct))
.ShouldBe(StatusCodes.Good);
f.Port.Calls.Single().Method.ShouldBe(DataConditionMethods.Confirm);
}
/// <summary>
/// Review S1 + S6: a fault BEFORE dispatch (the gate throws) is that item's <c>BadInternalError</c>, unsent — the batch
/// still answers and a local item after the imported one is applied and Good (imported-first ordering); a batch
/// carrying a pre-validation failure answers it per item while its imported call dispatches; a port that THROWS after
/// dispatch is OutcomeUnknown (<c>BadCommunicationError</c>), dispatched once.
/// </summary>
[Fact]
public async Task A_fault_before_dispatch_is_a_per_item_BadInternalError_and_the_rest_of_the_batch_still_answers()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-fault", encrypted: false, ct);
rig.Enforce(true, [ServerEventRig.Key()], ServerEventRig.ClusterGrant(Granted, "acl-key", NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead
| NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm | NodePermissions.MethodCall));
rig.MaterialiseNative();
var routed = 0;
rig.Nm.NativeAlarmAckRouter = _ => Interlocked.Increment(ref routed);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var serverItem = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
rig.Project(true, new AlarmConditionSnapshot(true, false, true, true, AlarmShelvingKind.Unshelved, 700, "local"));
await RecordedEvents.WaitUntilAsync(() => events.Has(serverItem, "local"));
var localEventId = events.LatestEventId(serverItem, "local");
f.Port.AuthorizeThrows = true;
var response = await session.CallAsync(null,
[
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
new CallMethodRequest { ObjectId = ServerEventRig.ConditionNodeId(session, native: true), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(ByteString.From(localEventId)), new Variant(new LocalizedText("local ack"))] },
], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadInternalError.Code, "the imported item faulted before dispatch");
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code, "the local item after it was applied and answers");
Volatile.Read(ref routed).ShouldBe(1);
f.Port.Calls.ShouldBeEmpty("nothing was sent");
// A pre-validation failure in the same batch as a good imported call: answered per item, the imported one dispatched.
f.Port.AuthorizeThrows = false;
response = await session.CallAsync(null,
[
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = NodeId.Null },
new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("remote ack"))] },
], ct);
StatusCode.IsBad(response.Results[0].StatusCode).ShouldBeTrue();
response.Results[1].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
f.Port.Calls.Count.ShouldBe(1);
// A port that throws after dispatch: OutcomeUnknown, never retried.
f.Port.Handler = (_, _) => throw new InvalidOperationException("port fault");
(await CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), "n", ct))
.ShouldBe(StatusCodes.BadCommunicationError);
f.Port.Calls.Count.ShouldBe(2);
f.Acked().ShouldBeFalse();
}
/// <summary>
/// Review S4: one stalled connection holds at most its sub-limit (4) of the node's 8 slots — a call to another connection
/// still dispatches at once; the stalled connection's further calls wait out their budget and answer
/// <c>BadTooManyOperations</c> unsent (slot exhaustion).
/// </summary>
[Fact]
public async Task One_stalled_connection_cannot_starve_another_and_its_excess_calls_are_BadTooManyOperations_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-slots", encrypted: false, ct);
var f = Fixture.Install(rig);
const string other = "conn-b";
f.Apply(Update(version: 3, active: true, acked: false));
f.Apply(Update(version: 3, active: true, acked: false, connection: other));
using var session = await rig.ConnectAsync(anonymous: false, ct);
f.Port.Timeout = TimeSpan.FromSeconds(3);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Port.Handler = async (call, token) =>
{
if (call.ConnectionId == Connection) await release.Task.WaitAsync(token);
return Applied();
};
var stalled = Enumerable.Range(0, OtOpcUaNodeManager.DefaultImportedMethodConcurrency)
.Select(i => CallAsync(session, f.ConditionId(session), MethodIds.ConditionType_AddComment, f.CurrentEventId(), $"c{i}", ct)).ToArray();
await WaitUntilAsync(() => f.Port.Calls.Count == OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
var sw = Stopwatch.StartNew();
(await CallAsync(session, f.ConditionId(session, other), MethodIds.ConditionType_AddComment, f.CurrentEventId(other), "b", ct))
.ShouldBe(StatusCodes.Good, "a healthy origin is not starved by a stalled one");
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(1.5));
var outcomes = await Task.WhenAll(stalled);
outcomes.Count(o => o == StatusCodes.BadTooManyOperations).ShouldBe(
OtOpcUaNodeManager.DefaultImportedMethodConcurrency - OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
outcomes.Count(o => o == StatusCodes.BadTimeout).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection);
f.Port.Calls.Count(c => c.ConnectionId == Connection).ShouldBe(OtOpcUaNodeManager.DefaultImportedMethodConcurrencyPerConnection,
"the excess calls never dispatched");
release.SetResult();
}
/// <summary>Review S4 floor: a request whose own deadline leaves less than the minimum dispatch budget is BadTimeout, unsent.</summary>
[Fact]
public async Task A_request_deadline_below_the_dispatch_floor_is_BadTimeout_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-floor", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
using var session = await rig.ConnectAsync(anonymous: false, ct);
var response = await session.CallAsync(new RequestHeader { TimeoutHint = 450 },
[new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.BadTimeout.Code);
f.Port.Calls.ShouldBeEmpty("450 ms − 250 ms grace leaves less than the 250 ms floor: refused before dispatch");
// Positive control: a roomy deadline dispatches, and the port's budget ends before the client's TimeoutHint (N7).
response = await session.CallAsync(new RequestHeader { TimeoutHint = 2_000 },
[new CallMethodRequest { ObjectId = f.ConditionId(session), MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [new Variant(f.CurrentEventId()), new Variant(new LocalizedText("x"))] }], ct);
response.Results[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
f.Port.Calls.Single().RemainingBudget.ShouldBeLessThanOrEqualTo(TimeSpan.FromMilliseconds(2_000) - OtOpcUaNodeManager.ImportedMethodGrace);
}
/// <summary>Review S6: a Warm standby refuses an imported method locally (<c>BadInvalidState</c>), nothing sent.</summary>
[Fact]
public async Task A_warm_standby_refuses_an_imported_method_unsent()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await WarmRedundancyWireTests.StartModeAsync("a3b-standby", "Warm", ct);
var f = Fixture.Install(rig);
f.Apply(Update(version: 3, active: true, acked: false));
var projection = rig.Server.CreateStandbyProjection()!;
WarmRedundancyWireTests.Demote(projection);
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.BadInvalidState);
f.Port.Calls.ShouldBeEmpty();
WarmRedundancyWireTests.Promote(projection);
(await CallAsync(session, f.ConditionId(session), MethodIds.AcknowledgeableConditionType_Acknowledge, f.CurrentEventId(), "x", ct))
.ShouldBe(StatusCodes.Good);
}
/// <summary>Review S6: identical calls from DIFFERENT principals never join — each is its own dispatch.</summary>
[Fact]
public async Task Identical_calls_from_different_principals_do_not_join()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("a3b-nojoin", encrypted: false, ct);
var f = Fixture.Install(rig);
f.Port.Granted.Add("anonymous");
f.Apply(Update(version: 3, active: true, acked: false));
using var keyed = await rig.ConnectAsync(anonymous: false, ct);
using var anonymous = await rig.ConnectAsync(anonymous: true, ct);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Port.Handler = async (_, _) => { await release.Task; return Applied(); };
var eventId = f.CurrentEventId();
var a = CallAsync(keyed, f.ConditionId(keyed), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct);
var b = CallAsync(anonymous, f.ConditionId(anonymous), MethodIds.AcknowledgeableConditionType_Acknowledge, eventId, "same", ct);
await WaitUntilAsync(() => f.Port.Calls.Count == 2);
rig.Nm.ImportedMethodsJoined.ShouldBe(0);
release.SetResult();
(await a).ShouldBe(StatusCodes.Good);
(await b).ShouldBe(StatusCodes.Good);
f.Port.Calls.Select(c => c.OnBehalfOf).Order().ShouldBe(new[] { "anonymous", Granted }.Order());
}
// ---------------------------------------------------------------------------------------------------------------------
private static DataConditionMethodResult Applied() => new(DataWriteState.AcceptedUnconfirmed, 0, null);
private static string KeyOf(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static ImportedConditionUpdate Update(long version, bool active, bool acked, DataActivationMarker? marker = null,
string message = "HR200 high", bool native = true, DateTimeOffset? time = null, string connection = Connection, string? key = null,
uint? methods = null, bool noMarker = false)
{
var placements = Fixture.DefaultPlacements;
var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200",
native ? DataConditionSourceKind.Native : DataConditionSourceKind.Scripted, placements.Select(p => p.Placement).ToArray(),
methods ?? (uint)(native ? DataConditionMethodSets.Native : DataConditionMethodSets.Scripted));
var state = new DataConditionState(key ?? Key1, version, false, true, info, active, acked, true, true, 0, 777, message,
StatusCodes.Good.Code, null, 0, time ?? DateTimeOffset.UtcNow, active || !acked, noMarker ? null : marker ?? Marker1);
return new ImportedConditionUpdate(connection, state, info, placements, "Plant/remote-a/" + placements[0].RelativePath);
}
/// <summary>Calls one method and returns its status (never throws for a Bad result).</summary>
private static async Task<StatusCode> CallAsync(ISession session, NodeId objectId, NodeId methodId, object eventId, string comment, CancellationToken ct)
{
var bytes = eventId switch { ByteString b => b, byte[] a => ByteString.From(a), _ => throw new ArgumentException(nameof(eventId)) };
var response = await session.CallAsync(null,
[new CallMethodRequest { ObjectId = objectId, MethodId = methodId, InputArguments = [new Variant(bytes), new Variant(new LocalizedText(comment))] }], ct);
var code = response.Results[0].StatusCode;
return StatusCode.IsGood(code) ? StatusCodes.Good : code;
}
private static async Task WaitUntilAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(15);
while (!condition())
{
if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 15 s");
await Task.Delay(10);
}
}
/// <summary>The fake origin port: a per-principal, per-method gate and a scriptable handler that records each dispatch.</summary>
internal sealed class FakePort : IProjectedConditionMethods
{
public HashSet<string> Granted { get; } = new(StringComparer.Ordinal);
public DataConditionMethods GrantedMethods { get; set; } = DataConditionMethodSets.All;
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5);
public ConcurrentQueue<(string Principal, DataConditionMethods Method)> AuthorizedFor { get; } = new();
public ConcurrentQueue<ImportedConditionMethodCall> Calls { get; } = new();
/// <summary>The gate throws (an unexpected fault BEFORE dispatch — review S1).</summary>
public bool AuthorizeThrows { get; set; }
public Func<ImportedConditionMethodCall, CancellationToken, Task<DataConditionMethodResult>> Handler { get; set; } =
(_, _) => Task.FromResult(Applied());
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
DataConditionMethods method)
{
AuthorizedFor.Enqueue((caller?.Principal ?? "", method));
if (AuthorizeThrows) throw new InvalidOperationException("gate fault");
return caller is not null && Granted.Contains(caller.Principal) && (GrantedMethods & method) == method
? new ImportedConditionMethodRoute(placements[0], Timeout) : null;
}
public Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken)
{
Calls.Enqueue(call);
return Handler(call, cancellationToken);
}
}
private sealed class Fixture
{
public required ServerEventRig Rig { get; init; }
public required FakePort Port { get; init; }
public string Identifier => ImportedConditionIds.Identifier(Connection, Key1);
public static IReadOnlyList<ImportedConditionPlacement> DefaultPlacements { get; } =
[
new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a", "dev1/HR200"),
];
public IReadOnlyList<ImportedConditionPlacement> Placements => DefaultPlacements;
public static Fixture Install(ServerEventRig rig)
{
var nm = rig.Nm;
nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw);
var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId;
var root = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant");
nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, root), parent,
"remote-a", "Plant/remote-a", MappingA, 1, () => true), out _).ShouldBeTrue();
var access = new ImportedConditionEventWireTests.FakeConditionAccess();
access.Allowed.Add(Granted);
nm.ProjectedConditionAccess = access;
var port = new FakePort();
port.Granted.Add(Granted);
nm.ProjectedConditionMethods = port;
return new Fixture { Rig = rig, Port = port };
}
public NodeId ConditionId(ISession session, string connection = Connection, string? key = null) =>
new(ImportedConditionIds.Identifier(connection, key ?? Key1), (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri));
public ByteString CurrentEventId(string connection = Connection, string? key = null) =>
Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.EventId!.Value;
public bool Acked(string connection = Connection, string? key = null) =>
Rig.Nm.FindImportedCondition(connection, key ?? Key1)!.AckedState!.Id!.Value;
public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]);
private static DataView View(string path) =>
new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path);
}
}
@@ -0,0 +1,206 @@
using System.Buffers.Binary;
using System.Net;
using System.Runtime.CompilerServices;
using Google.Protobuf;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// A3b review S5 (L3 on the REAL dispatch path): the consumer's method port is a real <see cref="ProjectedConditionAccess"/>
/// whose lease hands out a real <see cref="GrpcDataConnection"/>; the origin is an in-process gRPC endpoint (HTTP/2 framing
/// over an <see cref="HttpMessageHandler"/>) whose <c>CallConditionMethod</c> handler stalls for <see cref="Stall"/>. Only the
/// condition STREAM is a quiet stand-in (it opens, carries the Primary's provenance and never delivers) — the conditions
/// themselves are applied by the test, as in every other A3b wire test. The per-caller gate stays the test's fake (its own
/// tests are the Runtime gate tests); everything after it is production code.
/// </summary>
internal sealed class RealConditionMethodPath : IAsyncDisposable
{
public const string Incarnation = "boot-a";
private readonly IProjectedConditionMethods _gate;
private readonly DataConnectionManager _manager = new("consumer", 1);
private readonly GrpcDataConnection _grpc;
private readonly IDisposable? _demand;
public Origin Server { get; }
public ProjectedConditionAccess Access { get; }
public IProjectedConditionMethods Port { get; }
public RealConditionMethodPath(string connectionId, string mappingId, IProjectedConditionMethods gate, TimeSpan stall)
{
_gate = gate;
Server = new Origin(stall);
_manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { [connectionId] = new HashSet<string> { "consumer" } });
_grpc = new GrpcDataConnection(connectionId, new(DataTargetMode.Cluster, "c", null), [new Uri("https://origin.test")],
new Security(Server), _manager.Acquire(connectionId), 1 << 22, 1, eligibleNodeIds: new HashSet<string> { "origin" });
var mapping = new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = mappingId, DataConnectionId = connectionId, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe
| DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm,
MaxConditions = 10, ConditionStaleTimeoutMilliseconds = 60_000, ConditionSnapshotTimeoutMilliseconds = 60_000,
ConditionMethodTimeoutMilliseconds = 20_000, BranchName = mappingId, RemoteNamespaceUri = "https://zb.com/otopcua/raw",
RemoteIdentifierKind = "string", RemoteIdentifier = "Plant",
};
var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", "Plant"), DataRealm.Raw, mappingId, 1, "Plant/" + mappingId);
var scope = new NodeScope { ClusterId = "c1", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", mappingId] };
var placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority());
var state = new DataPlaneAuthorityState();
var policy = new DataOperationPolicy(state, new TriePermissionEvaluator(state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(new Mappings([placement]), new Connections(new Hybrid(_grpc)), policy, () => new NoSink(),
TimeProvider.System, new ProjectedConditionOptions(TimeSpan.FromSeconds(30), 122_500, long.MaxValue, TimeSpan.FromSeconds(1)),
NullLogger.Instance);
_demand = Access.AcquireEventDemand(null); // opens the condition stream (the serving incarnation calls are addressed to)
Port = new Adapter(this);
}
public async ValueTask DisposeAsync()
{
_demand?.Dispose();
Access.Dispose();
await _grpc.DisposeAsync();
_manager.Dispose();
}
private sealed class Adapter(RealConditionMethodPath owner) : IProjectedConditionMethods
{
public ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements,
DataConditionMethods method) => owner._gate.AuthorizeMethod(caller, placements, method);
public Task<DataConditionMethodResult> CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken) =>
owner.Access.CallAsync(call, cancellationToken);
}
/// <summary>The in-process origin: capabilities (Primary, conditions with every method) and a stalling method handler.</summary>
internal sealed class Origin(TimeSpan stall) : HttpMessageHandler
{
private static readonly DataLimits Limits = new(16, 16, 1 << 20, 16, 4, 1 << 20, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
private static readonly ServingIdentity Serving = new("origin", Incarnation, "Primary", 1, 1, 1);
public int MethodCalls;
public int MethodAnswers;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
var path = request.RequestUri!.AbsolutePath;
IMessage message;
if (path.EndsWith("/GetCapabilities", StringComparison.Ordinal))
{
var asked = request.Headers.Contains("x-otopcua-data-features");
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 5, Serving, DataReadiness.Ready,
DataOperationSets.V1 | (asked ? DataOperationSets.ConditionGrants : DataOperations.None),
new HashSet<DataValueKind> { DataValueKind.Double }, Limits, false, 0, "c", true, true, true, true, true,
Conditions: asked ? new DataConditionCapabilities(true, 7, 1000) : null));
}
else
{
Interlocked.Increment(ref MethodCalls);
var bytes = await request.Content!.ReadAsByteArrayAsync(token);
_ = W.ConditionMethodRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
await Task.Delay(stall, token); // the origin's handler stalls
Interlocked.Increment(ref MethodAnswers);
message = DataConditionProtoMapper.EncodeMethodResponse(new(DataWriteState.AcceptedUnconfirmed, 0, "AcceptedUnconfirmed", Serving));
}
var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5];
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5);
var ok = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
ok.Content.Headers.ContentType = new("application/grpc"); ok.TrailingHeaders.Add("grpc-status", "0");
return ok;
}
}
private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider
{
public event Action<string>? Changed { add { } remove { } }
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => new NonDisposing(handler)));
}
private sealed class NonDisposing(HttpMessageHandler inner) : HttpMessageHandler
{
private readonly HttpMessageInvoker _invoker = new(inner, disposeHandler: false);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
_invoker.SendAsync(request, cancellationToken);
}
private sealed class Mappings(IReadOnlyList<ProjectedMappingPlacement> current) : IProjectedConditionMappings
{
public IReadOnlyList<ProjectedMappingPlacement> Current { get; } = current;
public event Action? Changed { add { } remove { } }
}
private sealed class ActiveAuthority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
}
private sealed class Connections(IDataConnection connection) : IGrpcDataAdapterConnectionSource
{
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(connection));
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
/// <summary>The real gRPC connection for everything but the condition stream and root metadata (quiet stand-ins).</summary>
private sealed class Hybrid(GrpcDataConnection grpc) : IDataConnection, IDataPrimarySubscriptionSource, IDataConditionMethodService
{
public DataTarget Target => grpc.Target;
public TimeProvider Clock => grpc.Clock;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => grpc.GetCapabilitiesAsync(budget, cancellationToken);
public Task<DataBrowseBranch> BrowseAsync(Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) =>
grpc.BrowseAsync(request, cancellationToken);
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select(v => new DataItemResult<DataMetadata>("0", DataItemStatus.Good,
new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
DataOperations.Browse, 1, null, null, false), null)).ToArray());
public Task<IReadOnlyList<Core.Abstractions.DataConnections.ReadResult>> ReadAsync(Core.Abstractions.DataConnections.ReadRequest request,
CancellationToken cancellationToken) => grpc.ReadAsync(request, cancellationToken);
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => grpc.WriteAsync(request, cancellationToken);
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken) => Task.FromResult<IDataSubscription>(new QuietStream());
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken) => SubscribeAsync(cancellationToken);
public Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken) =>
grpc.CallConditionMethodAsync(request, cancellationToken);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
private sealed class QuietStream : IDataSubscription, IDataSubscriptionProvenance
{
private readonly CancellationTokenSource _closed = new();
public ServingIdentity Serving { get; } = new("origin", Incarnation, "Primary", 1, 1);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) => Task.CompletedTask;
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _closed.Token);
try { await Task.Delay(Timeout.Infinite, linked.Token); }
catch (OperationCanceledException) { }
yield break;
}
public ValueTask DisposeAsync() { _closed.Cancel(); return ValueTask.CompletedTask; }
}
private sealed class NoSink : IProjectedConditionSink
{
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates) { }
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys) { }
public void MarkConnectionStale(string connectionId) { }
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) { }
public void RequireRefresh(string connectionId) { }
}
}
@@ -0,0 +1,250 @@
using System.Security.Cryptography;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
/// <summary>
/// A3a (plan §5.2 N4, §5.4): an imported-condition id is classified BEFORE <c>RealmOf</c> on every authorizer entry point
/// (read, history, call, subscribe), whatever realm the caller computed; and the publish-time rewriter drops a marked
/// imported event whose re-check fails, and re-gates an unmarked one for the publishing session.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionClassifierTests : IAsyncDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-imported-classifier-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_condition_namespace_id_is_never_decided_by_the_realm_walk_on_any_authorizer_entry_point(bool aclEnabled)
{
var f = new Fixture(aclEnabled); // a Cluster-wide grant: the Raw/Uns walk would ALLOW everything
var conditionId = new NodeId("c1.anything", 9);
var calls = new List<(OpcUaOperation, NodeId)>();
f.Gate.ImportedConditionClassifier = (_, op, id) =>
{
if (id.NamespaceIndex != 9) return null;
calls.Add((op, id));
return false;
};
foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns })
{
foreach (var op in new[] { OpcUaOperation.Read, OpcUaOperation.Browse, OpcUaOperation.HistoryRead, OpcUaOperation.Call,
OpcUaOperation.CreateMonitoredItems, OpcUaOperation.AlarmAcknowledge })
{
f.Gate.Authorize(f.Identity, op, conditionId, realm).ShouldNotBeNull($"Authorize {op} {realm}");
f.Gate.AuthorizeIfRequired(f.Identity, op, conditionId, realm).ShouldNotBeNull($"AuthorizeIfRequired {op} {realm}");
f.Gate.IsAllowedCached(f.Identity, op, conditionId, realm).ShouldBeFalse($"IsAllowedCached {op} {realm}");
f.Gate.TryAuthorizeMapped(f.Identity, op, conditionId, realm, out var veto).ShouldBeTrue();
veto.ShouldNotBeNull();
}
}
calls.Count.ShouldBe(2 * 6 * 4, "every entry point asked the condition classifier, never the realm");
// Positive control: the same identity on an ordinary Raw id is decided by the grant walk (allowed).
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, new NodeId("Plant/x", 2), AddressSpaceRealm.Raw).ShouldBeNull();
}
[Fact]
public async Task The_node_manager_classifier_allows_Read_and_Subscribe_through_the_condition_and_refuses_history_and_calls()
{
var nm = await BootAsync();
var f = new Fixture(aclEnabled: true);
nm.Authorizer = f.Gate;
var access = new Access();
nm.ProjectedConditionAccess = access;
var key = Convert.ToBase64String(SHA256.HashData("k"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_');
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR");
var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR");
var state = new DataConditionState(key, 1, false, true, new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native,
[view], 3), true, false, true, true, 0, 500, "m", 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1));
nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, state.Info, [placement], "Plant/remote-a/dev1/HR")]);
var alarm = nm.FindImportedCondition("conn-a", key).ShouldNotBeNull();
nm.IsImportedConditionId(alarm.NodeId).ShouldBeTrue();
var child = alarm.ActiveState!.Id!.NodeId;
nm.IsImportedConditionId(child).ShouldBeTrue("children live in the condition's namespace (#629)");
foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns })
{
access.Visible = true;
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldBeNull();
f.Gate.Authorize(f.Identity, OpcUaOperation.CreateMonitoredItems, alarm.NodeId, realm).ShouldBeNull();
f.Gate.Authorize(f.Identity, OpcUaOperation.HistoryRead, alarm.NodeId, realm).ShouldNotBeNull("no imported condition history");
f.Gate.Authorize(f.Identity, OpcUaOperation.Call, alarm.NodeId, realm).ShouldNotBeNull("remote methods are A3b");
f.Gate.Authorize(f.Identity, OpcUaOperation.AlarmAcknowledge, alarm.NodeId, realm).ShouldNotBeNull();
access.Visible = false;
access.Generation++;
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldNotBeNull("not visible ⇒ denied despite the Cluster grant");
}
}
[Fact]
public void The_rewriter_drops_a_failed_marked_event_and_regates_an_unmarked_imported_one()
{
var keep = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => true)) { ClientHandle = 1 };
var drop = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 2 };
var unmarkedDenied = new EventFieldList { ClientHandle = 3 };
var unmarkedOther = new EventFieldList { ClientHandle = 4 };
var throwing = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => throw new InvalidOperationException())) { ClientHandle = 5 };
var message = new NotificationMessage
{
SequenceNumber = 7,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [keep, drop, unmarkedDenied, unmarkedOther, throwing] })],
};
var projected = ProjectedNotificationRewriter.Project(message, republish: false, list => list.ClientHandle == 3 ? false : null);
var events = projected.NotificationData[0].TryGetValue<EventNotificationList>(out var list) ? list! : throw new InvalidOperationException();
projected.NotificationData.Count.ShouldBe(1);
events.Events.ToArray()!.Select(e => e.ClientHandle).ShouldBe([1u, 4u]);
// Every denied event emptied ⇒ the payload is left out entirely (events have no Bad-value form).
var allDenied = new NotificationMessage { SequenceNumber = 8,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [drop] })] };
ProjectedNotificationRewriter.Project(allDenied, republish: true, null).NotificationData.Count.ShouldBe(0);
// No imported gate and no marker: v1 messages pass through as the same instance.
var plain = new NotificationMessage { SequenceNumber = 9, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [unmarkedOther] })] };
ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue();
}
/// <summary>
/// A3 review round 2 (root cause of the intermittent OI ConditionRefresh failures): SDK 2.0.1 pools EventFieldList
/// process-wide, and <c>SentMessageQueue</c> calls <c>Reuse()</c> on every list of an acknowledged message. A marked
/// list that went back to the stock pool was rented by an unrelated server/session's <c>GetEventFields</c> (its
/// RefreshStart/RefreshEnd), carrying a revoked marker, and the rewriter dropped it. A released marked list must never
/// be rentable, and must not keep its marker (closure over condition + identity) alive.
/// </summary>
[Fact]
public void A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker()
{
var marked = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 77 };
((IPooledEncodeable)marked).Reuse(); // exactly what SentMessageQueue.ReuseNotificationPayloads does on ACK / eviction
marked.Marker.ShouldBeNull("a released list holds no authority (and keeps no closure alive)");
// Drain more than the pool can hold: had the marked instance been returned, it would come out here.
var rented = new List<EventFieldList>();
try
{
for (var i = 0; i < PooledEncodeableType<EventFieldList>.DefaultMaximumRetained + 64; i++)
rented.Add((EventFieldList)EventFieldListActivator.Instance.CreateInstance());
rented.ShouldNotContain(l => l is ProjectedEventFieldList, "a stock list rented for any event is never a marked one");
}
finally
{
foreach (var l in rented) ((IPooledEncodeable)l).Reuse();
}
// A released marked list that somehow reached the rewriter fails closed (never judged by a stale marker).
var message = new NotificationMessage { SequenceNumber = 10,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0);
}
/// <summary>
/// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 <c>SentMessageQueue</c> hands Publish
/// and Republish a <c>CoreUtils.Clone</c> of the stored message. The gate holds only because
/// <see cref="EventFieldList.Clone"/> is <c>MemberwiseClone</c>, which keeps the subclass, the marker and the handle. Pins
/// that dependency: an SDK that cloned through the activator (a stock list) would turn this red.
/// </summary>
[Fact]
public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker()
{
var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false);
var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 };
var direct = marked.Clone().ShouldBeOfType<ProjectedEventFieldList>();
direct.Marker.ShouldBeSameAs(marker);
direct.ClientHandle.ShouldBe(42u);
var message = new NotificationMessage { SequenceNumber = 11,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish
delivered.NotificationData[0].TryGetValue<EventNotificationList>(out var list).ShouldBeTrue();
var events = list!.Events;
var cloned = events[0].ShouldBeOfType<ProjectedEventFieldList>();
cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance");
cloned.Marker.ShouldBeSameAs(marker);
ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count
.ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)");
}
[Fact]
public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL()
{
var registry = new ProjectedConditionRegistry();
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
var computes = 0;
bool Allow() { computes++; return true; }
var now = DateTimeOffset.UtcNow;
var expiringKey = new object();
registry.Verdict(expiringKey, condition, 1, now, now.AddSeconds(2), Allow).ShouldBeTrue();
registry.Verdict(expiringKey, condition, 1, now.AddSeconds(1), now.AddSeconds(2), Allow).ShouldBeTrue();
computes.ShouldBe(1, "served from cache inside both bounds");
registry.Verdict(expiringKey, condition, 1, now.AddSeconds(3), now.AddSeconds(2), () => { computes++; return false; })
.ShouldBeFalse("past the key's expiry the verdict is re-proved (and the policy now denies)");
var longLived = new object();
registry.Verdict(longLived, condition, 1, now, null, Allow).ShouldBeTrue();
registry.Verdict(longLived, condition, 1, now + ProjectedConditionRegistry.PositiveVerdictTtl + TimeSpan.FromSeconds(1), null, Allow);
computes.ShouldBe(4, "a positive verdict lives at most the TTL");
}
private async Task<OtOpcUaNodeManager> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ImportedClassifier", ApplicationUri = $"urn:ImportedClassifier:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
_host = started.Host;
return started.Server.NodeManager!;
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pki))
try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
private sealed class Access : IProjectedConditionAccess
{
public bool Visible { get; set; }
public long Generation { get; set; } = 1;
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) => caller is not null && Visible;
public long AuthorityGeneration => Generation;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null;
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible;
public bool IsConditionBearingMapping(string mappingId) => true;
}
private sealed class Fixture
{
private readonly DataPlaneAuthorityState _state = new();
private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1) };
public DataPlaneAuthorizer Gate { get; }
public Fixture(bool aclEnabled)
{
_state.Apply("c1", "rev", [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.Cluster,
PermissionFlags = (NodePermissions)~0 }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), aclEnabled,
NullLogger.Instance, TimeProvider.System);
}
public RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", _key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
}
}
@@ -97,14 +97,51 @@ public sealed class GrpcDataConditionMethodClientTests
a.MethodCalls.ShouldBe(1);
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null)
[Fact]
public async Task Without_a_connection_ceiling_the_deadline_is_the_requests_budget_not_a_hidden_5s()
{
// A3b review S2: the per-mapping timeout rides RemainingBudget; a 30 s mapping must not be cut at a client-wide 5 s.
var a = new Endpoint("a");
await using var connection = Connect([a], methodTimeout: null, setCeiling: false);
(await connection.CallConditionMethodAsync(Request(budget: TimeSpan.FromSeconds(8)), Ct)).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
a.LastTimeout.ShouldNotBeNull().ShouldBeGreaterThan(TimeSpan.FromSeconds(6));
TimeSpan.FromTicks(a.LastRequest!.RemainingBudgetTicks).ShouldBeGreaterThan(TimeSpan.FromSeconds(6));
}
[Fact]
public async Task A_deadline_passing_after_send_is_OutcomeUnknown_with_BadTimeout_known_not_inferred()
{
var a = new Endpoint("a") { Hang = true };
await using var connection = Connect([a]);
var result = await connection.CallConditionMethodAsync(Request(budget: TimeSpan.FromMilliseconds(400)), Ct);
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
result.StatusCode.ShouldBe(0x800A0000u, "BadTimeout: the transport knows the deadline passed");
a.MethodCalls.ShouldBe(1);
}
[Fact]
public async Task An_invalid_request_is_RejectedBeforeDispatch_never_thrown()
{
var a = new Endpoint("a");
await using var connection = Connect([a]);
var result = await connection.CallConditionMethodAsync(Request() with { OperationId = new string('x', 10_000) }, Ct);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(0x80AB0000u);
a.MethodCalls.ShouldBe(0);
}
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null, bool setCeiling = true)
{
var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
var router = new Router(endpoints);
return new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), endpoints.Select(e => new Uri($"https://{e.Name}.test")),
new Security(router), manager.Acquire("link"), 1 << 22, endpoints.Length,
eligibleNodeIds: endpoints.Select(e => e.Name).ToHashSet()) { ConditionMethodTimeout = methodTimeout ?? TimeSpan.FromSeconds(5) };
var uris = endpoints.Select(e => new Uri($"https://{e.Name}.test")).ToArray();
var eligible = endpoints.Select(e => e.Name).ToHashSet();
return setCeiling
? new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), uris, new Security(router), manager.Acquire("link"), 1 << 22,
endpoints.Length, eligibleNodeIds: eligible) { ConditionMethodTimeout = methodTimeout ?? TimeSpan.FromSeconds(5) }
: new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), uris, new Security(router), manager.Acquire("link"), 1 << 22,
endpoints.Length, eligibleNodeIds: eligible);
}
private sealed class Endpoint(string name)
@@ -0,0 +1,736 @@
using System.Security.Cryptography;
using System.Threading.Channels;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// A3a (plan §5.4, §5.5): the consumer condition runtime over a scripted origin stream — the per-mapping capacity
/// decision before anything is materialised (and the item removed), the snapshot barrier, the host caps, 2,000 conditions
/// without <c>MaxProjectionNodes</c>, the version rule (removal bypasses it and forgets the version), the lifetime rule (a
/// stream end re-snapshots and never removes; only a complete re-snapshot does), staleness, the mapping gate with a real
/// <see cref="DataOperationPolicy"/>, primary placement from deployed config, and demand with linger.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class GrpcDataProjectedConditionAccessTests
{
private const string Connection = "conn-a";
[Fact]
public async Task A_total_over_MaxConditions_is_ConditionCapacity_and_its_item_removed_before_materialising_other_mappings_unaffected()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", total: 2);
stream.Records("map-b", Record(Key("x"), 3), Record(Key("y"), 3));
stream.Begin("map-a", total: 3);
// Positive control: the removal is the must-arrive effect of the LAST frame, so every earlier frame was processed.
await f.WaitAsync(() => stream.Removed.Count == 1);
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the over-limit item is removed, not held open");
f.Sink.Applied.ShouldBeEmpty("nothing is materialised before the barrier");
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 2);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Access.MappingStatuses(Connection)!["map-b"].ShouldBe(ProjectedConditionMappingStatus.Complete);
f.Sink.Applied.ShouldAllBe(u => u.Placements.All(p => p.MappingId == "map-b"));
}
[Fact]
public async Task Two_thousand_conditions_in_one_mapping_materialise_without_MaxProjectionNodes_and_the_host_cap_rejects_before_materialising()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 5000));
f.Mappings.Current[0].Mapping.MaxProjectionNodes = 10;
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 2000);
stream.Records("map-a", Enumerable.Range(0, 2000).Select(i => Record(Key("k" + i), 3)).ToArray());
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Applied.Count == 2000);
f.Sink.Applied.Select(u => u.State.ConditionKey).Distinct().Count().ShouldBe(2000);
f.Mappings.Current[0].Mapping.MaxProjectionNodes.ShouldBe(10, "conditions have their own budget");
// Host cap: 1,999 conditions' worth of nodes ⇒ the 2,000-condition mapping is rejected at begin.
await using var capped = new Fixture(new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 1999 * 49, long.MaxValue,
TimeSpan.FromMilliseconds(50)), ("map-a", DataRealm.Raw, 5000));
using var cappedDemand = capped.Access.AcquireEventDemand(null);
var cappedStream = await capped.NextStreamAsync();
cappedStream.Ack();
cappedStream.Begin("map-a", total: 2000);
await capped.WaitAsync(() => cappedStream.Removed.Count == 1 && capped.Access.BarriersCompleted(Connection) == 1);
capped.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
capped.Sink.Applied.ShouldBeEmpty("the barrier (the positive control) passed with nothing to materialise");
}
[Fact]
public async Task Versions_gate_per_key_but_a_removal_bypasses_the_gate_and_forgets_the_version()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 1);
stream.Records("map-a", Record(Key("x"), 5));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
stream.Records("map-a", Record(Key("x"), 4, message: "stale")); // older ⇒ dropped
stream.Records("map-a", Record(Key("x"), 5, removed: true)); // removal at the hub watermark (= an applied version)
await f.WaitAsync(() => f.Sink.Removed.Count == 1);
f.Sink.Applied.ShouldNotContain(u => u.State.Message == "stale");
stream.Records("map-a", Record(Key("x"), 3, message: "re-added")); // the version was forgotten
await f.WaitAsync(() => f.Sink.Applied.Any(u => u.State.Message == "re-added"));
}
[Fact]
public async Task A_stream_end_re_snapshots_without_removing_and_only_a_complete_re_snapshot_removes_staleness_in_between()
{
// map-b (MaxConditions 0) is the positive control: its begin is refused, which must arrive as an item removal.
await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 0));
using var demand = f.Access.AcquireEventDemand(null);
var first = await f.NextStreamAsync();
first.Ack();
first.Begin("map-b", total: 1);
first.Begin("map-a", total: 2);
first.Records("map-a", Record(Key("x"), 3), Record(Key("y"), 3));
first.Complete("map-a");
await f.WaitAsync(() => f.Sink.Applied.Count == 2);
first.End(); // an origin deploy ends the stream (A2 S1)
var second = await f.NextStreamAsync();
await f.WaitAsync(() => f.Sink.Stale.Count >= 1); // stale timeout (100 ms) passes before the new snapshot completes
f.Sink.Removed.ShouldBeEmpty("a stream end is never 'conditions removed'");
second.Ack();
second.Begin("map-a", total: 1);
second.Records("map-a", Record(Key("x"), 9));
second.Begin("map-b", total: 1);
await f.WaitAsync(() => second.Removed.Count == 1); // positive control: every earlier frame was processed
f.Sink.Removed.ShouldBeEmpty("an incomplete snapshot removes nothing");
second.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Count == 1);
f.Sink.Removed.Single().ShouldBe(Key("y"));
f.Access.BarriersCompleted(Connection).ShouldBe(2, "one barrier per stream: the first snapshot and the re-snapshot");
}
[Fact]
public async Task A_mapping_whose_snapshot_times_out_is_Unavailable_the_rest_proceed_and_RefreshRequired_follows()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
f.Mappings.Current[0].Mapping.ConditionSnapshotTimeoutMilliseconds = 300;
f.Mappings.Current[1].Mapping.ConditionSnapshotTimeoutMilliseconds = 300;
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
f.Sink.RefreshRequired.ShouldBe(1);
}
[Fact]
public async Task The_primary_placement_comes_from_deployed_config_Raw_first_then_mapping_id_and_SourceName_follows_it()
{
await using var f = new Fixture(("map-u", DataRealm.Uns, 10), ("map-z", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
// Stream order deliberately the reverse of the deployed order.
foreach (var mapping in new[] { "map-u", "map-z", "map-b" })
{
stream.Begin(mapping, total: 1);
stream.Records(mapping, Record(Key("x"), 3, placement: mapping == "map-u" ? f.UnsPlacement : f.RawPlacement));
stream.Complete(mapping);
}
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
var update = f.Sink.Applied.Single();
update.Placements.Select(p => p.MappingId).ShouldBe(["map-b", "map-z", "map-u"]);
update.SourceName.ShouldBe("Plant/map-b/dev1/HR200", "the primary mapping's branch path + the address below the remote root");
update.Placements[0].FolderLocalSubject.ShouldBe("Plant/map-b/dev1");
}
[Fact]
public async Task The_gate_is_the_mapping_Subscribe_grant_on_the_placement_folder_and_needs_the_condition_bits()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, f.RawPlacement, "Plant/map-a/dev1", "dev1/HR200");
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe);
f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeTrue();
f.Access.CanSee(f.Identity("someone-else"), [placement]).ShouldBeFalse();
f.Access.CanSee(null, [placement]).ShouldBeFalse();
f.Grant(NodePermissions.Browse);
f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("Subscribe is the visibility permission (not AlarmRead)");
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe);
f.Mappings.Current[0].Mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe;
f.Access.CanSee(f.Identity("reader"), [placement]).ShouldBeFalse("a mapping without AlarmSubscribe carries no conditions");
}
[Fact]
public async Task Demand_opens_the_stream_and_the_linger_closes_it_and_removes_what_it_materialised()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
f.Access.IsRunning(Connection).ShouldBeFalse();
var demand = f.Access.AcquireEventDemand(null)!;
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 1);
stream.Records("map-a", Record(Key("x"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
demand.Dispose();
f.Access.IsRunning(Connection).ShouldBeTrue("the linger keeps it open");
await f.WaitAsync(() => !f.Access.IsRunning(Connection) && f.Sink.Removed.Count == 1);
}
// ---------------------------------------------------------------------------------------------------------------------
// Review round 1 (a3a-review-round1.md)
// ---------------------------------------------------------------------------------------------------------------------
private static async Task<FakeStream> CompleteFirstAsync(Fixture f, params (string Mapping, DataConditionState[] Records)[] snapshots)
{
var stream = await f.NextStreamAsync();
stream.Ack();
foreach (var (mapping, records) in snapshots)
{
stream.Begin(mapping, records.Length);
stream.SnapshotRecords(mapping, records);
stream.Complete(mapping);
}
await f.WaitAsync(() => f.Access.BarriersCompleted(Connection) >= 1);
return stream;
}
[Fact]
public async Task B1_an_in_stream_multi_frame_re_snapshot_keeps_every_condition_until_complete_then_removes_only_what_it_dropped()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3), Record(Key("z"), 3)]), ("map-b", []));
await f.WaitAsync(() => f.Sink.Live.Count == 3);
// A2 re-snapshots inside a live stream (hub reader reset, retaken incomplete apply): begin, record frames, complete.
stream.Begin("map-a", total: 2);
stream.SnapshotRecords("map-a", Record(Key("x"), 4));
stream.SnapshotRecords("map-a", Record(Key("y"), 4));
stream.Records("map-b", Record(Key("ctl"), 1)); // positive control: a delta on the other mapping must be applied
await f.WaitAsync(() => f.Sink.Live.Contains(Key("ctl")));
f.Sink.Removed.ShouldBeEmpty("a re-snapshot in progress removes nothing (B1)");
f.Sink.Live.ShouldContain(Key("z"));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Count == 1);
f.Sink.Removed.Single().ShouldBe(Key("z"), "only the key the COMPLETE re-snapshot no longer lists is removed");
f.Sink.Live.ShouldBe([Key("x"), Key("y"), Key("ctl")], ignoreOrder: true);
}
[Fact]
public async Task B1_an_in_stream_re_snapshot_over_capacity_removes_the_mapping_once_keeps_keys_another_mapping_lists_and_requires_refresh()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 2), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3), Record(Key("y"), 3)]), ("map-b", [Record(Key("y"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 2);
var refreshes = f.Sink.RefreshRequired;
stream.Begin("map-a", total: 3); // the origin now lists more than MaxConditions
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Count == 1);
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"));
f.Sink.Removed.Single().ShouldBe(Key("x"), "y is still listed by map-b");
f.Sink.Live.ShouldBe([Key("y")]);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.RefreshRequired.ShouldBeGreaterThan(refreshes, "clients are told the removal happened (§5.2)");
}
private static Fixture TimedFixture(int timeoutMs, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
{
var f = new Fixture(mappings);
foreach (var m in f.Mappings.Current) m.Mapping.ConditionSnapshotTimeoutMilliseconds = timeoutMs;
return f;
}
[Fact]
public async Task B2_a_snapshot_completing_after_the_timeout_is_merged_late_and_the_stream_is_kept()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
stream.Begin("map-a", total: 1); // 2,000 conditions arriving 1 s late, in miniature
stream.SnapshotRecords("map-a", Record(Key("w"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("w")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Complete);
(await f.TryNextStreamAsync(TimeSpan.FromMilliseconds(900))).ShouldBeNull("a late completion cancels the retry");
}
[Fact]
public async Task B2_an_incomplete_barrier_marks_the_incomplete_mappings_materialised_keys_BadNoCommunication_never_removed()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var first = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]), ("map-b", [Record(Key("y"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 2);
first.End();
var second = await f.NextStreamAsync();
second.Ack();
second.Begin("map-b", total: 1);
second.SnapshotRecords("map-b", Record(Key("y"), 4));
second.Complete("map-b"); // map-a never answers: the barrier passes at the timeout
await f.WaitAsync(() => f.Sink.StaleKeys.Contains(Key("x")));
f.Sink.Removed.ShouldBeEmpty("unknown is not gone");
f.Sink.StaleKeys.ShouldNotContain(Key("y"));
f.Sink.RefreshRequired.ShouldBeGreaterThanOrEqualTo(1);
}
[Fact]
public async Task B2_S7_a_refused_item_is_an_incomplete_barrier_RefreshRequired_and_the_stream_is_retried_after_a_bounded_wait()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack(refused: "map-a"); // e.g. a Secondary that advertises but refuses (A2 N7)
stream.Begin("map-b", total: 1);
stream.Records("map-b", Record(Key("x"), 3));
stream.Complete("map-b");
await f.WaitAsync(() => f.Sink.Applied.Count == 1);
f.Sink.RefreshRequired.ShouldBe(1, "S7: an incomplete barrier from a non-Good ack also requires refresh");
(await f.TryNextStreamAsync(TimeSpan.FromSeconds(5))).ShouldNotBeNull("B2: an Unavailable mapping ends the stream; a new one retries it");
}
[Fact]
public async Task Deviation9_a_condition_stream_served_by_a_Secondary_is_dropped_and_reopened_on_the_Primary()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
f.Connections.Roles.Enqueue("Secondary");
using var demand = f.Access.AcquireEventDemand(null);
var secondary = await f.NextStreamAsync();
var primary = await f.NextStreamAsync();
secondary.Disposed.ShouldBeTrue("never opened items on a Secondary");
f.Connections.PrimarySubscribes.ShouldBeGreaterThanOrEqualTo(2, "the Primary-only open is asked for");
primary.Ack();
primary.Begin("map-a", 1);
primary.SnapshotRecords("map-a", Record(Key("x"), 3));
primary.Complete("map-a");
await f.WaitAsync(() => f.Sink.Live.Contains(Key("x")));
}
[Fact]
public async Task S6_a_root_whose_metadata_fails_is_Unavailable_and_its_item_is_not_opened()
{
await using var f = TimedFixture(300, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
f.Connections.MetadataFails.Add(0);
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Mappings.ShouldBe(["map-b"]);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.Unavailable);
}
[Fact]
public async Task B4_the_host_caps_are_node_wide_across_connections()
{
var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50));
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10, "conn-a"), ("map-b", DataRealm.Raw, 10, "conn-b"));
using var demand = f.Access.AcquireEventDemand(null);
var streams = new[] { await f.NextStreamAsync(), await f.NextStreamAsync() };
foreach (var stream in streams)
{
var mapping = stream.Mappings.Single();
stream.Ack();
stream.Begin(mapping, 2);
stream.SnapshotRecords(mapping, Record(Key(mapping + "1"), 3), Record(Key(mapping + "2"), 3));
stream.Complete(mapping);
}
await f.WaitAsync(() => f.Access.BarriersCompleted("conn-a") == 1 && f.Access.BarriersCompleted("conn-b") == 1);
streams.Sum(x => x.Removed.Count).ShouldBe(1, "two connections of 2 cannot both fit a 3-condition node cap");
f.Sink.Live.Count.ShouldBe(2);
f.Access.ChargedConditions.ShouldBeLessThanOrEqualTo(3);
}
[Fact]
public async Task B4_admission_is_order_independent_a_later_ordered_begin_arriving_first_still_counts()
{
var options = new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 3 * 49, long.MaxValue, TimeSpan.FromMilliseconds(50));
await using var f = new Fixture(options, ("map-a", DataRealm.Raw, 10), ("map-b", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-b", 2);
stream.Begin("map-a", 2);
await f.WaitAsync(() => stream.Removed.Count == 1);
stream.Removed.Single().ShouldBe(stream.HandleOf("map-a"), "the second begin is decided against the first one's claim");
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
}
[Fact]
public async Task B4_records_past_the_snapshot_total_reset_the_mapping_to_ConditionCapacity_before_materialising()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 100));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", total: 1);
stream.SnapshotRecords("map-a", Enumerable.Range(0, 50).Select(i => Record(Key("k" + i), 3)).ToArray());
stream.Complete("map-a");
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Access.BarriersCompleted(Connection) == 1);
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.Applied.ShouldBeEmpty("an origin claiming total 1 cannot materialise 50 (the barrier is the positive control)");
f.Access.ChargedConditions.ShouldBe(0);
}
[Fact]
public async Task B4_post_snapshot_delta_growth_past_MaxConditions_resets_the_mapping_and_removes_its_conditions()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 2));
using var demand = f.Access.AcquireEventDemand(null);
var stream = await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
stream.Records("map-a", Record(Key("y"), 3), Record(Key("z"), 3));
await f.WaitAsync(() => stream.Removed.Count == 1 && f.Sink.Removed.Contains(Key("x")));
f.Access.MappingStatuses(Connection)!["map-a"].ShouldBe(ProjectedConditionMappingStatus.ConditionCapacity);
f.Sink.Live.ShouldBeEmpty();
}
[Fact]
public async Task S2_an_authority_deactivation_moves_the_authority_generation_so_cached_verdicts_are_re_proved()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var before = f.Access.AuthorityGeneration;
((ActiveAuthority)f.Mappings.Current[0].Authority).Active = false; // no deploy, no epoch change
f.Access.AuthorityGeneration.ShouldNotBe(before);
}
[Fact]
public async Task S3_a_new_runner_waits_for_the_old_runners_removal_so_a_re_materialised_key_survives()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null)!;
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
f.Sink.RemovalGate = gate; // hold the old runner's removal open
demand.Dispose();
await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired; its removal is now blocked in the sink
using var again = f.Access.AcquireEventDemand(null);
_ = Task.Delay(400, TestContext.Current.CancellationToken).ContinueWith(_ => gate.TrySetResult(), TaskScheduler.Default);
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", 1);
stream.SnapshotRecords("map-a", Record(Key("x"), 4));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Count == 1 && f.Sink.Applied.Count == 2);
f.Sink.Live.ShouldContain(Key("x"), "the old runner's removal must not land after the new runner materialised the key");
}
[Fact]
public async Task S4_a_mapping_change_hands_the_materialised_set_over_after_the_old_loop_stopped()
{
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
using var demand = f.Access.AcquireEventDemand(null);
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
await f.WaitAsync(() => f.Sink.Live.Count == 1);
f.Mappings.Current[0].Mapping.MaxConditions = 11; // a changed signature ⇒ a new runner, a new stream
f.Mappings.Raise();
var stream = await f.NextStreamAsync();
stream.Ack();
stream.Begin("map-a", 1);
stream.SnapshotRecords("map-a", Record(Key("y"), 3));
stream.Complete("map-a");
await f.WaitAsync(() => f.Sink.Removed.Contains(Key("x")));
f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it");
}
[Fact]
public async Task N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable()
{
// Verification review r2 N1: each runner kept its predecessor (and that one's record sets), so every linger expiry
// + re-subscribe or mapping change added a link R3 → R2 → R1 and memory grew without bound.
await using var f = new Fixture(("map-a", DataRealm.Raw, 10));
var demand = f.Access.AcquireEventDemand(null)!;
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)]));
var first = f.Access.RunnerReference(Connection)!;
var version = 3L;
for (var cycle = 0; cycle < 3; cycle++)
{
demand.Dispose();
await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired
demand = f.Access.AcquireEventDemand(null)!;
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)]));
}
for (var change = 0; change < 2; change++)
{
f.Mappings.Current[0].Mapping.MaxConditions++; // a changed signature ⇒ a new runner, a new stream
f.Mappings.Raise();
await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)]));
}
f.Sink.Live.ShouldBe([Key("x")], "the hand-over still works across every cycle");
for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); }
first.IsAlive.ShouldBeFalse("the current runner must not keep a chain of predecessors reachable");
demand.Dispose();
}
// ---------------------------------------------------------------------------------------------------------------------
internal static string Key(string seed) =>
Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_');
private static DataConditionState Record(string key, long version, bool removed = false, string message = "high", DataView? placement = null)
{
var info = removed ? null : new DataConditionInfo("AlarmConditionType", "HR200", DataConditionSourceKind.Native,
[placement ?? Fixture.DefaultRawPlacement], 3);
return new DataConditionState(key, version, removed, !removed, info, true, false, true, true, 0, 500, message, 0, null, 0,
DateTimeOffset.UtcNow, true, new DataActivationMarker("inc", 1));
}
private sealed class Fixture : IAsyncDisposable
{
internal static readonly DataView DefaultRawPlacement =
new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"), DataRealm.Raw, null, 0, "Plant/dev1/HR200");
public DataView RawPlacement => DefaultRawPlacement;
public DataView UnsPlacement { get; } =
new(new DataAddress("origin", "https://zb.com/otopcua/uns", "string", "Area/Line/Filler/HR200"), DataRealm.Uns, null, 0, "Area/Line/Filler/HR200");
private readonly DataPlaneAuthorityState _state = new();
private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1) };
public FakeMappings Mappings { get; }
public FakeSink Sink { get; } = new();
public FakeConnections Connections { get; } = new();
public ProjectedConditionAccess Access { get; }
public Fixture(params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
: this(DefaultOptions, mappings) { }
public static ProjectedConditionOptions DefaultOptions =>
new(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50));
public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions)[] mappings)
: this(options, mappings.Select(m => (m.Id, m.Realm, m.MaxConditions, Connection)).ToArray()) { }
public Fixture(ProjectedConditionOptions options, params (string Id, DataRealm Realm, int MaxConditions, string Connection)[] mappings)
{
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
Mappings = new FakeMappings(mappings.Select(m => Placement(m.Id, m.Realm, m.MaxConditions, m.Connection)).ToList());
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(Mappings, Connections, policy, () => Sink, TimeProvider.System, options, NullLogger.Instance);
}
public void Grant(NodePermissions permissions) =>
_state.Apply("c1", "rev-" + (int)permissions, [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = permissions }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal,
_key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
private static ProjectedMappingPlacement Placement(string id, DataRealm realm, int maxConditions, string connection)
{
var mapping = new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = id, DataConnectionId = connection, Enabled = true, Realm = realm, RemoteRealm = realm,
AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe, MaxConditions = maxConditions,
ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000, BranchName = id,
RemoteNamespaceUri = realm == DataRealm.Raw ? "https://zb.com/otopcua/raw" : "https://zb.com/otopcua/uns",
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "Plant" : "Area",
};
var segments = new[] { "Plant", id };
var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), realm, id, 1,
string.Join('/', segments));
var scope = new NodeScope { ClusterId = "c1", Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = segments };
return new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority());
}
public async Task<FakeStream> NextStreamAsync() => await Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
/// <summary>The next stream within <paramref name="within"/>, or null.</summary>
public async Task<FakeStream?> TryNextStreamAsync(TimeSpan within)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
cts.CancelAfter(within);
try { return await Connections.Streams.Reader.ReadAsync(cts.Token); }
catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested) { return null; }
}
public async Task WaitAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition())
{
if (DateTime.UtcNow > deadline) condition().ShouldBeTrue("condition not met within 10 s");
await Task.Delay(20, TestContext.Current.CancellationToken);
}
}
public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; }
}
private sealed class ActiveAuthority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool Active { get; set; } = true;
public bool IsActive => Active;
}
internal sealed class FakeMappings(List<ProjectedMappingPlacement> current) : IProjectedConditionMappings
{
public IReadOnlyList<ProjectedMappingPlacement> Current { get; } = current;
public event Action? Changed;
public void Raise() => Changed?.Invoke();
}
internal sealed class FakeSink : IProjectedConditionSink
{
private readonly object _gate = new();
private readonly List<ImportedConditionUpdate> _applied = [];
private readonly List<string> _removed = [];
private readonly List<string> _stale = [];
private readonly List<string> _staleKeys = [];
private readonly HashSet<string> _live = new(StringComparer.Ordinal);
private int _refresh;
public IReadOnlyList<ImportedConditionUpdate> Applied { get { lock (_gate) return _applied.ToList(); } }
public IReadOnlyList<string> Removed { get { lock (_gate) return _removed.ToList(); } }
public IReadOnlyList<string> Stale { get { lock (_gate) return _stale.ToList(); } }
public IReadOnlyList<string> StaleKeys { get { lock (_gate) return _staleKeys.ToList(); } }
/// <summary>The keys the sink holds right now (applied minus removed).</summary>
public IReadOnlyCollection<string> Live { get { lock (_gate) return _live.ToList(); } }
public int RefreshRequired => Volatile.Read(ref _refresh);
/// <summary>When set, a removal blocks until released (the S3 race window, held open).</summary>
public TaskCompletionSource? RemovalGate { get; set; }
public void ApplyConditions(IReadOnlyList<ImportedConditionUpdate> updates)
{
lock (_gate) { _applied.AddRange(updates); foreach (var u in updates) _live.Add(u.State.ConditionKey); }
}
public void RemoveConditions(string connectionId, IReadOnlyCollection<string> conditionKeys)
{
RemovalGate?.Task.Wait(TimeSpan.FromSeconds(10));
lock (_gate) { _removed.AddRange(conditionKeys); foreach (var k in conditionKeys) _live.Remove(k); }
}
public void MarkConnectionStale(string connectionId) { lock (_gate) _stale.Add(connectionId); }
public void MarkConditionsStale(string connectionId, IReadOnlyCollection<string> conditionKeys) { lock (_gate) _staleKeys.AddRange(conditionKeys); }
public void RequireRefresh(string connectionId) => Interlocked.Increment(ref _refresh);
}
internal sealed class FakeConnections : IGrpcDataAdapterConnectionSource
{
public Channel<FakeStream> Streams { get; } = Channel.CreateUnbounded<FakeStream>();
/// <summary>Metadata answers Bad for these root indexes (deployed order).</summary>
public HashSet<int> MetadataFails { get; } = [];
/// <summary>The serving roles of the next streams (Primary when empty).</summary>
public Queue<string> Roles { get; } = new();
public int PrimarySubscribes;
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken) =>
ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(new FakeConnection(this)));
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataPrimarySubscriptionSource
{
public Task<IDataSubscription> SubscribePrimaryAsync(CancellationToken cancellationToken)
{
Interlocked.Increment(ref owner.PrimarySubscribes);
return SubscribeAsync(cancellationToken);
}
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null);
public TimeProvider Clock => TimeProvider.System;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) =>
Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((v, i) => owner.MetadataFails.Contains(i)
? new DataItemResult<DataMetadata>("0", DataItemStatus.Unavailable, null, null)
: new DataItemResult<DataMetadata>("0", DataItemStatus.Good, new DataMetadata(v with { Subject = v.Address.Identifier }, v.Address.Identifier, "Folder", DataValueKind.Null, -1, [], false,
DataOperations.Browse, 1, null, null, false), null)).ToArray());
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
string role;
lock (owner.Roles) role = owner.Roles.TryDequeue(out var next) ? next : "Primary";
var stream = new FakeStream(role);
owner.Streams.Writer.TryWrite(stream);
return Task.FromResult<IDataSubscription>(stream);
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
internal sealed class FakeStream(string role = "Primary") : IDataSubscription, IDataSubscriptionProvenance
{
public ServingIdentity Serving { get; } = new("origin-1", "inc-1", role, 1, 1);
public bool Disposed { get; private set; }
/// <summary>The mapping ids this stream opened items for.</summary>
public IReadOnlyList<string> Mappings => Open.Items.Select(x => x.ClientItemId).ToArray();
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
private readonly TaskCompletionSource<OpenSubscription> _open = new(TaskCreationOptions.RunContinuationsAsynchronously);
private long _sequence;
public List<DataItemHandle> Removed { get; } = [];
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open) _open.TrySetResult(open);
if (command is RemoveSubscriptionItems remove) lock (Removed) Removed.AddRange(remove.Items);
return Task.CompletedTask;
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public ValueTask DisposeAsync() { Disposed = true; _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
private OpenSubscription Open => _open.Task.Wait(TimeSpan.FromSeconds(10)) ? _open.Task.Result : throw new TimeoutException("no open");
public DataItemHandle HandleOf(string mapping)
{
var index = Open.Items.Select((x, i) => (x, i)).Single(x => x.x.ClientItemId == mapping).i;
return new DataItemHandle(Open.SubscriptionId, Open.StreamEpoch, (ulong)(index + 1), 1);
}
public void Ack(params string[] refused) => _frames.Writer.TryWrite(new DataSubscriptionAck(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, "open",
Open.Items.Select(x => refused.Contains(x.ClientItemId)
? new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Unavailable, null, x.Settings, "secondary")
: new DataSubscriptionItemAck(x.ClientItemId, DataItemStatus.Good, HandleOf(x.ClientItemId), x.Settings, null)).ToArray()));
/// <summary>Snapshot record frames exactly as the A2 origin frames them (is_snapshot, no total).</summary>
public void SnapshotRecords(string mapping, params DataConditionState[] records)
{
foreach (var chunk in records.Chunk(128)) Frame(mapping, true, null, chunk, false);
}
public void Begin(string mapping, int total) => Frame(mapping, true, total, [], false);
public void Records(string mapping, params DataConditionState[] records)
{
foreach (var chunk in records.Chunk(128)) Frame(mapping, false, null, chunk, false);
}
public void Complete(string mapping) => Frame(mapping, true, null, [], true);
public void End() => _frames.Writer.TryComplete();
private void Frame(string mapping, bool snapshot, int? total, IReadOnlyList<DataConditionState> items, bool complete) =>
_frames.Writer.TryWrite(new DataSubscriptionConditions(Open.SubscriptionId, Open.StreamEpoch, ++_sequence, HandleOf(mapping), snapshot,
total, items, complete));
}
}
@@ -0,0 +1,316 @@
using System.Threading.Channels;
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using BrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest;
using ReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest;
using ReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// A3b (plan §5.6): the consumer condition runtime's method port — the per-LOCAL-caller gate with a real
/// <see cref="DataOperationPolicy"/> (AlarmAcknowledge ⇒ Acknowledge/AddComment, AlarmConfirm ⇒ Confirm, the mapping's own
/// bit, the mapping's <c>ConditionMethodTimeoutMilliseconds</c>), and dispatch: addressed with the serving incarnation of the
/// condition stream the records arrive on; no open stream (connection down) ⇒ <c>BadNoCommunication</c>, nothing sent.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class GrpcDataProjectedConditionMethodTests
{
private const string Connection = "conn-a";
private const uint BadNoCommunication = 0x80310000u;
private static readonly ServingIdentity Serving = new("origin-1", "serving-inc-7", "Primary", 1, 1);
[Fact]
public async Task The_method_gate_is_the_local_callers_alarm_grant_on_the_placement_folder_and_the_mappings_own_bit()
{
await using var f = new Fixture();
var placement = f.Placement();
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge);
var route = f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Acknowledge);
route.ShouldNotBeNull();
route.Placement.ShouldBe(placement);
route.Timeout.ShouldBe(TimeSpan.FromMilliseconds(4321), "the mapping's ConditionMethodTimeoutMilliseconds");
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.AddComment).ShouldNotBeNull();
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm).ShouldBeNull("AlarmAcknowledge is not AlarmConfirm");
f.Access.AuthorizeMethod(f.Identity("someone-else"), [placement], DataConditionMethods.Acknowledge).ShouldBeNull("per local caller");
f.Access.AuthorizeMethod(null, [placement], DataConditionMethods.Acknowledge).ShouldBeNull();
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe);
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Acknowledge)
.ShouldBeNull("seeing a condition (Subscribe) does not authorize acknowledging it");
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm);
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm).ShouldNotBeNull();
f.Mapping.AllowedOperations &= ~DataOperations.AlarmConfirm;
f.Access.AuthorizeMethod(f.Identity("reader"), [placement], DataConditionMethods.Confirm)
.ShouldBeNull("the mapping must itself grant the method's bit");
f.Access.AuthorizeMethod(f.Identity("reader"), [placement with { MappingId = "unknown" }], DataConditionMethods.Acknowledge).ShouldBeNull();
}
[Fact]
public async Task The_gate_routes_through_the_first_authorized_placement_and_refuses_a_realm_mismatch()
{
// A3b review S6: the real gate with several placements (the "first authorized placement" deviation) and a realm mismatch.
await using var f = new Fixture();
f.Grant(NodePermissions.Browse | NodePermissions.Subscribe | NodePermissions.AlarmAcknowledge);
var good = f.Placement();
var realmMismatch = good with { Realm = DataRealm.Uns };
var unknownMapping = good with { MappingId = "map-x" };
var ungranted = good with { FolderLocalSubject = "Elsewhere/map-a/dev1" };
var alsoGood = good with { RelativePath = "dev1/HR200-b" };
var id = f.Identity("reader");
f.Access.AuthorizeMethod(id, [realmMismatch], DataConditionMethods.Acknowledge).ShouldBeNull("a placement's realm must be its mapping's");
f.Access.AuthorizeMethod(id, [unknownMapping, realmMismatch, good, alsoGood], DataConditionMethods.Acknowledge)
.ShouldNotBeNull().Placement.ShouldBe(good, "the first placement the caller passes the gate on, in primary order");
f.Access.AuthorizeMethod(id, [alsoGood, good], DataConditionMethods.Acknowledge).ShouldNotBeNull().Placement.ShouldBe(alsoGood);
f.Access.AuthorizeMethod(id, [ungranted], DataConditionMethods.Acknowledge).ShouldBeNull("the grant is on the placement's folder scope");
f.Access.AuthorizeMethod(id, [ungranted, good], DataConditionMethods.Acknowledge).ShouldNotBeNull().Placement.ShouldBe(good);
}
[Fact]
public async Task An_invalid_request_is_refused_unsent_before_the_lease()
{
// A3b review S3: a validation failure is RejectedBeforeDispatch, never an exception the node manager reads as "unknown".
await using var f = new Fixture();
using var demand = f.Access.AcquireEventDemand(null);
await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication);
var acquired = f.Connections.Acquired;
var sent = f.Connections.Sent.Count;
var result = await f.Access.CallAsync(f.Call() with { OperationId = new string('x', 10_000) }, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(0x80AB0000u);
f.Connections.Sent.Count.ShouldBe(sent);
f.Connections.Acquired.ShouldBe(acquired, "not even leased");
}
[Fact]
public async Task With_no_open_condition_stream_a_call_is_BadNoCommunication_and_nothing_is_sent()
{
await using var f = new Fixture();
var result = await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(BadNoCommunication);
f.Connections.Acquired.ShouldBe(0, "the connection is never even leased");
f.Connections.Sent.ShouldBeEmpty();
}
[Fact]
public async Task A_call_goes_through_the_lease_with_the_streams_serving_incarnation_and_a_stream_end_stops_dispatch()
{
await using var f = new Fixture();
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication);
var sent = f.Connections.Sent.Last();
sent.ExpectedServingIncarnation.ShouldBe(Serving.Incarnation, "addressed to the incarnation the records came from");
sent.Placement.ShouldBe(f.Placement().Placement);
sent.Method.ShouldBe(DataConditionMethods.Acknowledge);
sent.ExpectedActivation.ShouldBe(new DataActivationMarker("inc", 3));
sent.OperationId.ShouldBe("op-1");
sent.RemainingBudget.ShouldBe(TimeSpan.FromMilliseconds(900));
sent.OnBehalfOf.ShouldBe("operator");
f.Connections.Result = new(DataWriteState.OutcomeUnknown, 0x80050000u, "transport failed");
(await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown, "passed through");
// The connection goes down: the stream ends and cannot be re-opened.
var before = f.Connections.Sent.Count;
f.Connections.Down = true;
stream.End();
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode == BadNoCommunication);
var final = f.Connections.Sent.Count;
(final - before).ShouldBeLessThanOrEqualTo(1, "at most the call racing the stream end");
(await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode.ShouldBe(BadNoCommunication);
f.Connections.Sent.Count.ShouldBe(final, "connection down: nothing sent");
}
[Fact]
public async Task A_lease_refusing_the_operation_is_BadUserAccessDenied_unsent()
{
await using var f = new Fixture();
using var demand = f.Access.AcquireEventDemand(null);
await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
await f.WaitAsync(async () => (await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken)).StatusCode != BadNoCommunication);
var sent = f.Connections.Sent.Count;
f.Connections.Refuse = true;
var result = await f.Access.CallAsync(f.Call(), TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(0x801F0000u);
f.Connections.Sent.Count.ShouldBe(sent);
}
[Fact]
public async Task The_condition_item_carries_the_origins_canonical_root_view_learned_from_metadata()
{
// Live a3b-cond-2: a UNS root item built from the address alone (subject = the opaque EquipmentId) was refused Denied.
await using var f = new Fixture(uns: true);
using var demand = f.Access.AcquireEventDemand(null);
var stream = await f.Connections.Streams.Reader.ReadAsync(TestContext.Current.CancellationToken);
var open = await stream.Opened.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
f.Connections.MetadataViews.Single().Subject.ShouldBe("EQ-0001", "metadata is asked as the browse resolver asks it (RemoteRootEntityId)");
open.Items.Single().View.Subject.ShouldBe("area/line/plc", "the item uses the origin's own view of the root");
}
// ---------------------------------------------------------------------------------------------------------------------
private sealed class Fixture : IAsyncDisposable
{
private readonly DataPlaneAuthorityState _state = new();
private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1) };
private readonly ProjectedMappingPlacement _placement;
public FakeConnections Connections { get; } = new();
public ProjectedConditionAccess Access { get; }
public RemoteNamespaceMapping Mapping => _placement.Mapping;
public Fixture(bool uns = false)
{
Grant(NodePermissions.Browse | NodePermissions.Subscribe);
var mapping = new RemoteNamespaceMapping
{
RemoteNamespaceMappingId = "map-a", DataConnectionId = Connection, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
AllowedOperations = DataOperations.Browse | DataOperations.Subscribe | DataOperations.AlarmSubscribe
| DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm,
MaxConditions = 10, ConditionStaleTimeoutMilliseconds = 100, ConditionSnapshotTimeoutMilliseconds = 30_000,
ConditionMethodTimeoutMilliseconds = 4321, BranchName = "map-a", RemoteNamespaceUri = "https://zb.com/otopcua/raw",
RemoteIdentifierKind = "string", RemoteIdentifier = "Plant",
};
if (uns)
{
mapping.Realm = mapping.RemoteRealm = DataRealm.Uns;
mapping.RemoteNamespaceUri = "https://zb.com/otopcua/uns";
mapping.RemoteIdentifier = "EQ-0001";
mapping.RemoteRootEntityId = "EQ-0001";
}
var segments = new[] { "Plant", "map-a" };
var anchor = new DataView(new DataAddress("origin", mapping.RemoteNamespaceUri, "string", mapping.RemoteIdentifier), mapping.Realm, "map-a", 1, "Plant/map-a");
var scope = new NodeScope { ClusterId = "c1", Kind = uns ? NodeHierarchyKind.Uns : NodeHierarchyKind.Raw, Segments = segments };
_placement = new ProjectedMappingPlacement(mapping, anchor, anchor, scope, ["local-parent"], new ActiveAuthority());
var policy = new DataOperationPolicy(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), TimeProvider.System);
Access = new ProjectedConditionAccess(new GrpcDataProjectedConditionAccessTests.FakeMappings([_placement]), Connections, policy,
() => new GrpcDataProjectedConditionAccessTests.FakeSink(), TimeProvider.System,
new ProjectedConditionOptions(TimeSpan.FromMilliseconds(200), 122_500, long.MaxValue, TimeSpan.FromMilliseconds(50)), NullLogger.Instance);
}
public void Grant(NodePermissions permissions) =>
_state.Apply("c1", "rev-" + (int)permissions, [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder,
ScopeId = "folder", PermissionFlags = permissions }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
public RoleCarryingUserIdentity Identity(string principal) => new(new UserNameIdentityToken { UserName = "apikey" }, [], principal,
_key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
public ImportedConditionPlacement Placement() =>
new("map-a", DataRealm.Raw, new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR200"),
DataRealm.Raw, null, 0, "Plant/dev1/HR200"), "Plant/map-a/dev1", "dev1/HR200");
public ImportedConditionMethodCall Call() => new(Connection, "key", Placement(), DataConditionMethods.Acknowledge,
new DataActivationMarker("inc", 3), "c", "op-1", TimeSpan.FromMilliseconds(900), "operator");
public async Task WaitAsync(Func<Task<bool>> condition)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!await condition())
{
if (DateTime.UtcNow > deadline) (await condition()).ShouldBeTrue("condition not met within 10 s");
await Task.Delay(20, TestContext.Current.CancellationToken);
}
}
public ValueTask DisposeAsync() { Access.Dispose(); return ValueTask.CompletedTask; }
}
private sealed class ActiveAuthority : IDataMappedCatalogAuthority
{
public long CatalogEpoch => 1;
public long AuthorityEpoch => 1;
public bool IsActive => true;
}
private sealed class FakeConnections : IGrpcDataAdapterConnectionSource
{
private int _acquired;
public Channel<FakeStream> Streams { get; } = Channel.CreateUnbounded<FakeStream>();
public List<DataConditionMethodRequest> Sent { get; } = [];
public List<DataView> MetadataViews { get; } = [];
public DataConditionMethodResult Result { get; set; } = new(DataWriteState.AcceptedUnconfirmed, 0, null);
public bool Refuse { get; set; }
public volatile bool Down;
public int Acquired => Volatile.Read(ref _acquired);
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _acquired);
if (Down) return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Lease(new FakeConnection(this)));
}
private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease
{
public IDataConnection Connection => connection;
public CancellationToken CancellationToken => CancellationToken.None;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
private sealed class FakeConnection(FakeConnections owner) : IDataConnection, IDataConditionMethodService
{
public DataTarget Target { get; } = new(DataTargetMode.Cluster, "origin", null);
public TimeProvider Clock => TimeProvider.System;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
{
lock (owner.MetadataViews) owner.MetadataViews.AddRange(request.Views);
// The origin answers with ITS canonical view of the root (subject = its browse path, not the opaque id).
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select(v => new DataItemResult<DataMetadata>("0",
DataItemStatus.Good, new DataMetadata(v with { Subject = "area/line/plc" }, "plc", "Folder", DataValueKind.Null, -1, [], false,
DataOperations.Browse, 1, null, null, false), null)).ToArray());
}
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException();
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
{
var stream = new FakeStream();
owner.Streams.Writer.TryWrite(stream);
return Task.FromResult<IDataSubscription>(stream);
}
public Task<DataConditionMethodResult> CallConditionMethodAsync(DataConditionMethodRequest request, CancellationToken cancellationToken)
{
if (owner.Refuse) throw new UnauthorizedAccessException("Operation is not enabled for this connection.");
lock (owner.Sent) owner.Sent.Add(request);
return Task.FromResult(owner.Result);
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
/// <summary>A stream that carries the serving identity it was established with (as the production one does) and no frames.</summary>
private sealed class FakeStream : IDataSubscription, IDataSubscriptionProvenance
{
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
public ServingIdentity Serving => GrpcDataProjectedConditionMethodTests.Serving;
public TaskCompletionSource<OpenSubscription> Opened { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
{
if (command is OpenSubscription open) Opened.TrySetResult(open);
return Task.CompletedTask;
}
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
public void End() => _frames.Writer.TryComplete();
public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); return ValueTask.CompletedTask; }
}
}