feat: preserve grpc write admission and uncertain outcomes
This commit is contained in:
@@ -20,7 +20,7 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
|
||||
| P02 | Schema/artifact/consumer projection | Passed; Astra approved | 72 F + 31 P + 106 R, no failures/skips; final run `20261116T034337.311145Z-cd97a339f340` |
|
||||
| P03 | Shared authorization and leases | Passed; Astra approved | 77 K + 89 O + 53 R + 19 H, no failures/skips; final run `20261116T034150.797719Z-8f107e03d8d5` |
|
||||
| P04 | Immutable publication, hub and local ports | Passed; Astra approved | 185 R + 16 A + 16 C + 77 O + 74 ScriptWorker + 88 MTConnect + 40 OpcUaClient = 496, no failures/skips; final run `20261116T060538.590404Z-b8ef1894731e` |
|
||||
| P05 | Mutation tickets/outcomes | Pending | |
|
||||
| P05 | Mutation tickets/outcomes | Passed; Astra approved | Complete gate 910/910 passed `20261116T084759.594405Z-42a294fc7f4f` after three Astra regression corrections; source and candidate reconciliation approved |
|
||||
| P06 | Streams/sharing/fair delivery | Pending | |
|
||||
| P07 | TLS/provisioning/node+cluster clients | Pending | |
|
||||
| P08 | Raw/UNS projection and adapter | Pending | |
|
||||
@@ -67,6 +67,28 @@ Final [Astra P02/P03 review](p02-p03-astra-review.md) closes all five findings a
|
||||
|
||||
Independent Python helpers for local-context validation, fixture endpoint/manifest isolation, ownership-only cleanup, atomic secret files, bounded/redacted processes, deployment outcome polling and CLI result validation have test-first preparation evidence: initial discovery failed on missing modules; the focused combined run subsequently passed 44 tests. This is not the P10 gate. Concrete Compose, SQL/device/seeder, TLS/provisioning, runtime observation, CLI/probe scenarios and actual Docker integration remain pending. No containers or databases have been modified.
|
||||
|
||||
## P05 execution notes
|
||||
|
||||
Runtime and SDK missing-API RED evidence is `20261116T062437.578601Z-6e2b4f1b2274` and `20261116T062507.986231Z-c09214fa8087`. The real DI composition test failed on the missing shared fence in `20261116T064939.908320Z-4dd869b001d4`; runtime registration now supplies one singleton without replacing an explicit registration. Rich actor creation initially failed all 19 startup checks because Akka constructor-based Props could not use the private rich constructor. An explicit indirect producer fixed creation, verified by one narrowly filtered positive test in `20261116T071454.486118Z-e187323e8fe5`; this was a diagnostic selection through the same discovery/TRX/source-identity guards, not a complete phase gate.
|
||||
|
||||
| Boundary | Observed RED | Correction / focused evidence |
|
||||
|---|---|---|
|
||||
| Original credential, authority, route and role admission | Missing API above | First 12 admission checks passed `20261116T065544.493707Z-3eb41ed1767c`; actual composed catalog/policy/actor checks are included in the driver cases |
|
||||
| Stop/restart retirement, injected-clock gateway deadline, snapshot-role callback order | 15 passed / 4 failed `20261116T071731.988476Z-ab7eaaea4c9b` | All original 19 cases subsequently passed inside the physical-overlap RED run below |
|
||||
| Rich physical same-target exclusion | 19 passed / 2 failed `20261116T072907.706321Z-c0a3b2178516` | Shared keyed permit now survives actor replacement, ID case variation, caller timeout and observation expiry; verified in the 910-test gate |
|
||||
| Principal duplicate identity | 5 passed / 1 failed `20261116T070925.834679Z-03e9d268979d` | Principal uses OrdinalIgnoreCase; operation ID remains Ordinal |
|
||||
| Late confirmation retention | 3 passed / 1 failed `20261116T072347.015611Z-61960f01d936` | Accepted definitive refinement refreshes result retention before physical release |
|
||||
| Expired observer result authority | 12 passed / 1 failed `20261116T074826.305696Z-f170f189f3b8` | Physical observer is the sole definitive publisher; the expiry case passed in the later 15-case hash RED |
|
||||
| Membership-event callback ordering | 8 passed / 1 failed `20261116T080834.575675Z-a81b507a518b` | Primary publication moved ahead of independent history callbacks; verified in the 910-test gate |
|
||||
| Authoritative SDK value and timestamp | 3 passed / 4 failed `20261116T065427.180129Z-23fa1d306a25` | All 7 passed `20261116T073441.203032Z-e27a76f907e9`; uncertainty restores last authoritative value/time and marks uncertain |
|
||||
| Concrete Modbus rich outcome / no resend | Capability absent, `20261116T065504.810035Z-1d3c011bd4e3` | All 20 passed `20261116T074539.497522Z-2b59ad2f16cd`, including real TCP dropped reply after effect and unsupported injected transport |
|
||||
| Allocation-bounded exact value fingerprint | Missing internal method, `20261116T080329.365239Z-f4c6626ad391` | All 8 passed `20261116T081444.424298Z-0adf33e9701f`; no large GetBytes/GetArray copies during hashing |
|
||||
| Resolved address and exact string operation semantics | 13 passed / 2 failed `20261116T082102.902677Z-dd7a6a847714` | Canonical catalog view and lossless UTF-16 metadata hashing verified in the 910-test gate |
|
||||
|
||||
The first complete P05 gate passed 906 tests in `20261116T082435.847137Z-41e436e72d95`. [Astra's final source review](p05-astra-review.md) then identified three uncovered cases. Real TCP FC23 wrong-function exception fallback produced the expected failure in `20261116T083756.925253Z-ac0395f545eb` (21 passed/one failed); its no-replay correction passed all 22 focused cases in `20261116T084606.160092Z-73c1868a8b65`. The current-key-expiry fence-wait test failed in `20261116T084157.535508Z-509aba58e961` (22 passed/one failed), and the actual coordinator-backed source callback blocked in `20261116T084419.395301Z-6c55e8767242` (19 passed/one failed). Current immutable key expiry is now checked with original expiry under the final dispatch fence; role-wrapper cache refresh uses nonblocking fence acquisition and provisional process provenance on contention. The final complete gate passed **910** tests (195 Runtime, 70 SDK, 29 Core, 593 Modbus, 23 Abstractions), no failures/skips, in `20261116T084759.594405Z-42a294fc7f4f`. Astra verified the final candidate hashes and approved P05.
|
||||
|
||||
The [physical lifetime review](p05-physical-lifetime-astra-review.md) requires keyed rich-to-rich exclusion for known pending raw tasks. It does not promise universal device ordering against the unchanged legacy abandonment path, fire-and-forget application, different logical references or another process. Both factory-supported Modbus modes provide an explicit no-resend transport path; legacy transport recovery is preserved. The rich SDK hook remains unbound until the complete authorized P08 mapping route exists. No Docker or database apply has run.
|
||||
|
||||
## P04 execution notes
|
||||
|
||||
Hub and source-feed expected missing-API RED runs: `20261116T035138.678709Z-921224df1e45` and `20261116T035253.701549Z-3677798d45ff`. The coordinated production graph then compiled while the Task10 test failed on the missing local catalog/facade APIs in `20261116T040451.917499Z-9fc5a1cf55f8`. [Publication review](p04-publication-astra-review.md) identified producer blocking, lifecycle, binding recovery and virtual freshness issues; correction candidates remain unapproved until their behavioral gate and rereview finish.
|
||||
@@ -79,9 +101,9 @@ The P04 selector manifest adds only affected virtual/restart, timestamp/worker/h
|
||||
|
||||
## Later-phase integration obligations
|
||||
|
||||
P05 read-only preparation located the actual device invocation inside the resilience delegate, after actor dispatch and `Task.Yield`; final ticket validation must occur there. Capture the actual driver task for bounded late observation, because the resilience wrapper can time out first. Legacy Good acknowledgments without established device-application guarantees remain unconfirmed.
|
||||
P05 read-only preparation located the actual device invocation inside the resilience delegate, after actor dispatch and `Task.Yield`; final ticket validation must occur there. Capture the actual driver task for bounded late observation, because the resilience wrapper can time out first. Legacy Good acknowledgments without established device-application guarantees remain unconfirmed. The agreed rich path shares a short dispatch/publication fence across actual authority, catalog, primary-verdict, route and driver-lifetime pointer changes; permission evaluation, callbacks and arbitrary driver code remain outside it. The dispatch mark is the documented linearization point immediately before the driver call on the same delegate path. Dispatched Unknown claims and physical-call/payload permits remain pinned until the actual task ends, even after observer retention expires. Real per-item endpoint switching belongs to the P07 connection-client gate, with mapped integration in P08; P05 must prove ordered partial executor outcomes without a fabricated failover client.
|
||||
|
||||
P06 must prove retained snapshot acquisition age survives transport/reconnect independently of optional wall-clock timestamps. Current unary `ReadResult` carries age, while subscription values do not yet carry an explicit age field; resolve this at the stream contract checkpoint rather than infer freshness from receipt. P07 should construct remote realm roots using the canonical cluster identity from validated capabilities, and compose source publishers with real atomic process/role provenance shared with the catalog coordinator.
|
||||
The [Astra P06 contract checkpoint](p06-contract-astra-review.md) approves additive age/readiness with explicit domain age uncertainty, successful delivery receipts, finite session expiry and real acknowledged acquisition demand. It approves no implementation yet. P06 must prove retained snapshot acquisition age survives transport/reconnect independently of optional wall-clock timestamps. Current unary `ReadResult` carries age, while subscription values do not yet carry an explicit age field; resolve this at the stream contract checkpoint rather than infer freshness from receipt. P07 should construct remote realm roots using the canonical cluster identity from validated capabilities, and compose source publishers with real atomic process/role provenance shared with the catalog coordinator.
|
||||
|
||||
## P00 verification
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# P05 Astra implementation review
|
||||
|
||||
**Disposition: approved for P05 source freeze.** All three findings below are resolved in the reviewed correction candidate and complete applicable gate. The final gate passed **910 tests with zero failures/skips**. This is a P05 checkpoint, not approval of the complete data-connection feature.
|
||||
|
||||
The review is read-only except this evidence document. No reviewer builds, tests, production changes, migration execution or Docker work were performed. Scope covers Task 11/12 admission, actual actor invocation, publication fencing, operation retention, physical resource lifetime, SDK rich completion, Modbus rich no-resend handling and exact value/metadata fingerprints. The plan, design obligations and execution ledger informed the review.
|
||||
|
||||
## Candidate and verification evidence
|
||||
|
||||
Final complete gate `artifacts/grpc-data/20261116T084759.594405Z-42a294fc7f4f/unit/P05/run.json` reports **910 passed, zero failures/skips**: Runtime 195, SDK 70, Core 29, Modbus 593 and Core.Abstractions 23. Every new and required existing class is represented in execution; this gate has no platform exclusions. Before this final review-document edit, the reviewed checkout matched its recorded baseline `70f50201e9140aa51b64b289e608c3bea4061003`, tracked binary-diff SHA-256 `5c12ff3d22f130314af6e84055bb94200682167f6decfe841c0fd57ca77fcd5a` and all 19 recorded untracked file hashes. That includes 16 source/test files and three review documents. This document's disposition update is the sole reviewer change after reconciliation.
|
||||
|
||||
The preceding complete gate `20261116T082435.847137Z-41e436e72d95` passed 906 tests but did not cover the three issues found during source review. Its tracked diff SHA-256 was `8f3d9145aeff119443b6b9d9028e6ee897f1c0be8455962f235a968631f6968a`; its 18 recorded untracked hashes also matched the then-reviewed checkout. The additional correction regressions are included in the final 910-test gate.
|
||||
|
||||
The execution ledger records the actual failing tests preceding the existing corrections. Relevant evidence includes physical same-target RED `20261116T072907.706321Z-c0a3b2178516`, late-retention RED `20261116T072347.015611Z-61960f01d936`, observer-expiry RED `20261116T074826.305696Z-f170f189f3b8`, real actor ordering RED `20261116T071731.988476Z-ab7eaaea4c9b`, membership callback ordering RED `20261116T080834.575675Z-a81b507a518b`, SDK RED `20261116T065427.180129Z-23fa1d306a25`, and canonical metadata hashing RED `20261116T082102.902677Z-dd7a6a847714`. The complete gate covers their corrected candidates.
|
||||
|
||||
## H1 — Mismatched Modbus exception can trigger a second mutation
|
||||
|
||||
**Severity: High. Status: resolved.** In the initially reviewed `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus/ModbusDriver.cs:1568`, `SingleSendWriteTransport` correctly declined to classify a mismatched exception function as a definitive refusal, but rethrew the original `ModbusException`. `TryWriteViaFc23Async` at line 1830 caught every exception with code `0x01`, without matching the requested function, and returned false. `WriteOneAsync` then sent FC16 as its fallback.
|
||||
|
||||
Consequently an FC23 request followed by a matching transaction/unit but mismatched exception function, for example FC6/code1, can issue a second mutation after an ambiguous first response. Transport-level retry is disabled, but this driver-level fallback still violates the rich no-replay boundary. The existing wrong-function test mutates a normal FC23 response and does not exercise the exception catch.
|
||||
|
||||
Reject a mismatched exception function as an invalid/ambiguous response before the rich path reaches the legacy fallback, or constrain that fallback to the exact requested FC23 function. Preserve fallback after a valid FC23 Illegal Function response, which proves that request did not perform the write. Add a regression with an exact physical send/effect count: malformed exception response must yield Unknown and one send; valid FC23 Illegal Function may still lead to the safe FC16 fallback. A real TCP fixture is preferred because this crosses the response parser and fallback together.
|
||||
|
||||
**Resolution:** the rich wrapper now converts a mismatched write exception function to `InvalidDataException` before the FC23 fallback catch. Its definitive-refusal flag remains false and the outcome is Unknown. Actual RED `20261116T083756.925253Z-ac0395f545eb` passed 21 tests and failed this new case by incorrectly reporting confirmed success. Focused gate `20261116T084606.160092Z-73c1868a8b65` then passed all 22. The real TCP regression verifies an FC23 effect followed by `0x86/0x01` produces one request, one effect and Unknown; its positive counterpart verifies exact `0x97/0x01` permits two requests but one effect through FC16. Both pass in the complete final gate. The change is confined to the rich wrapper and preserves legacy behavior.
|
||||
|
||||
## H2 — Current key expiry is not rechecked at dispatch commitment
|
||||
|
||||
**Severity: High. Status: resolved.** The initially reviewed `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteDispatchGate.cs:36` checked current key usability before acquiring the publication fence. The final fenced check at line 49 checked only the ticket's original `CredentialExpiresUtc`. Current key expiry can be earlier than that original timestamp, or the original timestamp can be absent: changing a deployed key's expiry does not change its secret-derived credential version.
|
||||
|
||||
A context authenticated under a nonexpiring/later-expiring key can remain usable after its key's expiry has been shortened. If the current key is still valid during policy evaluation but expires while this invocation waits for the fence, authority/catalog references remain unchanged and the final check can commit dispatch after current key expiry. The existing expiry regression advances time before policy evaluation and uses the caller expiry, so does not establish this boundary.
|
||||
|
||||
Inside the final short fence, recheck the already captured immutable authority's key binding and expiry against the current time, as well as the original context expiry. Keep permission evaluation and callbacks outside the fence; expose a bounded immutable credential check rather than invoking the evaluator there. A deterministic regression should hold the fence after policy succeeds, advance UTC across the current key expiry while original expiry is null/later, release it, and verify a terminal undispatched rejection with zero backend calls.
|
||||
|
||||
**Resolution:** the gate captures current enabled key facts and verifies principal/credential version from its captured immutable authority before policy evaluation. It keeps the current key expiry as a local value. After acquiring the fence it checks both this expiry and the original context expiry against one fresh UTC sample, while the authority identity check ensures those captured facts remain authoritative. Hashing, key copying and permission evaluation remain outside the fence. Actual RED `20261116T084157.535508Z-509aba58e961` passed 22 tests and failed the real actor/current-key-expiry case by confirming the write. That regression holds the fence, waits for the last successful policy UTC read, advances time beyond current key expiry with a null original expiry, and verifies rejection/zero device calls; it passes in the final complete gate. Taking the UTC sample at the start of this short fenced block is acceptable: the remaining checks are bounded immutable reads with no await, permission evaluator or driver callback. The correction closes the demonstrated fence-wait expiry gap without promising an atomic wall-clock-and-CAS instruction.
|
||||
|
||||
## M1 — Role-wrapper refresh makes acquisition callbacks block again
|
||||
|
||||
**Severity: Medium. Status: resolved.** The initially reviewed `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs:61` called blocking `DispatchFence.Enter()` when `Current` had to replace its cached serving-role wrapper. P04 approved that accessor as a bounded lock-free read/CAS path. `SourceSamplePublisher.TryPublish` calls its supplied serving provider at `SourceSamplePublisher.cs:338` while in the producer callback and per-source gate; the coordinator-backed provider traverses `Serving` and `Current`.
|
||||
|
||||
A role mismatch while another thread holds the dispatch fence therefore makes the new ingress wait, despite the surrounding source and hub gates using nonblocking acquisition. The scope is the production coordinator-backed source provider; it does not depend on an arbitrary malicious callback.
|
||||
|
||||
Use a nonblocking fence acquisition for read-side wrapper refresh and return an appropriate unavailable/provisional identity on contention, or arrange control-side publication with lock-free reads. Preserve current producer identity and actual acquisition timestamps; dropping a contended acquisition must not replay it later as fresh. Add the composed regression: coordinator-backed publisher, cached role mismatch, another thread holding the dispatch fence, and a producer callback that completes without waiting for that holder.
|
||||
|
||||
**Resolution:** `DataWriteDispatchFence.TryEnter` uses `Monitor.TryEnter` with no wait. The bounded `Current` refresh returns null on contention; `Serving` then provides actual process identity/current role with provisional zero epochs, as permitted by the P04 acquisition boundary. Source publisher and hub remain unchanged. Actual RED `20261116T084419.395301Z-6c55e8767242` passed 19 tests and failed the new callback case because it waited for the fence. The composed publisher/coordinator regression now completes before the held fence is released, preserves the active producer, and verifies a subsequent real acquisition's value and original source timestamp. It passes in the final complete gate. Public serving still requires the established catalog/authority validation; provisional raw retention does not make a public catalog ready.
|
||||
|
||||
## Resolved earlier findings and reviewed behavior
|
||||
|
||||
- The [earlier physical-lifetime review](p05-physical-lifetime-astra-review.md) is superseded for its two findings: `LateWriteObserver` now reserves the global slot and `(driver ID, reference)` key together, using driver `OrdinalIgnoreCase` and reference `Ordinal`. Release follows actual raw invocation completion, including synchronous blocking before a task is returned. Caller timeout, observer expiry and actor replacement do not release that target. Real actor regressions use capacity two, prove another target progresses, and cover replacement driver ID case variation. Local actor slots can still be abandoned as in the legacy path.
|
||||
- Accepted definitive `LateRefine` updates the retained-result timestamp before physical completion becomes visible. The one-minute registry/five-minute observer regression confirms a result arriving after two minutes remains Existing for its new result-retention window. Previously completed Unknown waiter tasks stay immutable; current retained outcome supplies the refinement.
|
||||
- The actual rich driver call is inside the non-idempotent resilience invoker delegate. Ticket validation runs there immediately before the dispatch CAS. Driver code, permission evaluation and authority notifications run outside the short publication fence. Authority/catalog/route/lifetime and primary-generation publications share the fence; remap-away-and-back and demote/promote do not revive old proofs. H2 now also checks current-key expiry after fence acquisition.
|
||||
- Dispatch and proven no-call rejection compete through the claim transition. Released queued tickets cannot later invoke the driver. The raw-task observer alone publishes definitive dispatched results; outer Ask/invoker replies can establish no-call rejection or Unknown but cannot refine beyond observer retention. Payload and physical capacity remain charged until the actual invocation exits.
|
||||
- Executor admission uses authenticated context, resolved catalog view and trusted route, enforces authorization/export/write/type readiness before dispatch, retains its own value lease, joins duplicate operation IDs without tying shared work to a waiter's cancellation, and preserves per-item input order. Registry principal comparison matches case-insensitive principal identity while operation IDs remain ordinal. Internal canonical fingerprints preserve typed shape, ordinal UTF-16 including unpaired surrogates and floating-point bits without a payload-sized hashing copy.
|
||||
- SDK rich completion is asynchronous and uses the exact node/write stamp. Rejection/confirmed failure restores prior authoritative value, status and source timestamp. Unknown/AcceptedUnconfirmed restores the prior value/time with `UncertainLastUsableValue`. Equal-valued fresh source updates, newer writes and recreated nodes cannot be overwritten by stale completions. No optimistic value is published to the sample hub by this seam.
|
||||
- Modbus rich TCP and RTU-over-TCP calls disable transport resend after ambiguous loss and keep legacy recovery behavior. Valid normal echoes/readback shape are checked, and real TCP dropped-reply-after-effect evidence exists. H1's mismatched-exception fallback hole is resolved by the rich wrapper and actual TCP regression.
|
||||
- Runtime DI supplies one shared dispatch fence without overriding an explicit registration. Production data service wiring belongs to P07; the SDK hook remains unbound until the authorized P08 mapping route exists. Real endpoint failover belongs to P07/P08, not a fabricated P05 client.
|
||||
|
||||
The target exclusion guarantee is limited to rich-to-rich known pending raw tasks in this process. It does not promise universal device ordering against legacy abandoned operations, different references naming the same device storage, fire-and-forget application after a task returns, or another process. Those limitations do not excuse replay of a known ambiguous mutation or dispatch using expired current credentials.
|
||||
|
||||
The focused correction rereview and reconciled complete applicable gate satisfy the P05 checkpoint. No P05 findings remain open; dependent implementation may proceed subject to its own planned gates and review.
|
||||
@@ -0,0 +1,28 @@
|
||||
# P05 Astra physical-lifetime checkpoint
|
||||
|
||||
**Disposition: a rich-write target-lifetime guard is required before approving this boundary.** This narrow source review inspected `RunRichWriteAsync`, actor queue completion, `LateWriteObserver` and `WriteOperationRegistry` at baseline `70f50201e` plus the current P05 candidate. No source edits, builds or tests were performed. This is not a whole-P05 review.
|
||||
|
||||
## Confirmed overlap after abandonment
|
||||
|
||||
`DriverInstanceActor.RunRichWriteAsync` around lines 1338–1351 waits for the invoker outcome only through its bounded timeout/abandonment window, then unconditionally sends `WriteCompleted`. `OnWriteCompleted` around lines 1499–1505 removes `_tagsInFlight` and drains the queue. The separately retained `LateWriteReservation` correctly keeps the payload and global physical permit until the raw invocation actually exits, including synchronous blocking before it returns a task. However, that permit is only a node-wide count.
|
||||
|
||||
With at least two global physical permits, a token-ignoring rich write A can remain physically pending after its caller receives Unknown and its actor tag slot is released. A **different operation ID** B for the same trusted driver/reference can then pass the ordinary tag check, reserve the second permit and dispatch. A's later completion may occur after B. Duplicate-operation protection does not help because these are intentionally different operations. The current physical-capacity regression uses a limit of one, which hides this per-target gap.
|
||||
|
||||
Task 11 requires per-tag serialization and bounded physical work. Its compatibility requirement preserves the established legacy timeout behavior; it does not justify representing a known-pending rich invocation as physically finished. For the additive rich path, preserve the per-target physical exclusion while retaining bounded caller response and actor-slot release.
|
||||
|
||||
## Minimal guard
|
||||
|
||||
- Reserve a process-shared rich physical-target key together with the existing global permit. Use the trusted stable driver ID plus the resolved driver reference, with the same identity comparison semantics as the route. Do not key by client view/alias, operation ID or actor/driver incarnation: replacement actors must still see the known pending invocation. Include an owner/cluster discriminator only if stable driver IDs are not already process-unique.
|
||||
- Hold that key, physical permit and value lifetime until the actual raw invocation exits. Caller timeout, outer Ask failure, observer-retention expiry, registry retention, actor stop/restart and driver reincarnation must not release it. Every proven pre-dispatch rejection releases its unused reservation exactly once.
|
||||
- Reject a conflicting new rich operation before dispatch, or keep it only within the existing bounded queue/expiry policy. A per-key busy check must not block unrelated references. Bound the key registry by the active physical-permit limit; clean entries at actual completion.
|
||||
- Keep legacy admission behavior unchanged in this correction. Consequently the guarantee is **rich-to-rich known-task exclusion**, not universal device ordering against legacy abandoned writes, another process, or later device application behind a fire-and-forget API. Once an underlying task returns AcceptedUnconfirmed, no known pending task remains to guard; do not manufacture device confirmation.
|
||||
|
||||
The decisive regression uses `maxOutstanding >= 2`: A on target X ignores cancellation and remains live after its Unknown response; B with a new operation ID on X must not invoke the backend; C on another reference must progress. After A actually completes, a newly admitted write on X may run. Repeat the protected-key case through actor/driver replacement using the same shared observer. Verify exact raw call count and release once on both success and rejection.
|
||||
|
||||
## Known registry retention correction
|
||||
|
||||
The coordinator had already identified the `WriteClaim.LateRefine` timestamp issue; this is not a new finding. The inspected implementation replaces `_outcome` with a definitive late result but leaves `_completedTimestamp` at the earlier Unknown/AcceptedUnconfirmed response. `CanRetire` can then prune the newly refined result immediately after `PhysicalFinished`, allowing a same-ID claim to become Owner instead of returning the retained outcome.
|
||||
|
||||
Refresh the retained-result timestamp when a definitive late refinement is accepted, before publishing physical completion. The stated regression is appropriate: one-minute registry retention, five-minute observer retention, definitive raw completion at two minutes, then the duplicate must remain Existing with the definitive current outcome. Keep the already-completed waiter task immutable; late refinement is queried through the retained current outcome. This checkpoint does not assert the queued correction has passed.
|
||||
|
||||
Host-stop publication ordering, injected-clock Ask behavior, primary verdict ordering, SDK correction and Modbus transport behavior were explicitly outside this narrow review and are not newly reported here.
|
||||
@@ -0,0 +1,48 @@
|
||||
# P06 Astra contract checkpoint
|
||||
|
||||
**Disposition: approve the minimal contract direction below, subject to the required semantics and tests. This is not implementation or P06 phase approval.** This read-only checkpoint inspected Tasks 13/14, the approved design, the subscription/domain/protobuf contracts, snapshot cursor behavior and the existing driver desired-subscription boundary at baseline `70f50201e` plus active P05 work. No source was changed and no build/tests were run. Actor changes must remain serialized after the P05 owner finishes.
|
||||
|
||||
## 1. Preserve acquisition age without inventing network freshness
|
||||
|
||||
`SnapshotItem` currently retains a sample/version but not its source's monotonic received timestamp. `DataSubscriptionValue`, `ValueUpdate` and `CompactUpdate` currently carry no acquisition age or readiness. Required additions:
|
||||
|
||||
- Capture the **actual existing `SourceState.Received`** with the immutable snapshot item under the same partition capture lock. Retained snapshots, status-only changes, role/header overlays and reconnects must not replace it with snapshot/send/receive time. The timestamp remains process-local; never serialize an absolute monotonic counter.
|
||||
- Add per-update optional `origin_age_ticks` and presence-bearing readiness to both fallback and compact forms, using new field numbers. Compute the elapsed origin age from the retained acquisition timestamp as late as practical at encoding/emission. A delayed encoded age is still a lower bound, never an exact receiver age. Preserve independently absent original source/server wall timestamps; do not infer age from them.
|
||||
- Decode age with explicit uncertainty. A small domain `DataAgeBounds` value with nullable lower and upper durations is sufficient: absent age means unknown, not zero; a supplied nonnegative origin age gives a lower bound at receipt and **no finite stream upper bound**. Accumulate receiver-local monotonic elapsed time afterward. Validate negative values, overflow and inconsistent bounds. Age zero is valid only when explicitly present. An absent readiness field must not silently become Ready; negotiate support or expose unknown/unavailable readiness while preserving original sample quality separately.
|
||||
- A receiver may certify a finite maximum-age requirement only from a known upper bound. `lower > maximum` proves stale; `lower <= maximum` with unknown upper proves neither fresh nor stale. Origin readiness, transport liveness and freshness are separate facts. A fresh authorized snapshot does not imply newly acquired device data.
|
||||
|
||||
**Decision:** additive wire age/readiness plus explicit domain age bounds/unknown freshness is sufficient for the current design. No stream probe/control extension is required now. Do not expose a plain lower-bound `TimeSpan` as though it were an exact age. A unary response can conservatively bound age above by its origin age plus elapsed time since that request began, provided the origin age was sampled within that causal request/response window. An unsolicited stream frame has no such finite upper bound. A later correlated probe may establish one only when its response is demonstrably ordered with the relevant sample/version; a heartbeat or metadata renewal alone cannot do so. Do not assume a finite one-way network delay or synchronized wall clocks.
|
||||
|
||||
Add codec parity/absence/invalid-duration tests and fake-time tests for a stalled snapshot, queued encoding, reconnect and status-only updates. Verify that absent wall timestamps do not prevent correct monotonic age, and that unknown stream freshness never satisfies a finite maximum-age predicate.
|
||||
|
||||
## 2. Commit delivery state at the actual adapter boundary
|
||||
|
||||
`ReadAllAsync` yielding a frame is not evidence of successful socket write. Use one serialized internal delivery sink/receipt boundary per stream. A prepared delivery owns bounded retained samples, authorization/publication gates, item/stream revisions and the expected committed baseline. The P07 transport adapter must await its actual `WriteAsync`; only successful completion acknowledges that delivery and commits the baseline/cursor. Failure, cancellation or ambiguous completion leaves no delivered baseline and resets/closes that epoch. This is transport acceptance, not a claim that the remote application consumed bytes.
|
||||
|
||||
The final authority/lease/revision check precedes handing bytes to the transport. Do not hold an actor/partition lock or a shared authority mutation lock through a potentially stalled socket write. Bytes already handed to the transport cannot be recalled; queued unsent payloads remain subject to the final gate. Removal acknowledgment is emitted only after earlier in-flight delivery is settled and every queued old-revision segment is canceled or rejected, so no old revision follows the acknowledgment.
|
||||
|
||||
Define the direct in-process adapter separately: enforce one consumer and choose an explicit successful bounded handoff/acceptance point. Commit there, or expose an acceptance receipt. Do not route the network adapter through an API that auto-commits merely on enumeration. Requesting the next item or disposing a frame must not accidentally stand in for an unobserved network result.
|
||||
|
||||
`SnapshotLease.TryReadDelta` currently mutates `_versions` and `_positions` before downstream delivery. P06 must replace or wrap that use with prepare/commit semantics. Keep **last considered version**, **pending retained candidate** and **last successfully delivered baseline** separate. Filtering/coalescing may advance considered work without claiming delivery; a failed candidate cannot advance the committed baseline or conceal a snapshot catch-up gap. Re-evaluate a candidate if its expected baseline changed while encoding. A receipt must be idempotent and scoped to the exact stream epoch/item revision so a late completion cannot commit into a replacement.
|
||||
|
||||
## 3. Use bounded session expiry and existing Open semantics
|
||||
|
||||
`OpenSubscription.SessionLifetime` already exists. Require a positive finite admitted duration, capped by server limits and current credential/authority lifetime. Expiry is measured monotonically and enforced even on a quiet control-only stream. At expiry, reject further commands/delivery, release demand and leases, and require a new Open/new stream epoch and snapshot. In v1, renewal can mean replacement with a newly authenticated Open; do not silently invent a renewal command or extend expiry on ordinary values/heartbeats.
|
||||
|
||||
If a requested duration cannot be admitted, reject it or report the effective duration explicitly; do not silently promise the requested lifetime while using an undisclosed revision. A duration is an upper lifetime limit, not a guarantee against earlier credential revocation. Separate command acknowledgment deadlines from session lifetime. An acknowledgment timeout after admission has an uncertain outcome and requires reconciliation through a fresh epoch/snapshot, not a fabricated rejection.
|
||||
|
||||
## 4. Acknowledge actual upstream demand, not mux interest
|
||||
|
||||
The current DriverHost sends a complete reference set with one publishing interval, and DriverInstance stores it then self-sends Subscribe. `SubscriptionEstablished` currently reports only diagnostic ID/reference count and is swallowed on ordinary self-resubscription; it proves neither a requested demand revision nor an effective sampling cadence. DependencyMux interest changes do not configure physical acquisition.
|
||||
|
||||
Required implementation boundary:
|
||||
|
||||
- Maintain a versioned demand registry merged with the existing legacy references/alarm behavior. Removing the final gRPC consumer must never remove a legacy interest. Preserve principal, export, target-mode/pinned-node, consistency and serving-generation isolation in sharing keys; shared physical samples do not share authorization.
|
||||
- Carry a desired revision and current producer incarnation to the actual driver subscription operation; return an acknowledged applied revision with effective supported settings or a rejection. Ignore late acknowledgment from a superseded desired revision/producer. Completion of the current driver's real Subscribe operation is a minimum requirement; do not claim arbitrary sampling/filter support merely because the generic method accepted an interval argument.
|
||||
- Compute the fastest admitted cadence and union of required triggers, with no upstream value deadband by default. Keep sampling and downstream publishing distinct. The current single driver-level interval may force a common faster cadence; revise/reject unsupported per-item demands honestly. An adapter whose physical cadence cannot change must report its known supported behavior instead of inventing acknowledgment.
|
||||
- A stronger add/modify remains pending until the actual origin establishment is acknowledged. Then take the registration/snapshot/version boundary and emit revised settings plus acknowledgment in order. Failure or timeout releases the tentative interest and does not send a success snapshot. Only safe relaxation may debounce; churn must coalesce bounded desired revisions without losing the latest stronger request.
|
||||
- Atomically install partition interest and capture its immutable state/watermark under the same owner boundary. Updates between physical acknowledgment and snapshot capture must be represented by the snapshot or later dirty generation. Multi-partition capture remains a vector, with bounded catch-up/reset; it does not imply cross-item atomicity. Keep steady interest ownership distinct from the finite snapshot payload lease so disposing sent snapshot chunks does not silently remove demand or lose the catch-up boundary.
|
||||
|
||||
Essential regressions are actual driver acknowledgment/revision ordering; faster-demand failure and revised settings; legacy-plus-gRPC union and last-interest removal; quiet source/revocation/expiry; source changes during registration/capture; old prepared candidate versus changed baseline; failed/ambiguous writer; remove acknowledgment versus a blocked prior send; and bounded snapshot cancellation/reconnect pressure. Existing fake hub or mux registration tests alone cannot prove physical cadence.
|
||||
|
||||
These contracts permit P06 implementation to proceed without adding an unneeded network freshness probe. The implementation checkpoint must still demonstrate the acknowledged origin boundary, actual writer receipt and bounded resource ownership before P06 approval.
|
||||
@@ -221,19 +221,29 @@
|
||||
"P05": [
|
||||
{
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=P05)|FullyQualifiedName~.DriverHostActorWriteRoutingTests.|FullyQualifiedName~.DriverInstanceActorConcurrentWriteTests.|FullyQualifiedName~.ActorNodeWriteGatewayTests.|FullyQualifiedName~.PrimaryGatePolicyTests.|FullyQualifiedName~.DriverWriteBoundsTests.",
|
||||
"filter": "(Feature=GrpcData&Phase=P05)|FullyQualifiedName~.DriverHostActorWriteRoutingTests.|FullyQualifiedName~.DriverInstanceActorConcurrentWriteTests.|FullyQualifiedName~.ActorNodeWriteGatewayTests.|FullyQualifiedName~.PrimaryGatePolicyTests.|FullyQualifiedName~.DriverWriteBoundsTests.|FullyQualifiedName~.GrpcDataCatalogActivationTests.|FullyQualifiedName~.GrpcDataCatalogStagingTests.|FullyQualifiedName~.GrpcDataSourceFeedParityTests.|FullyQualifiedName~.WarmRoleAuthorityTests.|FullyQualifiedName~.DriverHostActorRoleViewTests.|FullyQualifiedName~.DriverHostActorPrimaryRoleSourceTests.|FullyQualifiedName~.DriverHostActorPrimaryGateTests.|FullyQualifiedName~.DriverInstanceActorDisposeTests.|FullyQualifiedName~.DriverHostActorRestartTests.",
|
||||
"new_classes": [
|
||||
"GrpcDataWriteAdmissionTests",
|
||||
"GrpcDataDriverOutcomeTests",
|
||||
"GrpcDataWriteRegistryTests",
|
||||
"GrpcDataLateWriteTests"
|
||||
"GrpcDataLateWriteTests",
|
||||
"GrpcDataWriteCompositionTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"DriverHostActorWriteRoutingTests",
|
||||
"DriverInstanceActorConcurrentWriteTests",
|
||||
"ActorNodeWriteGatewayTests",
|
||||
"PrimaryGatePolicyTests",
|
||||
"DriverWriteBoundsTests"
|
||||
"DriverWriteBoundsTests",
|
||||
"GrpcDataCatalogActivationTests",
|
||||
"GrpcDataCatalogStagingTests",
|
||||
"GrpcDataSourceFeedParityTests",
|
||||
"WarmRoleAuthorityTests",
|
||||
"DriverHostActorRoleViewTests",
|
||||
"DriverHostActorPrimaryRoleSourceTests",
|
||||
"DriverHostActorPrimaryGateTests",
|
||||
"DriverInstanceActorDisposeTests",
|
||||
"DriverHostActorRestartTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -248,6 +258,39 @@
|
||||
"NodeManagerBatchWriteTests",
|
||||
"EquipmentWriteGateTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Tests/ZB.MOM.WW.OtOpcUa.Core.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.DataPlaneAuthorityStateTests.|FullyQualifiedName~.GrpcDataPolicyTests.",
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"DataPlaneAuthorityStateTests",
|
||||
"GrpcDataPolicyTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests/ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=P05)|FullyQualifiedName~.ModbusDriverTests.|FullyQualifiedName~.ModbusWritePduFramingTests.|FullyQualifiedName~.ModbusStringAndBitArrayWriteTests.|FullyQualifiedName~.ModbusArrayWriteSupportParityTests.|FullyQualifiedName~.ModbusTransportSelfHealTests.",
|
||||
"new_classes": [
|
||||
"GrpcDataModbusWriteOutcomeTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"ModbusDriverTests",
|
||||
"ModbusWritePduFramingTests",
|
||||
"ModbusStringAndBitArrayWriteTests",
|
||||
"ModbusArrayWriteSupportParityTests",
|
||||
"ModbusTransportSelfHealTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=P05)|FullyQualifiedName~.GrpcDataContractsTests.",
|
||||
"new_classes": [
|
||||
"GrpcDataValueFingerprintTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"GrpcDataContractsTests"
|
||||
]
|
||||
}
|
||||
],
|
||||
"P06": [
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
public enum DataValueKind { Unspecified = 0, Null = 1, Boolean = 2, Int8 = 3, Int16 = 4, Int32 = 5, Int64 = 6, UInt8 = 7, UInt16 = 8, UInt32 = 9, UInt64 = 10, Float = 11, Double = 12, String = 13, Bytes = 14, Timestamp = 15, Guid = 16, Array = 17 }
|
||||
@@ -90,6 +92,32 @@ public sealed class DataValue : IDisposable
|
||||
public DataValueKind ArrayElementKind { get { ThrowIfDisposed(); return (_payload as ArrayPayload)?.Kind ?? throw new InvalidOperationException(); } }
|
||||
public IReadOnlyList<object> GetArray() { ThrowIfDisposed(); return _payload is ArrayPayload a ? Array.AsReadOnly((object[])a.Elements.Clone()) : throw new InvalidOperationException(); }
|
||||
public DataValue Retain() { ThrowIfDisposed(); return new(Kind, _payload, Dimensions); }
|
||||
/// <summary>Appends a private canonical value encoding without exposing or copying owned payload storage.</summary>
|
||||
internal void AppendSemanticFingerprint(IncrementalHash hash)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(hash);
|
||||
ThrowIfDisposed();
|
||||
DataFingerprintEncoding.AppendInt32(hash, 1);
|
||||
DataFingerprintEncoding.AppendInt32(hash, (int)Kind);
|
||||
if (Kind == DataValueKind.Null) return;
|
||||
if (Kind == DataValueKind.Bytes)
|
||||
{
|
||||
var bytes = (byte[])_payload!;
|
||||
DataFingerprintEncoding.AppendInt32(hash, bytes.Length);
|
||||
hash.AppendData(bytes);
|
||||
return;
|
||||
}
|
||||
if (_payload is ArrayPayload array)
|
||||
{
|
||||
DataFingerprintEncoding.AppendInt32(hash, (int)array.Kind);
|
||||
DataFingerprintEncoding.AppendInt32(hash, Dimensions!.Count);
|
||||
for (var i = 0; i < Dimensions.Count; i++) DataFingerprintEncoding.AppendInt32(hash, Dimensions[i]);
|
||||
DataFingerprintEncoding.AppendInt32(hash, array.Elements.Length);
|
||||
foreach (var element in array.Elements) DataFingerprintEncoding.AppendScalar(hash, array.Kind, element);
|
||||
return;
|
||||
}
|
||||
DataFingerprintEncoding.AppendScalar(hash, Kind, _payload!);
|
||||
}
|
||||
public void Dispose() => _disposed = true;
|
||||
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
private sealed record ArrayPayload(DataValueKind Kind, object[] Elements);
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
// Internal fingerprint framing only. This is not a transport or persisted format.
|
||||
internal static class DataFingerprintEncoding
|
||||
{
|
||||
internal static void AppendByte(IncrementalHash hash, byte value)
|
||||
{
|
||||
Span<byte> scratch = stackalloc byte[1];
|
||||
scratch[0] = value;
|
||||
hash.AppendData(scratch);
|
||||
}
|
||||
|
||||
internal static void AppendInt32(IncrementalHash hash, int value)
|
||||
{
|
||||
Span<byte> scratch = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteInt32LittleEndian(scratch, value);
|
||||
hash.AppendData(scratch);
|
||||
}
|
||||
|
||||
internal static void AppendInt64(IncrementalHash hash, long value)
|
||||
{
|
||||
Span<byte> scratch = stackalloc byte[8];
|
||||
BinaryPrimitives.WriteInt64LittleEndian(scratch, value);
|
||||
hash.AppendData(scratch);
|
||||
}
|
||||
|
||||
internal static void AppendString(IncrementalHash hash, string value)
|
||||
{
|
||||
AppendInt32(hash, value.Length);
|
||||
Span<byte> scratch = stackalloc byte[256];
|
||||
var offset = 0;
|
||||
while (offset < value.Length)
|
||||
{
|
||||
var chars = Math.Min(scratch.Length / 2, value.Length - offset);
|
||||
for (var i = 0; i < chars; i++)
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(scratch.Slice(i * 2, 2), value[offset + i]);
|
||||
hash.AppendData(scratch[..(chars * 2)]);
|
||||
offset += chars;
|
||||
}
|
||||
}
|
||||
|
||||
internal static void AppendScalar(IncrementalHash hash, DataValueKind kind, object value)
|
||||
{
|
||||
Span<byte> scratch = stackalloc byte[16];
|
||||
var count = 0;
|
||||
switch (kind)
|
||||
{
|
||||
case DataValueKind.Boolean: scratch[0] = (bool)value ? (byte)1 : (byte)0; count = 1; break;
|
||||
case DataValueKind.Int8: scratch[0] = unchecked((byte)(sbyte)value); count = 1; break;
|
||||
case DataValueKind.UInt8: scratch[0] = (byte)value; count = 1; break;
|
||||
case DataValueKind.Int16: BinaryPrimitives.WriteInt16LittleEndian(scratch, (short)value); count = 2; break;
|
||||
case DataValueKind.UInt16: BinaryPrimitives.WriteUInt16LittleEndian(scratch, (ushort)value); count = 2; break;
|
||||
case DataValueKind.Int32: BinaryPrimitives.WriteInt32LittleEndian(scratch, (int)value); count = 4; break;
|
||||
case DataValueKind.UInt32: BinaryPrimitives.WriteUInt32LittleEndian(scratch, (uint)value); count = 4; break;
|
||||
case DataValueKind.Int64: BinaryPrimitives.WriteInt64LittleEndian(scratch, (long)value); count = 8; break;
|
||||
case DataValueKind.UInt64: BinaryPrimitives.WriteUInt64LittleEndian(scratch, (ulong)value); count = 8; break;
|
||||
case DataValueKind.Float: BinaryPrimitives.WriteInt32LittleEndian(scratch, BitConverter.SingleToInt32Bits((float)value)); count = 4; break;
|
||||
case DataValueKind.Double: BinaryPrimitives.WriteInt64LittleEndian(scratch, BitConverter.DoubleToInt64Bits((double)value)); count = 8; break;
|
||||
case DataValueKind.Timestamp: BinaryPrimitives.WriteInt64LittleEndian(scratch, ((DateTimeOffset)value).UtcTicks); count = 8; break;
|
||||
case DataValueKind.Guid: ((Guid)value).TryWriteBytes(scratch); count = 16; break;
|
||||
case DataValueKind.String: AppendString(hash, (string)value); return;
|
||||
default: throw new ArgumentOutOfRangeException(nameof(kind));
|
||||
}
|
||||
hash.AppendData(scratch[..count]);
|
||||
}
|
||||
}
|
||||
+2
@@ -11,6 +11,8 @@
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="README.md" />
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests" />
|
||||
<InternalsVisibleTo Include="ZB.MOM.WW.OtOpcUa.Runtime" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -22,6 +22,8 @@ public sealed class DataOperationPolicy
|
||||
{
|
||||
/// <summary>The currently installed local authority generation, rechecked at publication boundaries.</summary>
|
||||
public long AuthorityEpoch => _authority.Current.GenerationId;
|
||||
/// <summary>Checks that a mutation gate and this policy use the same authority publisher.</summary>
|
||||
public bool UsesAuthority(IDataPlaneAuthoritySource authority) => ReferenceEquals(_authority, authority);
|
||||
private readonly IDataPlaneAuthoritySource _authority;
|
||||
private readonly IPermissionEvaluator _evaluator;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
@@ -563,6 +563,11 @@ public interface IDataPlaneAuthoritySink
|
||||
/// </remarks>
|
||||
public sealed class DataPlaneAuthorityState : IDataPlaneAuthoritySource, IDataPlaneAuthoritySink
|
||||
{
|
||||
/// <summary>Creates an authority state ordered with rich-write dispatch when a shared fence is supplied.</summary>
|
||||
public DataPlaneAuthorityState(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
|
||||
|
||||
/// <summary>The ordering fence used for publication of this authority.</summary>
|
||||
public DataWriteDispatchFence DispatchFence { get; }
|
||||
/// <summary>
|
||||
/// Generations of the trie retained per cluster. One is enough for correctness now — every
|
||||
/// authorization call stamps itself with the current generation — but an in-flight request that
|
||||
@@ -637,7 +642,7 @@ public sealed class DataPlaneAuthorityState : IDataPlaneAuthoritySource, IDataPl
|
||||
clusterId, revisionHash, generation, staged.Keys, staged.Grants, staged.ScopePaths, dropped,
|
||||
staged.EquipmentScopePaths, staged.ScriptedAlarmOwners, staged.UnsFolderScopes,
|
||||
staged.TagReferencingEquipment);
|
||||
Volatile.Write(ref _current, published);
|
||||
using (DispatchFence.Enter()) Volatile.Write(ref _current, published);
|
||||
}
|
||||
|
||||
// Outside the lock, deliberately. Subscribers walk live subscriptions and take the SDK's own
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
|
||||
/// <summary>Orders mutation dispatch commitments with security and routing publications.</summary>
|
||||
/// <remarks>The holder performs only bounded state publication or validation; never invoke external code while held.</remarks>
|
||||
public sealed class DataWriteDispatchFence
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
|
||||
/// <summary>Enter synchronously. Dispose on the same thread; never hold across an await.</summary>
|
||||
public IDisposable Enter()
|
||||
{
|
||||
Monitor.Enter(_gate);
|
||||
return new Releaser(_gate);
|
||||
}
|
||||
|
||||
/// <summary>Attempts entry without waiting; callers must fail closed when contention prevents entry.</summary>
|
||||
public bool TryEnter(out IDisposable? lease)
|
||||
{
|
||||
if (!Monitor.TryEnter(_gate)) { lease = null; return false; }
|
||||
lease = new Releaser(_gate);
|
||||
return true;
|
||||
}
|
||||
|
||||
private sealed class Releaser(object gate) : IDisposable
|
||||
{
|
||||
private object? _gate = gate;
|
||||
public void Dispose()
|
||||
{
|
||||
var held = Interlocked.Exchange(ref _gate, null);
|
||||
if (held is not null) Monitor.Exit(held);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,13 @@ public interface IModbusTransport : IAsyncDisposable
|
||||
Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Transport that can issue one transaction without resending it after an ambiguous failure.</summary>
|
||||
public interface IModbusWriteOnceTransport : IModbusTransport
|
||||
{
|
||||
/// <summary>Sends once; reconnecting before the first send is permitted, replay after send is not.</summary>
|
||||
Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Represents a Modbus protocol exception.</summary>
|
||||
public sealed class ModbusException(byte functionCode, byte exceptionCode, string message)
|
||||
: Exception(message)
|
||||
|
||||
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
|
||||
@@ -20,7 +21,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
/// <see cref="PollGroupEngine"/> since Modbus has no native push model.
|
||||
/// </remarks>
|
||||
public sealed class ModbusDriver
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, IWriteOutcomeCapability, IBatchSubscribable, IHostConnectivityProbe, IPerCallHostResolver, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Authored tags this driver could not build into its poll table.</summary>
|
||||
private readonly SkippedTagLedger _skippedTags = new();
|
||||
@@ -1477,6 +1478,112 @@ public sealed class ModbusDriver
|
||||
|
||||
// ---- IWritable ----
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
{
|
||||
var (generation, transport, table) = CaptureLifecycle();
|
||||
var results = new DataWriteOutcome[writes.Count];
|
||||
var batch = new BatchOutcome();
|
||||
for (var i = 0; i < writes.Count; i++)
|
||||
{
|
||||
var write = writes[i];
|
||||
if (!table.TryGetValue(write.FullReference, out var tag))
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNodeIdUnknown, "Unknown tag.");
|
||||
continue;
|
||||
}
|
||||
if (!tag.Writable || tag.Region is ModbusRegion.DiscreteInputs or ModbusRegion.InputRegisters)
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotWritable, "Tag is not writable.");
|
||||
continue;
|
||||
}
|
||||
if (transport is not IModbusWriteOnceTransport once)
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadNotSupported, "Transport cannot guarantee a single send.");
|
||||
continue;
|
||||
}
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadTimeout, "Canceled before dispatch.");
|
||||
continue;
|
||||
}
|
||||
if (_options.WriteOnChangeOnly && IsRedundantWrite(write.FullReference, write.Value))
|
||||
{
|
||||
results[i] = new(DataWriteState.AcceptedUnconfirmed, 0, "Write suppressed without a new device acknowledgement.");
|
||||
continue;
|
||||
}
|
||||
var unit = ResolveUnitId(tag);
|
||||
if (batch.IsFailedFast(unit))
|
||||
{
|
||||
results[i] = new(DataWriteState.RejectedBeforeDispatch, StatusBadCommunicationError, "Batch stopped before dispatch.");
|
||||
continue;
|
||||
}
|
||||
var tracked = new SingleSendWriteTransport(once);
|
||||
try
|
||||
{
|
||||
await WriteOneAsync(tracked, tag, write.Value, cancellationToken).ConfigureAwait(false);
|
||||
results[i] = tracked.ValidWriteAcknowledged
|
||||
? new(DataWriteState.DriverConfirmedSuccess, 0, null)
|
||||
: new(DataWriteState.OutcomeUnknown, StatusBadCommunicationError, "No confirmed write response.");
|
||||
batch.Answered = true;
|
||||
if (_options.WriteOnChangeOnly && tracked.ValidWriteAcknowledged)
|
||||
lock (_lastWrittenLock) _lastWrittenByRef[write.FullReference] = write.Value;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var status = MapWriteFailure(ex, unit, write.FullReference, batch, cancellationToken);
|
||||
var state = tracked.DefinitiveRefusal ? DataWriteState.DriverConfirmedFailure :
|
||||
!tracked.WriteAttempted && ex is (ModbusWriteRefusedException or OverflowException or FormatException or
|
||||
InvalidCastException or ArgumentException or NotSupportedException)
|
||||
? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown;
|
||||
results[i] = new(state, status, ex.Message);
|
||||
InvalidateWriteCache(write.FullReference);
|
||||
}
|
||||
}
|
||||
ReportOutcome(generation, batch, DateTime.UtcNow);
|
||||
return results;
|
||||
}
|
||||
|
||||
/// <summary>Tracks actual write PDUs and validates their protocol responses without altering the legacy path.</summary>
|
||||
private sealed class SingleSendWriteTransport(IModbusWriteOnceTransport transport) : IModbusTransport
|
||||
{
|
||||
public bool WriteAttempted { get; private set; }
|
||||
public bool ValidWriteAcknowledged { get; private set; }
|
||||
public bool DefinitiveRefusal { get; private set; }
|
||||
public Task ConnectAsync(CancellationToken ct) => throw new NotSupportedException();
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
|
||||
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
||||
{
|
||||
var isWrite = pdu[0] is 0x05 or 0x06 or 0x0F or 0x10 or 0x17;
|
||||
if (isWrite)
|
||||
{
|
||||
WriteAttempted = true;
|
||||
ValidWriteAcknowledged = false;
|
||||
DefinitiveRefusal = false;
|
||||
}
|
||||
byte[] reply;
|
||||
try { reply = await transport.SendWithoutRetryAsync(unitId, pdu, ct).ConfigureAwait(false); }
|
||||
catch (ModbusException ex)
|
||||
{
|
||||
// A response for another function cannot establish that this write was refused.
|
||||
// In particular, don't let FC23's illegal-function fallback replay an ambiguous write.
|
||||
if (isWrite && ex.FunctionCode != pdu[0])
|
||||
throw new InvalidDataException("Modbus exception function did not match the write request.", ex);
|
||||
DefinitiveRefusal = isWrite && ex.FunctionCode == pdu[0] && ex.ExceptionCode is (1 or 2 or 3);
|
||||
throw;
|
||||
}
|
||||
if (!isWrite) return reply;
|
||||
var valid = pdu[0] == 0x17
|
||||
? reply.Length == 2 + 2 * ((pdu[3] << 8) | pdu[4]) && reply[0] == pdu[0] && reply[1] == reply.Length - 2
|
||||
: reply.Length == 5 && reply.AsSpan().SequenceEqual(pdu.AsSpan(0, 5));
|
||||
if (!valid) throw new InvalidDataException("Modbus write acknowledgement did not match the request.");
|
||||
ValidWriteAcknowledged = true;
|
||||
return reply;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
/// skipped (a raw injected stream cannot reconnect).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class ModbusRtuOverTcpTransport : IModbusTransport
|
||||
public sealed class ModbusRtuOverTcpTransport : IModbusWriteOnceTransport
|
||||
{
|
||||
private readonly ModbusSocketLifecycle? _life;
|
||||
private readonly Stream? _testStream;
|
||||
@@ -89,7 +89,12 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
|
||||
_life is null ? Task.CompletedTask : _life.ConnectAsync(ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
||||
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, true);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, false);
|
||||
|
||||
private async Task<byte[]> SendCoreAsync(byte unitId, byte[] pdu, CancellationToken ct, bool allowRetry)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(nameof(ModbusRtuOverTcpTransport));
|
||||
if (_life is null && _testStream is null) throw new InvalidOperationException("Transport not connected");
|
||||
@@ -117,7 +122,7 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
|
||||
_life?.MarkSuccess();
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) when (!freshlyConnected && _life is not null && _life.AutoReconnect
|
||||
catch (Exception ex) when (allowRetry && !freshlyConnected && _life is not null && _life.AutoReconnect
|
||||
&& !ct.IsCancellationRequested
|
||||
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
|
||||
{
|
||||
@@ -131,6 +136,11 @@ public sealed class ModbusRtuOverTcpTransport : IModbusTransport
|
||||
_life.MarkSuccess();
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) when (!allowRetry && (ex is OperationCanceledException || ModbusSocketLifecycle.IsSocketLevelFailure(ex)))
|
||||
{
|
||||
if (_life is not null) await _life.TearDownAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -31,7 +31,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus;
|
||||
/// socket in reasonable time even when the application is mostly idle.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class ModbusTcpTransport : IModbusTransport
|
||||
public sealed class ModbusTcpTransport : IModbusWriteOnceTransport
|
||||
{
|
||||
private readonly ModbusSocketLifecycle _life;
|
||||
private readonly TimeSpan _timeout;
|
||||
@@ -68,7 +68,12 @@ public sealed class ModbusTcpTransport : IModbusTransport
|
||||
public Task ConnectAsync(CancellationToken ct) => _life.ConnectAsync(ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
||||
public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, true);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<byte[]> SendWithoutRetryAsync(byte unitId, byte[] pdu, CancellationToken ct) => SendCoreAsync(unitId, pdu, ct, false);
|
||||
|
||||
private async Task<byte[]> SendCoreAsync(byte unitId, byte[] pdu, CancellationToken ct, bool allowRetry)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(nameof(ModbusTcpTransport));
|
||||
|
||||
@@ -92,11 +97,11 @@ public sealed class ModbusTcpTransport : IModbusTransport
|
||||
|
||||
try
|
||||
{
|
||||
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
|
||||
var result = await SendOnceAsync(unitId, pdu, ct, strictResponse: !allowRetry).ConfigureAwait(false);
|
||||
_life.MarkSuccess();
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) when (!freshlyConnected && _life.AutoReconnect
|
||||
catch (Exception ex) when (allowRetry && !freshlyConnected && _life.AutoReconnect
|
||||
&& !ct.IsCancellationRequested
|
||||
&& ModbusSocketLifecycle.IsSocketLevelFailure(ex))
|
||||
{
|
||||
@@ -106,10 +111,16 @@ public sealed class ModbusTcpTransport : IModbusTransport
|
||||
// dialled is not retried: it proved nothing about a stale connection.
|
||||
await _life.TearDownAsync().ConfigureAwait(false);
|
||||
await _life.EnsureConnectedAsync(ct).ConfigureAwait(false);
|
||||
var result = await SendOnceAsync(unitId, pdu, ct).ConfigureAwait(false);
|
||||
var result = await SendOnceAsync(unitId, pdu, ct, strictResponse: false).ConfigureAwait(false);
|
||||
_life.MarkSuccess();
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) when (!allowRetry && (ex is OperationCanceledException || ModbusSocketLifecycle.IsSocketLevelFailure(ex)))
|
||||
{
|
||||
// The response might still arrive; do not reuse this socket and never replay the PDU.
|
||||
await _life.TearDownAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -138,7 +149,7 @@ public sealed class ModbusTcpTransport : IModbusTransport
|
||||
/// per-op timeout (the caller token is NOT cancelled) is a desync.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
private async Task<byte[]> SendOnceAsync(byte unitId, byte[] pdu, CancellationToken ct)
|
||||
private async Task<byte[]> SendOnceAsync(byte unitId, byte[] pdu, CancellationToken ct, bool strictResponse)
|
||||
{
|
||||
var stream = _life.Stream;
|
||||
if (stream is null) throw new InvalidOperationException("Transport not connected");
|
||||
@@ -169,6 +180,9 @@ public sealed class ModbusTcpTransport : IModbusTransport
|
||||
|
||||
var header = _header;
|
||||
await ReadExactlyAsync(stream, header, cts.Token).ConfigureAwait(false);
|
||||
if (strictResponse && (header[2] != 0 || header[3] != 0 || header[6] != unitId))
|
||||
throw new ModbusTransportDesyncException(ModbusTransportDesyncException.DesyncReason.UnitMismatch,
|
||||
"Modbus response protocol or unit does not match the request.");
|
||||
var respTxId = (ushort)((header[0] << 8) | header[1]);
|
||||
if (respTxId != txId)
|
||||
throw new ModbusTransportDesyncException(
|
||||
|
||||
@@ -15,6 +15,8 @@ using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
// the SDK result stays unqualified as the dominant name in the override; the source DTO is HistorianRead.
|
||||
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
|
||||
using SdkHistoryReadResult = Opc.Ua.HistoryReadResult;
|
||||
using DataWriteOutcome = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataWriteOutcome;
|
||||
using DataWriteState = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataWriteState;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
@@ -3396,6 +3398,41 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
return ServiceResult.Good;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Observes a rich mapped-write result without blocking the SDK write callback. The caller supplies
|
||||
/// the authoritative pre-write tuple and the exact active SDK write stamp. Mapped dispatch is wired
|
||||
/// separately once its remote route and authorization are available.
|
||||
/// </summary>
|
||||
internal Task ObserveMappedWriteCompletion(Task<DataWriteOutcome> completion, string nodeId,
|
||||
AddressSpaceRealm realm, object? optimisticValue, object? priorValue, StatusCode priorStatus,
|
||||
DateTime priorSourceTimestamp, EquipmentVariableState.WriteStamp stamp)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(completion);
|
||||
return completion.ContinueWith(t =>
|
||||
{
|
||||
// A fault, cancellation or unrecognized result says nothing definitive about device execution.
|
||||
var outcome = t.IsCompletedSuccessfully ? t.Result : null;
|
||||
if (t.IsFaulted) _ = t.Exception;
|
||||
if (outcome?.State is DataWriteState.RejectedBeforeDispatch or DataWriteState.DriverConfirmedFailure)
|
||||
{
|
||||
RevertOptimisticWriteIfNeeded(nodeId, new NodeWriteOutcome(false, outcome.Diagnostic),
|
||||
optimisticValue, priorValue, priorStatus, null, realm, stamp, priorSourceTimestamp);
|
||||
return;
|
||||
}
|
||||
if (outcome?.State == DataWriteState.DriverConfirmedSuccess) return;
|
||||
lock (Lock)
|
||||
{
|
||||
if (!_variables.TryGetValue(MapKey(realm, nodeId), out var variable) ||
|
||||
variable is not EquipmentVariableState equipment || !equipment.OwnsWrite(stamp)) return;
|
||||
variable.Value = SdkValueBoundary.FromClr(priorValue,
|
||||
variable.DataType == DataTypeIds.Byte && variable.ValueRank == ValueRanks.OneDimension);
|
||||
variable.StatusCode = StatusCodes.UncertainLastUsableValue;
|
||||
variable.Timestamp = priorSourceTimestamp;
|
||||
variable.ClearChangeMasks(SystemContext, includeChildren: false);
|
||||
}
|
||||
}, CancellationToken.None, TaskContinuationOptions.RunContinuationsAsynchronously, TaskScheduler.Default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pure role + availability gate for an inbound equipment-tag write, extracted off
|
||||
/// <see cref="OnEquipmentTagWrite"/> so it is unit-testable without booting an SDK server. Fails closed:
|
||||
@@ -3781,7 +3818,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
/// <param name="writeStamp">The actual production node and accepted write attempt; absent only for legacy direct tests.</param>
|
||||
internal void RevertOptimisticWriteIfNeeded(
|
||||
string nodeId, NodeWriteOutcome outcome, object? optimisticValue, object? priorValue, StatusCode priorStatus,
|
||||
string? clientUserId, AddressSpaceRealm realm, EquipmentVariableState.WriteStamp? writeStamp = null)
|
||||
string? clientUserId, AddressSpaceRealm realm, EquipmentVariableState.WriteStamp? writeStamp = null,
|
||||
DateTime? priorSourceTimestamp = null)
|
||||
{
|
||||
// Built under Lock if (and only if) a revert is performed, then reported AFTER Lock is released.
|
||||
AuditWriteUpdateEventState? auditEvent = null;
|
||||
@@ -3815,7 +3853,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
if (variable is EquipmentVariableState restored) restored.InvalidateWriteOwnership();
|
||||
variable.Value = prior;
|
||||
variable.StatusCode = priorStatus;
|
||||
variable.Timestamp = now;
|
||||
variable.Timestamp = priorSourceTimestamp ?? now;
|
||||
variable.ClearChangeMasks(SystemContext, includeChildren: false); // notify — restore prior
|
||||
|
||||
// Item C: build the audit event-state while we hold the node reference + Lock, but DON'T report yet.
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
/// <summary>A publication barrier between desired authority and successfully served topology.</summary>
|
||||
public sealed class CatalogActivation
|
||||
{
|
||||
public CatalogActivation(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
|
||||
public DataWriteDispatchFence DispatchFence { get; }
|
||||
private readonly object _sync = new();
|
||||
private CatalogActivationState _current = new(0, "", 0, false);
|
||||
|
||||
@@ -53,7 +55,7 @@ public sealed class CatalogActivation
|
||||
lock (_sync)
|
||||
{
|
||||
var epoch = checked(_current.CatalogEpoch + 1);
|
||||
Volatile.Write(ref _current, new(epoch, revision, 0, false));
|
||||
using (DispatchFence.Enter()) Volatile.Write(ref _current, new(epoch, revision, 0, false));
|
||||
return epoch;
|
||||
}
|
||||
}
|
||||
@@ -64,7 +66,7 @@ public sealed class CatalogActivation
|
||||
lock (_sync)
|
||||
{
|
||||
if (_current.CatalogEpoch != catalogEpoch) return false;
|
||||
Volatile.Write(ref _current, _current with { AuthorityEpoch = authorityEpoch, IsReady = false });
|
||||
using (DispatchFence.Enter()) Volatile.Write(ref _current, _current with { AuthorityEpoch = authorityEpoch, IsReady = false });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -75,7 +77,7 @@ public sealed class CatalogActivation
|
||||
{
|
||||
if (_current.CatalogEpoch != catalogEpoch) return false;
|
||||
var ready = topologySucceeded && _current.AuthorityEpoch > 0;
|
||||
Volatile.Write(ref _current, _current with { IsReady = ready });
|
||||
using (DispatchFence.Enter()) Volatile.Write(ref _current, _current with { IsReady = ready });
|
||||
return ready;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
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.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Revalidates a trusted catalog-bound ticket and commits dispatch against live publications.</summary>
|
||||
internal sealed class DataWriteDispatchGate
|
||||
(LocalCatalogCoordinator coordinator, CatalogActivation activation, DataPlaneAuthorityState authority,
|
||||
DataOperationPolicy policy, RedundancyRoleView role, WriteRouteState routes, TimeProvider clock,
|
||||
DriverWriteBounds bounds) : IWriteDispatchGate
|
||||
{
|
||||
private static DataWriteOutcome Denied => new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write no longer admitted.");
|
||||
|
||||
public DataWriteOutcome? TryCommit(WriteAdmissionTicket ticket, WriteClaim claim)
|
||||
{
|
||||
var fence = authority.DispatchFence;
|
||||
if (!policy.UsesAuthority(authority) || !ReferenceEquals(fence, coordinator.DispatchFence) || !ReferenceEquals(fence, activation.DispatchFence)
|
||||
|| !ReferenceEquals(fence, role.DispatchFence) || !ReferenceEquals(fence, routes.DispatchFence)) return Denied;
|
||||
var proof = ticket.Proof;
|
||||
var admission = proof.Admission;
|
||||
var snapshot = authority.Current;
|
||||
// Capture the currently deployed key facts before policy evaluation, while the key is still
|
||||
// valid. The copied row is local to this invocation; no mutable credential object enters the fence.
|
||||
var key = snapshot.FindUsableKey(admission.ApiKeyId, clock.GetUtcNow().UtcDateTime);
|
||||
if (key is null || !string.Equals(key.Principal, admission.PrincipalId, StringComparison.OrdinalIgnoreCase)
|
||||
|| !string.Equals(DataCallerIdentity.CredentialVersionFor(key), admission.CredentialVersion, StringComparison.Ordinal))
|
||||
return Denied;
|
||||
var currentKeyExpiry = key.ExpiresUtc;
|
||||
var catalog = coordinator.Current;
|
||||
var activationSnapshot = activation.Current;
|
||||
var caller = new DataCallerIdentity(admission.PrincipalId, admission.ApiKeyId,
|
||||
admission.CredentialVersion, admission.CredentialExpiresUtc);
|
||||
if (catalog is null || !catalog.IsActive || catalog.AuthorityEpoch != snapshot.GenerationId
|
||||
|| !catalog.TryResolve(admission.View, out var node) || !node.SourceEnabled || !node.Supported || !node.Metadata.Writable
|
||||
|| node.EntityKind != proof.EntityKind || node.EntityId != proof.EntityId || node.Source != proof.Source
|
||||
|| node.Scope.ClusterId != proof.Scope.ClusterId || node.Scope.Kind != proof.Scope.Kind
|
||||
|| !node.Scope.Segments.SequenceEqual(proof.Scope.Segments)
|
||||
|| (node.Metadata.AllowedOperations & DataOperations.Write) == 0
|
||||
|| !catalog.AllowsExport(admission.PrincipalId, node, DataOperations.Write)
|
||||
|| !policy.IsCallerUsable(caller) || !policy.AuthorizeLocal(caller, OpcUaOperation.WriteOperate, node.Scope)) return Denied;
|
||||
var target = new WriteRouteTarget(proof.DriverInstanceId, proof.DriverReference, admission.DriverIncarnation,
|
||||
proof.RouteGeneration, proof.PrimaryGeneration);
|
||||
using (fence.Enter())
|
||||
{
|
||||
// These are immutable reads only. Writers acquire their own state lock first, then this fence.
|
||||
var utcNow = clock.GetUtcNow();
|
||||
if (!ReferenceEquals(snapshot, authority.Current) || !ReferenceEquals(activationSnapshot, activation.Current)
|
||||
|| !coordinator.IsPublished(catalog) || !activationSnapshot.IsReady
|
||||
|| admission.AuthorityEpoch != snapshot.GenerationId || admission.CatalogRevision != activationSnapshot.CatalogEpoch
|
||||
|| admission.ServingIncarnation != catalog.Serving.Incarnation
|
||||
|| !role.ShouldActAsPrimary || role.PrimaryGeneration <= 0 || role.PrimaryGeneration != proof.PrimaryGeneration
|
||||
|| !string.Equals(catalog.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|
||||
|| !routes.IsCurrent(admission.View, target)
|
||||
|| (admission.CredentialExpiresUtc is { } expiry && expiry <= utcNow)
|
||||
|| (currentKeyExpiry is { } currentExpiry && currentExpiry <= utcNow.UtcDateTime)
|
||||
|| clock.GetTimestamp() >= admission.MonotonicExpiry
|
||||
|| clock.GetElapsedTime(clock.GetTimestamp(), admission.MonotonicExpiry) < bounds.RunBound + DriverWriteBounds.ReplyMargin)
|
||||
return Denied;
|
||||
return claim.TryMarkDispatched() ? null : claim.CurrentOutcome ?? Denied;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Security.Cryptography;
|
||||
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.Runtime.Drivers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
internal sealed class WriteValueBudget(long limit)
|
||||
{
|
||||
private long _used;
|
||||
public IDisposable? TryReserve(long bytes)
|
||||
{
|
||||
if (bytes <= 0 || limit <= 0) return null;
|
||||
while (true)
|
||||
{
|
||||
var used = Volatile.Read(ref _used);
|
||||
if (bytes > limit - used) return null;
|
||||
if (Interlocked.CompareExchange(ref _used, used + bytes, used) == used) return new Lease(this, bytes);
|
||||
}
|
||||
}
|
||||
private sealed class Lease(WriteValueBudget owner, long bytes) : IDisposable
|
||||
{
|
||||
private int _released;
|
||||
public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Add(ref owner._used, -bytes); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Caller-bound origin-local mutation admission; routes only catalog-resolved views.</summary>
|
||||
internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<LocalExportCatalog?> catalog,
|
||||
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, IDataWriteRoute route,
|
||||
WriteOperationRegistry registry, WriteValueBudget values, TimeProvider clock, DriverWriteBounds bounds) : IDataWriteService
|
||||
{
|
||||
private static DataWriteOutcome Rejected(string reason) => new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, reason);
|
||||
private static readonly DataWriteOutcome Unknown = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown.");
|
||||
|
||||
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(request.Items);
|
||||
request.Budget.Validate();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (request.Items.Count > Math.Min(request.Budget.MaxItems, capabilities.Limits.MaxBatchItems))
|
||||
throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds the item limit.");
|
||||
var totalBytes = 0L;
|
||||
foreach (var item in request.Items)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
ArgumentNullException.ThrowIfNull(item.Value);
|
||||
totalBytes = checked(totalBytes + RetainedBytes(item));
|
||||
}
|
||||
if (totalBytes > request.Budget.MaxBytes) throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds its byte limit.");
|
||||
var started = clock.GetTimestamp();
|
||||
var pending = request.Items.Select(item => ExecuteItem(item, request.Budget, started, cancellationToken)).ToArray();
|
||||
return await Task.WhenAll(pending).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<WriteItemResult> ExecuteItem(WriteItem item, DataBudget budget, long start, CancellationToken cancellationToken)
|
||||
{
|
||||
WriteItemResult Reject(string reason) => new(item.CorrelationId, Rejected(reason));
|
||||
if (item.View is null || item.View.Address is null) return Reject("Write unavailable or denied before dispatch.");
|
||||
var current = catalog();
|
||||
var caller = new DataCallerIdentity(context.PrincipalId, context.ApiKeyId, context.CredentialVersion, context.CredentialExpiresUtc);
|
||||
if (current is null || !current.IsActive || !capabilities.IsReady || current.AuthorityEpoch != policy.AuthorityEpoch
|
||||
|| current.Serving != capabilities.Serving || !policy.IsCallerUsable(caller)
|
||||
|| !current.TryResolve(item.View, out var node) || !current.AllowsExport(context.PrincipalId, node, DataOperations.Write)
|
||||
|| (node.Metadata.AllowedOperations & DataOperations.Write) == 0
|
||||
|| !policy.AuthorizeLocal(caller, OpcUaOperation.WriteOperate, node.Scope))
|
||||
return Reject("Write unavailable or denied before dispatch.");
|
||||
// Role and structure are intentionally checked after authorization.
|
||||
if (!string.Equals(current.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|
||||
|| !node.SourceEnabled || !node.Supported || !node.Metadata.Writable
|
||||
|| !ValueMatches(node.Metadata, item.Value) || item.ExpectedCatalogRevision != current.Serving.CatalogEpoch
|
||||
|| item.ExpectedServingIncarnation != current.Serving.Incarnation)
|
||||
return Reject("Write unavailable before dispatch.");
|
||||
if (string.IsNullOrWhiteSpace(item.OperationId) || string.IsNullOrWhiteSpace(item.CorrelationId))
|
||||
return Reject("Invalid write identity.");
|
||||
|
||||
byte[] hash;
|
||||
try { hash = SemanticHash(node.Metadata.View, item); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{ return Reject("Invalid write value."); }
|
||||
var result = registry.Claim(context.PrincipalId, item.OperationId, item.ExpectedServingIncarnation, hash);
|
||||
if (result.Kind is WriteClaimKind.Conflict or WriteClaimKind.Stale or WriteClaimKind.Capacity || result.Claim is null)
|
||||
return Reject("Write operation conflict or capacity exhausted.");
|
||||
var claim = result.Claim;
|
||||
if (result.Kind == WriteClaimKind.Existing)
|
||||
{
|
||||
var existing = claim.CurrentOutcome ?? await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new(item.CorrelationId, existing);
|
||||
}
|
||||
|
||||
var remaining = budget.Timeout - clock.GetElapsedTime(start);
|
||||
if (item.RemainingBudget < remaining) remaining = item.RemainingBudget;
|
||||
WriteRouteTarget? target;
|
||||
try { target = remaining >= bounds.GatewayAsk && route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; }
|
||||
catch { target = null; }
|
||||
if (target is null)
|
||||
{
|
||||
var rejected = Rejected("Insufficient budget or no active driver route.");
|
||||
claim.Complete(rejected);
|
||||
return new(item.CorrelationId, rejected);
|
||||
}
|
||||
var lease = values.TryReserve(RetainedBytes(item));
|
||||
if (lease is null)
|
||||
{
|
||||
var rejected = Rejected("Retained write byte budget exhausted.");
|
||||
claim.Complete(rejected);
|
||||
return new(item.CorrelationId, rejected);
|
||||
}
|
||||
WriteAdmissionTicket ticket;
|
||||
try
|
||||
{
|
||||
var issued = clock.GetTimestamp();
|
||||
var expiration = checked(issued + (long)(remaining.TotalSeconds * clock.TimestampFrequency));
|
||||
var admission = new DataWriteAdmission(context.PrincipalId, node.Metadata.View, current.AuthorityEpoch,
|
||||
current.Serving.CatalogEpoch, current.Serving.Incarnation, target.DriverIncarnation, item.OperationId,
|
||||
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion);
|
||||
var scope = new FrozenWriteScope(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray());
|
||||
var proof = new WriteRouteProof(admission, scope, node.EntityKind, node.EntityId, node.Source,
|
||||
target.DriverInstanceId, target.DriverReference, target.RouteGeneration, target.PrimaryGeneration);
|
||||
ticket = new WriteAdmissionTicket(proof, item.Value.Retain(), issued, lease);
|
||||
}
|
||||
catch
|
||||
{
|
||||
lease.Dispose();
|
||||
var rejected = Rejected("Invalid write deadline or value.");
|
||||
claim.Complete(rejected);
|
||||
return new(item.CorrelationId, rejected);
|
||||
}
|
||||
_ = DispatchAsync(route, ticket, claim);
|
||||
return new(item.CorrelationId, await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
private static async Task DispatchAsync(IDataWriteRoute route, WriteAdmissionTicket ticket, WriteClaim claim)
|
||||
{
|
||||
try
|
||||
{
|
||||
var outcome = await route.DispatchAsync(ticket, claim, CancellationToken.None).ConfigureAwait(false);
|
||||
// The physical observer is the sole publisher of definitive dispatched outcomes. A route
|
||||
// reply can establish only a proven no-call rejection or an ambiguous post-dispatch outcome;
|
||||
// otherwise it could refine an Unknown after late-result retention has already expired.
|
||||
if (outcome.State == DataWriteState.RejectedBeforeDispatch)
|
||||
{
|
||||
if (claim.Complete(outcome)) ticket.Dispose();
|
||||
}
|
||||
else if (outcome.State == DataWriteState.OutcomeUnknown)
|
||||
claim.Complete(outcome);
|
||||
}
|
||||
catch
|
||||
{
|
||||
var rejection = Rejected("Write route failed before dispatch.");
|
||||
if (claim.Complete(rejection)) ticket.Dispose();
|
||||
else claim.Complete(Unknown);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ValueMatches(DataMetadata metadata, DataValue value) =>
|
||||
value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind &&
|
||||
(value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind &&
|
||||
metadata.Dimensions.Count == value.Dimensions!.Count &&
|
||||
metadata.Dimensions.Zip(value.Dimensions).All(x => x.First == 0 || x.First == x.Second));
|
||||
|
||||
private static long RetainedBytes(WriteItem item) => checked(3 * item.Value.EstimatedRetainedBytes + 512L + 2L *
|
||||
((item.CorrelationId?.Length ?? 0) + (item.OperationId?.Length ?? 0) + (item.View?.Subject?.Length ?? 0)
|
||||
+ (item.View?.MappingId?.Length ?? 0) + (item.View?.Address?.OriginClusterId?.Length ?? 0)
|
||||
+ (item.View?.Address?.NamespaceUri?.Length ?? 0) + (item.View?.Address?.IdentifierKind?.Length ?? 0)
|
||||
+ (item.View?.Address?.Identifier?.Length ?? 0) + (item.ExpectedServingIncarnation?.Length ?? 0)));
|
||||
|
||||
private static byte[] SemanticHash(DataView canonicalView, WriteItem item)
|
||||
{
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
// Hash the catalog's actual resolved identity, not a caller's equivalent spelling or subject claim.
|
||||
// UTF-16 code units are framed directly, so distinct ordinal strings never collapse via replacement.
|
||||
DataFingerprintEncoding.AppendInt32(hash, 1);
|
||||
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.OriginClusterId);
|
||||
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.NamespaceUri);
|
||||
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.IdentifierKind);
|
||||
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.Identifier);
|
||||
DataFingerprintEncoding.AppendInt32(hash, (int)canonicalView.Realm);
|
||||
DataFingerprintEncoding.AppendByte(hash, canonicalView.MappingId is null ? (byte)0 : (byte)1);
|
||||
if (canonicalView.MappingId is not null) DataFingerprintEncoding.AppendString(hash, canonicalView.MappingId);
|
||||
DataFingerprintEncoding.AppendInt64(hash, canonicalView.MappingRevision);
|
||||
DataFingerprintEncoding.AppendString(hash, canonicalView.Subject);
|
||||
DataFingerprintEncoding.AppendInt64(hash, item.ExpectedCatalogRevision);
|
||||
DataFingerprintEncoding.AppendString(hash, item.ExpectedServingIncarnation);
|
||||
item.Value.AppendSemanticFingerprint(hash);
|
||||
return hash.GetHashAndReset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using Akka.Actor;
|
||||
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.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Shared node-incarnation write state, explicitly wired only when the data plane is ready.</summary>
|
||||
public sealed class DataWriteRuntime
|
||||
{
|
||||
private readonly LocalCatalogCoordinator _catalog;
|
||||
private readonly DataOperationPolicy _policy;
|
||||
private readonly DataCapabilitiesProvider _capabilities;
|
||||
private readonly RedundancyRoleView _role;
|
||||
private readonly WriteOperationRegistry _registry;
|
||||
private readonly WriteValueBudget _values;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly DriverWriteBounds _bounds;
|
||||
internal readonly WriteRouteState Routes;
|
||||
internal readonly IWriteDispatchGate Gate;
|
||||
internal readonly LateWriteObserver Observer;
|
||||
internal Action<string>? BeforeDriverStopForTests { get; set; }
|
||||
|
||||
public DataWriteRuntime(LocalCatalogCoordinator catalog, CatalogActivation activation, DataPlaneAuthorityState authority,
|
||||
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, RedundancyRoleView role,
|
||||
TimeProvider clock, DriverWriteBounds bounds, string servingIncarnation,
|
||||
int maxOperations, long maxRegistryBytes, long maxWriteBytes, int maxPhysicalWrites, TimeSpan retention)
|
||||
{
|
||||
if (!ReferenceEquals(authority.DispatchFence, catalog.DispatchFence)
|
||||
|| !ReferenceEquals(authority.DispatchFence, activation.DispatchFence)
|
||||
|| !ReferenceEquals(authority.DispatchFence, role.DispatchFence) || !policy.UsesAuthority(authority)
|
||||
|| capabilities.Serving.Incarnation != servingIncarnation)
|
||||
throw new ArgumentException("Rich write publishers must share one fence and authority.");
|
||||
_catalog = catalog; _policy = policy; _capabilities = capabilities; _role = role; _clock = clock; _bounds = bounds;
|
||||
Routes = new(authority.DispatchFence);
|
||||
Gate = new DataWriteDispatchGate(catalog, activation, authority, policy, role, Routes, clock, bounds);
|
||||
Observer = new(maxPhysicalWrites, retention, clock);
|
||||
_registry = new(servingIncarnation, maxOperations, maxRegistryBytes, retention, clock);
|
||||
_values = new(maxWriteBytes);
|
||||
}
|
||||
|
||||
internal bool MatchesHost(LocalCatalogCoordinator? coordinator, IDriverPrimaryRoleSource? role,
|
||||
TimeProvider clock, DriverWriteBounds bounds) => ReferenceEquals(_catalog, coordinator)
|
||||
&& ReferenceEquals(_role, role) && ReferenceEquals(_clock, clock) && _bounds == bounds;
|
||||
|
||||
/// <summary>Creates an executor for an authenticated transport context and this node's driver host.</summary>
|
||||
public IDataWriteService ForCaller(DataAuthenticatedContext context, Func<IActorRef?> resolveHost) =>
|
||||
new DataWriteExecutor(context, () => _catalog.Current, _policy, _capabilities,
|
||||
new ActorDataWriteRoute(resolveHost, Routes, _role, _bounds, _clock), _registry, _values, _clock, _bounds);
|
||||
}
|
||||
|
||||
internal sealed class ActorDataWriteRoute(Func<IActorRef?> resolveHost, WriteRouteState routes,
|
||||
RedundancyRoleView role, DriverWriteBounds bounds, TimeProvider? clock = null) : IDataWriteRoute
|
||||
{
|
||||
public bool TryResolve(DataView view, out WriteRouteTarget? target)
|
||||
{
|
||||
if (!routes.TryResolve(view, out var found) || found is null || role.PrimaryGeneration <= 0)
|
||||
{ target = null; return false; }
|
||||
target = found with { PrimaryGeneration = role.PrimaryGeneration };
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
|
||||
{
|
||||
var host = resolveHost();
|
||||
if (host is null)
|
||||
{
|
||||
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Driver host unavailable.");
|
||||
if (claim.Complete(rejected)) ticket.Dispose();
|
||||
return claim.CurrentOutcome ?? rejected;
|
||||
}
|
||||
try
|
||||
{
|
||||
using var deadline = new CancellationTokenSource(bounds.GatewayAsk, clock ?? TimeProvider.System);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token, ct);
|
||||
return await host.Ask<DataWriteOutcome>(new DriverHostActor.RouteRichWrite(ticket, claim),
|
||||
Timeout.InfiniteTimeSpan, linked.Token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Route timed out before dispatch.");
|
||||
if (claim.Complete(rejected)) { ticket.Dispose(); return rejected; }
|
||||
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Route outcome unknown.");
|
||||
claim.Complete(unknown);
|
||||
return claim.CurrentOutcome ?? unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Limits physical outstanding driver operations, including token-ignoring operations.</summary>
|
||||
public sealed class LateWriteObserver
|
||||
{
|
||||
private readonly int _maxOutstanding;
|
||||
private readonly TimeSpan _retention;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<(string Driver, string Reference), LateWriteReservation> _targets = new(new TargetComparer());
|
||||
private int _outstanding;
|
||||
|
||||
public LateWriteObserver(int maxOutstanding, TimeSpan retention, TimeProvider? clock = null)
|
||||
{
|
||||
if (maxOutstanding <= 0 || retention <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maxOutstanding));
|
||||
_maxOutstanding = maxOutstanding;
|
||||
_retention = retention;
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
public bool TryReserve(out LateWriteReservation? reservation)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_outstanding >= _maxOutstanding) { reservation = null; return false; }
|
||||
reservation = new LateWriteReservation(this, _retention, _clock, null);
|
||||
_outstanding++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reserves both a global slot and the exact backing target until physical completion.</summary>
|
||||
public bool TryReserve(string driverInstanceId, string driverReference, out LateWriteReservation? reservation)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(driverReference);
|
||||
var target = (driverInstanceId, driverReference);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_outstanding >= _maxOutstanding || _targets.ContainsKey(target))
|
||||
{
|
||||
reservation = null;
|
||||
return false;
|
||||
}
|
||||
reservation = new LateWriteReservation(this, _retention, _clock, target);
|
||||
_targets.Add(target, reservation);
|
||||
_outstanding++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Release(LateWriteReservation reservation, (string Driver, string Reference)? target)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (target is { } key)
|
||||
{
|
||||
if (!_targets.TryGetValue(key, out var owner) || !ReferenceEquals(owner, reservation)) return;
|
||||
_targets.Remove(key);
|
||||
}
|
||||
_outstanding--;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TargetComparer : IEqualityComparer<(string Driver, string Reference)>
|
||||
{
|
||||
public bool Equals((string Driver, string Reference) x, (string Driver, string Reference) y) =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(x.Driver, y.Driver) && StringComparer.Ordinal.Equals(x.Reference, y.Reference);
|
||||
public int GetHashCode((string Driver, string Reference) key) =>
|
||||
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(key.Driver), StringComparer.Ordinal.GetHashCode(key.Reference));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A reservation transfers the physical permit and optional resources to the raw task.</summary>
|
||||
public sealed class LateWriteReservation : IDisposable
|
||||
{
|
||||
private readonly LateWriteObserver _owner;
|
||||
private readonly TimeSpan _retention;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly (string Driver, string Reference)? _target;
|
||||
// 0 reserved, 1 transferred, 2 released.
|
||||
private int _state;
|
||||
|
||||
internal LateWriteReservation(LateWriteObserver owner, TimeSpan retention, TimeProvider clock,
|
||||
(string Driver, string Reference)? target)
|
||||
{ _owner = owner; _retention = retention; _clock = clock; _target = target; }
|
||||
|
||||
public void Observe(Task<DataWriteOutcome> actualDriverTask, WriteClaim claim, IDisposable? lifetime = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(actualDriverTask);
|
||||
ArgumentNullException.ThrowIfNull(claim);
|
||||
if (Interlocked.CompareExchange(ref _state, 1, 0) != 0) throw new InvalidOperationException("Reservation already consumed.");
|
||||
var started = _clock.GetTimestamp();
|
||||
_ = ObserveCore(actualDriverTask, claim, lifetime, started);
|
||||
}
|
||||
|
||||
private async Task ObserveCore(Task<DataWriteOutcome> task, WriteClaim claim, IDisposable? lifetime, long started)
|
||||
{
|
||||
try
|
||||
{
|
||||
DataWriteOutcome outcome;
|
||||
try { outcome = await task.ConfigureAwait(false); }
|
||||
catch { outcome = new(DataWriteState.OutcomeUnknown, 0, "Driver completion failed or was canceled."); }
|
||||
if (_clock.GetElapsedTime(started, _clock.GetTimestamp()) < _retention)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!claim.Complete(outcome)) claim.LateRefine(outcome);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
claim.Complete(new(DataWriteState.OutcomeUnknown, 0, "Invalid driver outcome."));
|
||||
}
|
||||
}
|
||||
else claim.Complete(new(DataWriteState.OutcomeUnknown, 0, "Late-result retention expired."));
|
||||
}
|
||||
finally
|
||||
{
|
||||
claim.PhysicalFinished();
|
||||
try { lifetime?.Dispose(); }
|
||||
finally { Interlocked.Exchange(ref _state, 2); _owner.Release(this, _target); }
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _state, 2, 0) == 0) _owner.Release(this, _target);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@ public sealed record CatalogAttempt(long Epoch, string Revision)
|
||||
/// <summary>Coordinates desired authority, private catalog staging and served topology activation.</summary>
|
||||
public sealed class LocalCatalogCoordinator
|
||||
{
|
||||
public DataWriteDispatchFence DispatchFence => _activation.DispatchFence;
|
||||
internal bool IsPublished(LocalExportCatalog catalog) => ReferenceEquals(Volatile.Read(ref _published), catalog);
|
||||
internal IReadOnlyList<LocalDataNode> StagedNodes => Volatile.Read(ref _staged)?.Nodes ?? [];
|
||||
private readonly object _gate = new();
|
||||
private readonly CatalogActivation _activation;
|
||||
private readonly DataPlaneAuthorityState _authority;
|
||||
@@ -56,8 +59,12 @@ public sealed class LocalCatalogCoordinator
|
||||
return catalog.IsActive ? catalog : null;
|
||||
}
|
||||
var adjusted = catalog.WithServingRole(catalog.Serving with { Role = current.Role });
|
||||
if (ReferenceEquals(Interlocked.CompareExchange(ref _published, adjusted, catalog), catalog))
|
||||
continue;
|
||||
// Acquisition callers must not wait behind a write-commit or authority publisher.
|
||||
// Serving will return provisional zero epochs if the role wrapper cannot be refreshed.
|
||||
if (!DispatchFence.TryEnter(out var lease)) return null;
|
||||
using (lease)
|
||||
if (ReferenceEquals(Interlocked.CompareExchange(ref _published, adjusted, catalog), catalog))
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -82,7 +89,7 @@ public sealed class LocalCatalogCoordinator
|
||||
_staged = null;
|
||||
_terminal = false;
|
||||
_catalogValid = false;
|
||||
Volatile.Write(ref _published, null);
|
||||
using (DispatchFence.Enter()) Volatile.Write(ref _published, null);
|
||||
return attempt;
|
||||
}
|
||||
}
|
||||
@@ -134,10 +141,10 @@ public sealed class LocalCatalogCoordinator
|
||||
var state = _activation.Current;
|
||||
var valid = topologySucceeded && _staged is not null && _catalogValid
|
||||
&& state.AuthorityEpoch == _authority.Current.GenerationId;
|
||||
if (valid) Volatile.Write(ref _published, _staged);
|
||||
if (valid) { using (DispatchFence.Enter()) Volatile.Write(ref _published, _staged); }
|
||||
if (!_activation.Complete(attempt.Epoch, valid))
|
||||
{
|
||||
Volatile.Write(ref _published, null);
|
||||
using (DispatchFence.Enter()) Volatile.Write(ref _published, null);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
using System.Collections.Immutable;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
internal sealed record FrozenWriteScope(string ClusterId, NodeHierarchyKind Kind, ImmutableArray<string> Segments);
|
||||
internal sealed record WriteRouteTarget(string DriverInstanceId, string DriverReference, string DriverIncarnation,
|
||||
long RouteGeneration, long PrimaryGeneration);
|
||||
internal sealed record WriteRouteProof(DataWriteAdmission Admission, FrozenWriteScope Scope, string EntityKind,
|
||||
string EntityId, BackingSourceKey? Source, string DriverInstanceId, string DriverReference,
|
||||
long RouteGeneration, long PrimaryGeneration);
|
||||
|
||||
/// <summary>Owns the value and its byte charge until rejection or actual driver completion.</summary>
|
||||
internal sealed class WriteAdmissionTicket : IDisposable
|
||||
{
|
||||
private IDisposable? _byteLease;
|
||||
private int _disposed;
|
||||
public WriteAdmissionTicket(WriteRouteProof proof, DataValue value, long issuedAt, IDisposable? byteLease = null)
|
||||
{ Proof = proof; Value = value; IssuedAt = issuedAt; _byteLease = byteLease; }
|
||||
public WriteRouteProof Proof { get; }
|
||||
public DataValue Value { get; }
|
||||
public long IssuedAt { get; }
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
try { Value.Dispose(); }
|
||||
finally { Interlocked.Exchange(ref _byteLease, null)?.Dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
internal interface IWriteDispatchGate
|
||||
{
|
||||
DataWriteOutcome? TryCommit(WriteAdmissionTicket ticket, WriteClaim claim);
|
||||
}
|
||||
|
||||
internal interface IDataWriteRoute
|
||||
{
|
||||
bool TryResolve(DataView view, out WriteRouteTarget? target);
|
||||
Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Immutable, fenced route and physical actor-lifetime snapshots.</summary>
|
||||
internal sealed class WriteRouteState(DataWriteDispatchFence fence)
|
||||
{
|
||||
private sealed record Snapshot(long Generation, ImmutableDictionary<DataView, WriteRouteTarget> Routes,
|
||||
ImmutableDictionary<string, string> Drivers);
|
||||
private Snapshot _current = new(0, ImmutableDictionary<DataView, WriteRouteTarget>.Empty,
|
||||
ImmutableDictionary<string, string>.Empty.WithComparers(StringComparer.Ordinal));
|
||||
public DataWriteDispatchFence DispatchFence => fence;
|
||||
public string? CurrentDriverIncarnation(string driver) => Volatile.Read(ref _current).Drivers.GetValueOrDefault(driver);
|
||||
|
||||
public string BeginDriverIncarnation(string driver)
|
||||
{
|
||||
var incarnation = Guid.NewGuid().ToString("N");
|
||||
Update(s =>
|
||||
{
|
||||
var generation = checked(s.Generation + 1);
|
||||
var routes = s.Routes;
|
||||
foreach (var pair in s.Routes)
|
||||
if (pair.Value.DriverInstanceId == driver)
|
||||
routes = routes.SetItem(pair.Key, pair.Value with { DriverIncarnation = incarnation, RouteGeneration = generation });
|
||||
return s with { Generation = generation, Drivers = s.Drivers.SetItem(driver, incarnation), Routes = routes };
|
||||
});
|
||||
return incarnation;
|
||||
}
|
||||
|
||||
public void RetireDriver(string driver, string incarnation) => Update(s =>
|
||||
s.Drivers.TryGetValue(driver, out var current) && current == incarnation
|
||||
? s with { Generation = checked(s.Generation + 1), Drivers = s.Drivers.Remove(driver) } : s);
|
||||
|
||||
public void ReplaceRoutes(IEnumerable<(DataView View, string Driver, string Reference)> desired)
|
||||
{
|
||||
var items = desired.ToArray();
|
||||
Update(s =>
|
||||
{
|
||||
var generation = checked(s.Generation + 1);
|
||||
var next = ImmutableDictionary.CreateBuilder<DataView, WriteRouteTarget>();
|
||||
foreach (var (view, driver, reference) in items)
|
||||
{
|
||||
var incarnation = s.Drivers.GetValueOrDefault(driver) ?? string.Empty;
|
||||
if (!next.TryAdd(view, new(driver, reference, incarnation, generation, 0)))
|
||||
throw new InvalidOperationException("Duplicate write view.");
|
||||
}
|
||||
var same = next.Count == s.Routes.Count && next.All(pair => s.Routes.TryGetValue(pair.Key, out var old)
|
||||
&& old.DriverInstanceId == pair.Value.DriverInstanceId && old.DriverReference == pair.Value.DriverReference
|
||||
&& old.DriverIncarnation == pair.Value.DriverIncarnation);
|
||||
return same ? s : s with { Generation = generation, Routes = next.ToImmutable() };
|
||||
});
|
||||
}
|
||||
|
||||
public WriteRouteTarget Publish(DataView view, string driver, string reference, string incarnation)
|
||||
{
|
||||
WriteRouteTarget? result = null;
|
||||
Update(s =>
|
||||
{
|
||||
if (s.Routes.TryGetValue(view, out var existing) && existing.DriverInstanceId == driver
|
||||
&& existing.DriverReference == reference && existing.DriverIncarnation == incarnation
|
||||
&& s.Drivers.TryGetValue(driver, out var active) && active == incarnation)
|
||||
{ result = existing; return s; }
|
||||
var next = checked(s.Generation + 1);
|
||||
result = new(driver, reference, incarnation, next, 0);
|
||||
return s with { Generation = next, Routes = s.Routes.SetItem(view, result),
|
||||
Drivers = s.Drivers.ContainsKey(driver) ? s.Drivers : s.Drivers.Add(driver, incarnation) };
|
||||
});
|
||||
return result!;
|
||||
}
|
||||
|
||||
public bool TryResolve(DataView view, out WriteRouteTarget? target)
|
||||
{
|
||||
var current = Volatile.Read(ref _current);
|
||||
if (current.Routes.TryGetValue(view, out var found) && current.Drivers.TryGetValue(found.DriverInstanceId, out var incarnation)
|
||||
&& incarnation == found.DriverIncarnation) { target = found; return true; }
|
||||
target = null; return false;
|
||||
}
|
||||
public bool IsCurrent(DataView view, WriteRouteTarget target) => TryResolve(view, out var current)
|
||||
&& current == (target with { PrimaryGeneration = current!.PrimaryGeneration });
|
||||
|
||||
private void Update(Func<Snapshot, Snapshot> prepare)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var before = Volatile.Read(ref _current);
|
||||
var after = prepare(before);
|
||||
using (fence.Enter())
|
||||
{
|
||||
if (!ReferenceEquals(before, _current)) continue;
|
||||
Volatile.Write(ref _current, after);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
public enum WriteClaimKind { Owner, Existing, Conflict, Stale, Capacity }
|
||||
|
||||
public sealed record WriteClaimResult(WriteClaimKind Kind, WriteClaim? Claim = null);
|
||||
|
||||
/// <summary>Bounded, incarnation-local duplicate protection. Payload storage is owned by the executor.</summary>
|
||||
public sealed class WriteOperationRegistry
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<(string Principal, string Operation), Entry> _entries = new(new KeyComparer());
|
||||
private readonly string _incarnation;
|
||||
private readonly int _maxEntries;
|
||||
private readonly long _maxBytes;
|
||||
private readonly TimeSpan _retention;
|
||||
private readonly TimeProvider _clock;
|
||||
private long _retainedBytes;
|
||||
|
||||
public WriteOperationRegistry(string servingIncarnation, int maxEntries, long maxRetainedBytes,
|
||||
TimeSpan retention, TimeProvider? clock = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation);
|
||||
if (maxEntries <= 0 || maxRetainedBytes <= 0 || retention <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(maxEntries));
|
||||
_incarnation = servingIncarnation;
|
||||
_maxEntries = maxEntries;
|
||||
_maxBytes = maxRetainedBytes;
|
||||
_retention = retention;
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
public WriteClaimResult Claim(string principal, string operationId, string expectedServingIncarnation,
|
||||
ReadOnlyMemory<byte> semanticHash)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(operationId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(expectedServingIncarnation);
|
||||
if (semanticHash.Length != 32) throw new ArgumentException("A SHA-256 hash is required.", nameof(semanticHash));
|
||||
if (!StringComparer.Ordinal.Equals(_incarnation, expectedServingIncarnation)) return new(WriteClaimKind.Stale);
|
||||
var bytes = 256L + 2L * principal.Length + 2L * operationId.Length + semanticHash.Length;
|
||||
lock (_gate)
|
||||
{
|
||||
Prune();
|
||||
var key = (principal, operationId);
|
||||
if (_entries.TryGetValue(key, out var existing))
|
||||
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
|
||||
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
|
||||
if (_entries.Count >= _maxEntries || bytes > _maxBytes - _retainedBytes)
|
||||
return new(WriteClaimKind.Capacity);
|
||||
var claim = new WriteClaim(_clock);
|
||||
_entries.Add(key, new Entry(semanticHash.ToArray(), claim, bytes));
|
||||
_retainedBytes += bytes;
|
||||
return new(WriteClaimKind.Owner, claim);
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune()
|
||||
{
|
||||
var now = _clock.GetTimestamp();
|
||||
foreach (var pair in _entries.ToArray())
|
||||
{
|
||||
if (!pair.Value.Claim.CanRetire(now, _retention)) continue;
|
||||
_entries.Remove(pair.Key);
|
||||
_retainedBytes -= pair.Value.Bytes;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Entry(byte[] Hash, WriteClaim Claim, long Bytes);
|
||||
private sealed class KeyComparer : IEqualityComparer<(string Principal, string Operation)>
|
||||
{
|
||||
public bool Equals((string Principal, string Operation) x, (string Principal, string Operation) y) =>
|
||||
StringComparer.OrdinalIgnoreCase.Equals(x.Principal, y.Principal) &&
|
||||
StringComparer.Ordinal.Equals(x.Operation, y.Operation);
|
||||
|
||||
public int GetHashCode((string Principal, string Operation) key) =>
|
||||
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(key.Principal),
|
||||
StringComparer.Ordinal.GetHashCode(key.Operation));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One shared operation. Dispatch and rejection compete through a lock-free transition.</summary>
|
||||
public sealed class WriteClaim
|
||||
{
|
||||
// 0 pending, 1 dispatched, 2/3 completing before/after dispatch, 4/5 completed before/after dispatch.
|
||||
private int _state;
|
||||
private int _physicalFinished;
|
||||
private long _completedTimestamp;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly object _outcomeGate = new();
|
||||
private DataWriteOutcome? _outcome;
|
||||
private readonly TaskCompletionSource<DataWriteOutcome> _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
internal WriteClaim(TimeProvider clock) => _clock = clock;
|
||||
public Task<DataWriteOutcome> Completion => _completion.Task;
|
||||
public bool IsDispatched => Volatile.Read(ref _state) is 1 or 3 or 5;
|
||||
public DataWriteOutcome? CurrentOutcome => Volatile.Read(ref _outcome);
|
||||
|
||||
public bool TryMarkDispatched() => Interlocked.CompareExchange(ref _state, 1, 0) == 0;
|
||||
|
||||
public bool Complete(DataWriteOutcome outcome)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(outcome);
|
||||
outcome.Validate();
|
||||
while (true)
|
||||
{
|
||||
var state = Volatile.Read(ref _state);
|
||||
if (state is not (0 or 1)) return false;
|
||||
if ((state == 0) != (outcome.State == DataWriteState.RejectedBeforeDispatch)) return false;
|
||||
if (Interlocked.CompareExchange(ref _state, state + 2, state) != state) continue;
|
||||
lock (_outcomeGate)
|
||||
{
|
||||
Volatile.Write(ref _outcome, outcome);
|
||||
_completedTimestamp = _clock.GetTimestamp();
|
||||
Volatile.Write(ref _state, state + 4);
|
||||
_completion.TrySetResult(outcome);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool LateRefine(DataWriteOutcome outcome)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(outcome);
|
||||
outcome.Validate();
|
||||
if (outcome.State is not (DataWriteState.DriverConfirmedSuccess or DataWriteState.DriverConfirmedFailure)) return false;
|
||||
lock (_outcomeGate)
|
||||
{
|
||||
if (_outcome?.State is not (DataWriteState.OutcomeUnknown or DataWriteState.AcceptedUnconfirmed)) return false;
|
||||
Volatile.Write(ref _completedTimestamp, _clock.GetTimestamp());
|
||||
Volatile.Write(ref _outcome, outcome);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal void PhysicalFinished() => Volatile.Write(ref _physicalFinished, 1);
|
||||
|
||||
internal bool CanRetire(long now, TimeSpan retention)
|
||||
{
|
||||
var state = Volatile.Read(ref _state);
|
||||
return state is 4 or 5 && (state == 4 || Volatile.Read(ref _physicalFinished) != 0)
|
||||
&& _clock.GetElapsedTime(Volatile.Read(ref _completedTimestamp), now) >= retention;
|
||||
}
|
||||
}
|
||||
@@ -21,11 +21,13 @@ using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
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.ScriptedAlarms;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry;
|
||||
@@ -186,6 +188,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
private readonly CommonsNodeId _localNode;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? _catalogCoordinator;
|
||||
private readonly DataWriteRuntime? _dataWriteRuntime;
|
||||
private ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.CatalogAttempt? _catalogAttempt;
|
||||
private readonly IActorRef? _ackRouter;
|
||||
private readonly IDriverFactory _driverFactory;
|
||||
@@ -619,6 +622,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <param name="Success">True when the driver accepted the write.</param>
|
||||
/// <param name="Reason">Failure detail when <paramref name="Success"/> is false; null on success.</param>
|
||||
public sealed record NodeWriteResult(bool Success, string? Reason);
|
||||
internal sealed record RouteRichWrite(WriteAdmissionTicket Ticket, WriteClaim Claim);
|
||||
|
||||
/// <summary>
|
||||
/// Routes an inbound native-condition acknowledge to the owning driver child. The host wires the
|
||||
@@ -796,7 +800,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
TimeSpan? childShutdownTimeout = null,
|
||||
bool enforceSnapshotOrdering = false,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
|
||||
DataWriteRuntime? dataWriteRuntime = null) =>
|
||||
// WARNING: this forwarding list is POSITIONAL, and Props.Create compiles it into an
|
||||
// expression tree. Six IActorRef? parameters and several interface-typed ones mean a
|
||||
// mis-ordered argument is usually type-compatible and therefore compiles clean, then binds
|
||||
@@ -811,7 +816,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
|
||||
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
|
||||
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
|
||||
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator));
|
||||
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime));
|
||||
|
||||
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
|
||||
/// <param name="dbFactory">Database context factory for configuration database access.</param>
|
||||
@@ -949,8 +954,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
TimeSpan? childShutdownTimeout = null,
|
||||
bool enforceSnapshotOrdering = false,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null,
|
||||
DataWriteRuntime? dataWriteRuntime = null)
|
||||
{
|
||||
_dataWriteRuntime = dataWriteRuntime;
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_catalogCoordinator = catalogCoordinator;
|
||||
_snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null;
|
||||
@@ -958,6 +965,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
_scriptedAlarmRunner = scriptedAlarmRunner;
|
||||
_writeBounds = writeBounds ?? DriverWriteBounds.Default;
|
||||
_writeClock = writeClock ?? TimeProvider.System;
|
||||
if (_dataWriteRuntime is not null && !_dataWriteRuntime.MatchesHost(_catalogCoordinator, primaryRoleSource, _writeClock, _writeBounds))
|
||||
throw new ArgumentException("Rich writes require the host's exact catalog, role, clock and bounds.", nameof(dataWriteRuntime));
|
||||
_ackPreflightView = ackPreflightView;
|
||||
_scripting = scripting;
|
||||
_captureWhilePrimaryUnreachable = captureWhilePrimaryUnreachable;
|
||||
@@ -1061,8 +1070,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// </summary>
|
||||
private void StartPrimaryVerdictPublishing()
|
||||
{
|
||||
PublishHistoryUpdateVerdict();
|
||||
if (_primaryRoleSource is null) return;
|
||||
if (_primaryRoleSource is null) { PublishHistoryUpdateVerdict(); return; }
|
||||
PublishPrimaryVerdict();
|
||||
try
|
||||
{
|
||||
@@ -1086,13 +1094,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// node's new incarnation. A REMOVED member deliberately stays in the set: it never answers again, and
|
||||
// dropping it would re-derive the verdict from a cached snapshot that may still name it Primary,
|
||||
// closing the gate on a dead node until the next snapshot (the very hole the reachability tracking closes).
|
||||
if (evt is Akka.Cluster.ClusterEvent.MemberUp up
|
||||
&& _unreachableNodes.Remove(ToNodeId(up.Member.Address)))
|
||||
{
|
||||
RepublishHistorizationVerdictIfChanged();
|
||||
}
|
||||
|
||||
var becameReachable = evt is Akka.Cluster.ClusterEvent.MemberUp up
|
||||
&& _unreachableNodes.Remove(ToNodeId(up.Member.Address));
|
||||
PublishPrimaryVerdictIfChanged();
|
||||
if (becameReachable) RepublishHistorizationVerdictIfChanged();
|
||||
// One keyed timer: a burst of member events collapses into a single deferred pass.
|
||||
Timers.StartSingleTimer("republish-primary-verdict", RepublishPrimaryVerdict.Instance, MembershipRepublishDelay);
|
||||
}
|
||||
@@ -1101,20 +1106,23 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// The snapshot path publishes on every snapshot, as the other verdicts do.</summary>
|
||||
private void PublishPrimaryVerdict()
|
||||
{
|
||||
if (_primaryRoleSource is not null)
|
||||
{
|
||||
var verdict = ShouldServiceAsPrimary();
|
||||
_lastPublishedPrimaryVerdict = verdict;
|
||||
_primaryRoleSource.PublishPrimaryRole(verdict);
|
||||
}
|
||||
PublishHistoryUpdateVerdict();
|
||||
if (_primaryRoleSource is null) return;
|
||||
var verdict = ShouldServiceAsPrimary();
|
||||
_lastPublishedPrimaryVerdict = verdict;
|
||||
_primaryRoleSource.PublishPrimaryRole(verdict);
|
||||
}
|
||||
|
||||
/// <summary>The membership path publishes only a CHANGED verdict — member events are frequent and carry no
|
||||
/// role information, so republishing an unchanged verdict on each would be noise.</summary>
|
||||
private void PublishPrimaryVerdictIfChanged()
|
||||
{
|
||||
PublishHistoryUpdateVerdict();
|
||||
if (_primaryRoleSource is null || ShouldServiceAsPrimary() == _lastPublishedPrimaryVerdict) return;
|
||||
PublishPrimaryVerdict();
|
||||
if (_primaryRoleSource is not null && ShouldServiceAsPrimary() != _lastPublishedPrimaryVerdict)
|
||||
PublishPrimaryVerdict();
|
||||
else
|
||||
PublishHistoryUpdateVerdict();
|
||||
}
|
||||
|
||||
/// <summary>Publishes <see cref="PrimaryGatePolicy.ShouldServeHistoryUpdate"/> (no-op when no view
|
||||
@@ -1654,6 +1662,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
Receive<ReprovisionDeferred>(m => ReprovisionChild(m.Request, m.Child));
|
||||
Receive<ReconnectDriver>(HandleReconnectDriver);
|
||||
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
|
||||
Receive<RouteRichWrite>(HandleRouteRichWrite);
|
||||
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
|
||||
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
|
||||
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
|
||||
@@ -1719,6 +1728,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
Receive<ReprovisionDeferred>(m => ReprovisionChild(m.Request, m.Child));
|
||||
Receive<ReconnectDriver>(HandleReconnectDriver);
|
||||
Receive<RouteNodeWrite>(HandleRouteNodeWrite);
|
||||
Receive<RouteRichWrite>(HandleRouteRichWrite);
|
||||
Receive<RouteNativeAlarmAck>(HandleRouteNativeAlarmAck);
|
||||
Receive<DriverInstanceActor.AlarmAckFailed>(HandleAlarmAckFailed);
|
||||
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
|
||||
@@ -2368,6 +2378,40 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
.PipeTo(replyTo);
|
||||
}
|
||||
|
||||
private static void RejectRichRoute(RouteRichWrite msg, IActorRef replyTo, string reason)
|
||||
{
|
||||
var rejection = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x80310000u, reason);
|
||||
if (msg.Claim.Complete(rejection)) msg.Ticket.Dispose();
|
||||
replyTo.Tell(msg.Claim.CurrentOutcome ?? new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown."));
|
||||
}
|
||||
|
||||
private void HandleRouteRichWrite(RouteRichWrite msg)
|
||||
{
|
||||
var proof = msg.Ticket.Proof;
|
||||
if (_dataWriteRuntime is null || !ShouldServiceAsPrimary())
|
||||
{ RejectRichRoute(msg, Sender, "Write route unavailable."); return; }
|
||||
var realm = proof.Admission.View.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
|
||||
var nodeId = proof.Admission.View.Address.Identifier;
|
||||
if (!_driverRefByNodeId.TryGetValue((realm, nodeId), out var target)
|
||||
|| target.DriverInstanceId != proof.DriverInstanceId || target.RawPath != proof.DriverReference
|
||||
|| !_children.TryGetValue(target.DriverInstanceId, out var child))
|
||||
{ RejectRichRoute(msg, Sender, "Driver route changed."); return; }
|
||||
var replyTo = Sender;
|
||||
var deadline = new CancellationTokenSource(_writeBounds.HostAsk, _writeClock);
|
||||
child.Actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(msg.Ticket, msg.Claim),
|
||||
System.Threading.Timeout.InfiniteTimeSpan, deadline.Token)
|
||||
.ContinueWith(t =>
|
||||
{
|
||||
deadline.Dispose();
|
||||
if (t.IsCompletedSuccessfully) return t.Result;
|
||||
var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Driver route expired before dispatch.");
|
||||
if (msg.Claim.Complete(rejected)) { msg.Ticket.Dispose(); return rejected; }
|
||||
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0x800A0000u, "Driver outcome unknown.");
|
||||
msg.Claim.Complete(unknown);
|
||||
return msg.Claim.CurrentOutcome ?? unknown;
|
||||
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).PipeTo(replyTo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalise an OPC UA NodeId string to its BARE <c>s=</c> identifier. The node manager's inbound-write
|
||||
/// hook passes the full ns-qualified form (<c>NodeId.ToString()</c> == <c>"ns=<N>;s=<id>"</c>);
|
||||
@@ -2608,6 +2652,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
_localNode, string.Join(",", msg.Nodes.Select(n => n.NodeId)));
|
||||
}
|
||||
|
||||
// Publish the write fence before independent alarm/history callbacks can block this mailbox.
|
||||
PublishPrimaryVerdict();
|
||||
|
||||
// Publish on EVERY snapshot, including ones that leave the cached role untouched, so a role
|
||||
// that changes without this node being named still reaches the drain within one heartbeat.
|
||||
//
|
||||
@@ -2637,11 +2684,6 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
_historizationRoleView.PublishHistorizationRole(historizationVerdict);
|
||||
}
|
||||
|
||||
// The DATA-PLANE verdict, deliberately — the same one HandleRouteNodeWrite gates on, not the
|
||||
// drain verdict published immediately above. A driver reading this claims an exclusive identity
|
||||
// on a shared external system (the Sparkplug host id), where two claimants is the
|
||||
// harm, so an unknown role with a driver peer present must deny.
|
||||
PublishPrimaryVerdict();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -2743,6 +2785,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// node-manager's bounded Ask gets an immediate clear status instead of dead-lettering into a timeout.
|
||||
Receive<RouteNodeWrite>(_ =>
|
||||
Sender.Tell(new NodeWriteResult(false, "driver host stale (config DB unreachable)")));
|
||||
Receive<RouteRichWrite>(msg => RejectRichRoute(msg, Sender, "Driver host unavailable."));
|
||||
// An inbound native-condition ack can't be serviced while Stale either (the alarm inverse map is
|
||||
// empty until an apply runs). The node manager's pre-check refuses it synchronously while Stale (see the
|
||||
// top of this method); one that raced that refusal is dropped here with a log.
|
||||
@@ -3902,6 +3945,19 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
}
|
||||
|
||||
if (_dataWriteRuntime is not null && _catalogCoordinator is not null)
|
||||
{
|
||||
var mapped = new List<(DataView View, string Driver, string Reference)>();
|
||||
foreach (var node in _catalogCoordinator.StagedNodes)
|
||||
{
|
||||
var view = node.Metadata.View;
|
||||
var realm = view.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns;
|
||||
if (_driverRefByNodeId.TryGetValue((realm, view.Address.Identifier), out var target))
|
||||
mapped.Add((view, target.DriverInstanceId, target.RawPath));
|
||||
}
|
||||
_dataWriteRuntime.Routes.ReplaceRoutes(mapped);
|
||||
}
|
||||
|
||||
if (previousSourceRefs is not null)
|
||||
foreach (var previous in previousSourceRefs)
|
||||
if (!_nodeIdByDriverRef.ContainsKey(previous))
|
||||
@@ -4052,12 +4108,17 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
if (stub)
|
||||
{
|
||||
child = Context.ActorOf(
|
||||
DriverInstanceActor.Props(
|
||||
_dataWriteRuntime is null ? DriverInstanceActor.Props(
|
||||
new StubbedDriver(spec.DriverInstanceId, spec.DriverType),
|
||||
reconnectInterval: null,
|
||||
startStubbed: true,
|
||||
healthPublisher: _healthPublisher,
|
||||
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
|
||||
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation)
|
||||
: DriverInstanceActor.PropsForRichWrites(new StubbedDriver(spec.DriverInstanceId, spec.DriverType),
|
||||
startStubbed: true, healthPublisher: _healthPublisher, clusterId: clusterId,
|
||||
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation,
|
||||
writeDispatchGate: _dataWriteRuntime.Gate, lateWriteObserver: _dataWriteRuntime.Observer,
|
||||
writeRouteState: _dataWriteRuntime.Routes),
|
||||
actorName);
|
||||
}
|
||||
else
|
||||
@@ -4068,7 +4129,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// no-op invoker on nodes without the real resilience factory bound.
|
||||
var invoker = _invokerFactory.Create(spec.DriverInstanceId, spec.DriverType, spec.ResilienceConfig);
|
||||
child = Context.ActorOf(
|
||||
DriverInstanceActor.Props(
|
||||
_dataWriteRuntime is null ? DriverInstanceActor.Props(
|
||||
driver!,
|
||||
healthPublisher: _healthPublisher,
|
||||
clusterId: clusterId,
|
||||
@@ -4076,7 +4137,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
writeTimeout: _writeBounds.Timeout,
|
||||
writeClock: _writeClock,
|
||||
shutdownTimeout: _childShutdownTimeout,
|
||||
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
|
||||
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation)
|
||||
: DriverInstanceActor.PropsForRichWrites(driver!, healthPublisher: _healthPublisher, clusterId: clusterId,
|
||||
invoker: invoker, writeTimeout: _writeBounds.Timeout, writeClock: _writeClock,
|
||||
shutdownTimeout: _childShutdownTimeout, sourcePublisher: _sourcePublisher,
|
||||
sourceIncarnation: sourceIncarnation, writeDispatchGate: _dataWriteRuntime.Gate,
|
||||
lateWriteObserver: _dataWriteRuntime.Observer, writeRouteState: _dataWriteRuntime.Routes),
|
||||
actorName);
|
||||
child.Tell(new DriverInstanceActor.InitializeRequested(spec.DriverConfig));
|
||||
}
|
||||
@@ -4137,12 +4203,21 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
Context.Stop(adapter);
|
||||
}
|
||||
|
||||
private void RetireWriteIncarnation(string driverInstanceId)
|
||||
{
|
||||
var routes = _dataWriteRuntime?.Routes;
|
||||
var incarnation = routes?.CurrentDriverIncarnation(driverInstanceId);
|
||||
if (incarnation is not null) routes!.RetireDriver(driverInstanceId, incarnation);
|
||||
}
|
||||
|
||||
private void StopChild(string driverInstanceId)
|
||||
{
|
||||
if (!_children.TryGetValue(driverInstanceId, out var entry)) return;
|
||||
StopDependencyAdapter(driverInstanceId);
|
||||
_sourcePublisher?.RetireCurrentDriver(driverInstanceId);
|
||||
RetireChild(entry.Actor);
|
||||
RetireWriteIncarnation(driverInstanceId);
|
||||
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(driverInstanceId);
|
||||
PublishAckPreflight();
|
||||
@@ -4262,6 +4337,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
StopDependencyAdapter(msg.DriverInstanceId);
|
||||
_sourcePublisher?.RetireCurrentDriver(msg.DriverInstanceId);
|
||||
RetireChild(entry.Actor);
|
||||
RetireWriteIncarnation(msg.DriverInstanceId);
|
||||
_dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(msg.DriverInstanceId);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(msg.DriverInstanceId);
|
||||
// An operator Restart builds a NEW driver object, so the old one's retained values are evicted like a
|
||||
|
||||
@@ -6,6 +6,8 @@ using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
|
||||
@@ -71,6 +73,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// when the host's Ask fires (lmxopcua#777).</param>
|
||||
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null);
|
||||
public sealed record WriteAttributeResult(bool Success, string? Reason);
|
||||
internal sealed record WriteAttributeWithOutcome(WriteAdmissionTicket Ticket, WriteClaim Claim);
|
||||
/// <summary>
|
||||
/// Sent by <see cref="DriverHostActor"/> when an OPC UA client Acknowledges a NATIVE Part 9
|
||||
/// condition (resolved from the condition NodeId to this driver via the host's alarm inverse map).
|
||||
@@ -307,7 +310,13 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <summary>Writes waiting for a slot (or for their tag), in arrival order, stamped with arrival time.
|
||||
/// Failed fast on every exit from <c>Connected</c>, so a queued write never reaches a driver that is
|
||||
/// reconnecting; failed <c>BadTimeout</c> once older than <see cref="_queuedWriteBudget"/> since issued.</summary>
|
||||
private readonly LinkedList<(WriteAttribute Write, IActorRef ReplyTo, long IssuedAt)> _pendingWrites = new();
|
||||
private readonly LinkedList<(WriteAttribute Write, IActorRef ReplyTo, long IssuedAt, long Sequence)> _pendingWrites = new();
|
||||
private readonly LinkedList<(WriteAttributeWithOutcome Write, IActorRef ReplyTo, long Sequence)> _pendingRichWrites = new();
|
||||
private long _queuedWriteSequence;
|
||||
private readonly IWriteDispatchGate? _writeDispatchGate;
|
||||
private readonly LateWriteObserver? _lateWriteObserver;
|
||||
private readonly WriteRouteState? _writeRouteState;
|
||||
private string? _writeIncarnation;
|
||||
|
||||
/// <summary>Tags with a write currently inside the driver. A second write to the same tag waits in the
|
||||
/// queue behind it — two concurrent writes v1, v2 to one tag could otherwise land as v1.</summary>
|
||||
@@ -517,6 +526,23 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
writeTimeout,
|
||||
writeClock, sourcePublisher, sourceIncarnation));
|
||||
|
||||
internal static Props PropsForRichWrites(IDriver driver, IDriverCapabilityInvoker? invoker = null,
|
||||
TimeSpan? commsLossTimeout = null, int? maxWritesInFlight = null, TimeSpan? writeTimeout = null,
|
||||
IWriteDispatchGate? writeDispatchGate = null, LateWriteObserver? lateWriteObserver = null,
|
||||
WriteRouteState? writeRouteState = null, TimeProvider? writeClock = null,
|
||||
IDriverHealthPublisher? healthPublisher = null, string? clusterId = null, TimeSpan? shutdownTimeout = null,
|
||||
SourceSamplePublisher? sourcePublisher = null, long? sourceIncarnation = null, bool startStubbed = false) =>
|
||||
Akka.Actor.Props.CreateBy(new RichWriteActorProducer(() => new DriverInstanceActor(driver, DefaultReconnectInterval, startStubbed, healthPublisher, clusterId,
|
||||
invoker, null, commsLossTimeout, shutdownTimeout, maxWritesInFlight, null, null, writeTimeout, writeClock,
|
||||
sourcePublisher, sourceIncarnation, writeDispatchGate, lateWriteObserver, writeRouteState)));
|
||||
|
||||
private sealed class RichWriteActorProducer(Func<DriverInstanceActor> create) : IIndirectActorProducer
|
||||
{
|
||||
public Type ActorType => typeof(DriverInstanceActor);
|
||||
public ActorBase Produce() => create();
|
||||
public void Release(ActorBase actor) { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true when the driver should boot in DEV-STUB mode based on host platform and
|
||||
/// configured roles. Only the legacy v1 in-process <c>"Galaxy"</c> type stays Windows-only:
|
||||
@@ -580,7 +606,21 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
TimeProvider? writeClock = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null)
|
||||
: this(driver, reconnectInterval, startStubbed, healthPublisher, clusterId, invoker, healthPollInterval,
|
||||
commsLossTimeout, shutdownTimeout, maxWritesInFlight, queuedWriteBudget, initializeTimeout,
|
||||
writeTimeout, writeClock, sourcePublisher, sourceIncarnation, null, null, null) { }
|
||||
|
||||
private DriverInstanceActor(IDriver driver, TimeSpan reconnectInterval, bool startStubbed,
|
||||
IDriverHealthPublisher? healthPublisher, string? clusterId, IDriverCapabilityInvoker? invoker,
|
||||
TimeSpan? healthPollInterval, TimeSpan? commsLossTimeout, TimeSpan? shutdownTimeout,
|
||||
int? maxWritesInFlight, TimeSpan? queuedWriteBudget, TimeSpan? initializeTimeout,
|
||||
TimeSpan? writeTimeout, TimeProvider? writeClock, SourceSamplePublisher? sourcePublisher,
|
||||
long? sourceIncarnation, IWriteDispatchGate? writeDispatchGate, LateWriteObserver? lateWriteObserver,
|
||||
WriteRouteState? writeRouteState)
|
||||
{
|
||||
_writeDispatchGate = writeDispatchGate;
|
||||
_lateWriteObserver = lateWriteObserver;
|
||||
_writeRouteState = writeRouteState;
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_sourceIncarnation = sourceIncarnation;
|
||||
_writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout;
|
||||
@@ -618,6 +658,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <inheritdoc />
|
||||
protected override void PreStart()
|
||||
{
|
||||
if (_writeRouteState is not null) _writeIncarnation = _writeRouteState.BeginDriverIncarnation(_driverInstanceId);
|
||||
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
|
||||
!_sourcePublisher.IsDriverIncarnationActive(_driverInstanceId, previous))
|
||||
_sourceIncarnation = _sourcePublisher.RegisterDriverIncarnation(_driverInstanceId);
|
||||
@@ -662,6 +703,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// success without touching real hardware. Read returns null; Write succeeds.
|
||||
Receive<InitializeRequested>(_ => { /* no-op */ });
|
||||
Receive<WriteAttribute>(_ => Sender.Tell(new WriteAttributeResult(true, "stubbed")));
|
||||
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver is stubbed"));
|
||||
// Stubbed drivers have no upstream alarm system — swallow the ack (it's fire-and-forget, no reply).
|
||||
Receive<RouteAlarmAck>(_ => { /* stubbed drivers have no alarm backend */ });
|
||||
Receive<DisconnectObserved>(_ => { /* stubbed drivers don't disconnect */ });
|
||||
@@ -683,6 +725,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// "write timeout". Synchronous Receive: Sender.Tell on the actor thread is safe.
|
||||
Receive<WriteAttribute>(_ =>
|
||||
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
|
||||
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver not connected"));
|
||||
// A write launched while Connected can finish after the transition out of it; its slot still frees.
|
||||
Receive<WriteCompleted>(OnWriteCompleted);
|
||||
// An ack arriving while still connecting can't reach the upstream alarm system; drop it and report it
|
||||
@@ -763,6 +806,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// Synchronous Receive: the device call runs off the mailbox (see StartOrQueueWrite), so data changes
|
||||
// and further writes are never head-of-line blocked behind a slow device.
|
||||
Receive<WriteAttribute>(msg => StartOrQueueWrite(msg, Sender));
|
||||
Receive<WriteAttributeWithOutcome>(msg => StartOrQueueRichWrite(msg, Sender));
|
||||
Receive<WriteCompleted>(OnWriteCompleted);
|
||||
ReceiveAsync<RouteAlarmAck>(HandleAcknowledgeAsync);
|
||||
ReceiveAsync<Subscribe>(HandleSubscribeAsync);
|
||||
@@ -993,6 +1037,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// timeout on an inbound write to a transiently-down driver). Synchronous Receive.
|
||||
Receive<WriteAttribute>(_ =>
|
||||
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
|
||||
Receive<WriteAttributeWithOutcome>(msg => RejectRich(msg, Sender, "driver not connected"));
|
||||
Receive<WriteCompleted>(OnWriteCompleted);
|
||||
// An ack arriving while reconnecting can't reach the upstream alarm system; drop it and report it
|
||||
// failed so the host reverts the locally-committed acknowledge (lmxopcua#760).
|
||||
@@ -1192,13 +1237,180 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
|
||||
if (_writesInFlight >= _maxWritesInFlight || _tagsInFlight.Contains(msg.TagId))
|
||||
{
|
||||
_pendingWrites.AddLast((msg, replyTo, issuedAt));
|
||||
_pendingWrites.AddLast((msg, replyTo, issuedAt, ++_queuedWriteSequence));
|
||||
return;
|
||||
}
|
||||
|
||||
LaunchWrite(writable, msg, replyTo);
|
||||
}
|
||||
|
||||
private static readonly DataWriteOutcome RichRejected = new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Write rejected before dispatch.");
|
||||
private static readonly DataWriteOutcome RichUnknown = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Device outcome is unknown.");
|
||||
|
||||
private static void RejectRich(WriteAttributeWithOutcome msg, IActorRef replyTo, string reason)
|
||||
{
|
||||
var outcome = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, reason);
|
||||
if (msg.Claim.Complete(outcome)) msg.Ticket.Dispose();
|
||||
else outcome = msg.Claim.CurrentOutcome ?? RichUnknown;
|
||||
replyTo.Tell(outcome);
|
||||
}
|
||||
|
||||
private void StartOrQueueRichWrite(WriteAttributeWithOutcome msg, IActorRef replyTo)
|
||||
{
|
||||
if (_writeDispatchGate is null || _lateWriteObserver is null || _driver is not (IWritable or IWriteOutcomeCapability))
|
||||
{ RejectRich(msg, replyTo, "Rich writes are unavailable."); return; }
|
||||
if (_writeClock.GetElapsedTime(msg.Ticket.IssuedAt) > _queuedWriteBudget ||
|
||||
_writeClock.GetTimestamp() >= msg.Ticket.Proof.Admission.MonotonicExpiry)
|
||||
{ RejectRich(msg, replyTo, "Write expired before dispatch."); return; }
|
||||
var tag = msg.Ticket.Proof.DriverReference;
|
||||
if (_writesInFlight >= _maxWritesInFlight || _tagsInFlight.Contains(tag))
|
||||
{ _pendingRichWrites.AddLast((msg, replyTo, ++_queuedWriteSequence)); return; }
|
||||
LaunchRichWrite(msg, replyTo);
|
||||
}
|
||||
|
||||
private void LaunchRichWrite(WriteAttributeWithOutcome msg, IActorRef replyTo)
|
||||
{
|
||||
if (!_lateWriteObserver!.TryReserve(msg.Ticket.Proof.DriverInstanceId,
|
||||
msg.Ticket.Proof.DriverReference, out var reservation))
|
||||
{ RejectRich(msg, replyTo, "Outstanding driver write capacity exhausted."); return; }
|
||||
var tag = msg.Ticket.Proof.DriverReference;
|
||||
_writesInFlight++;
|
||||
_tagsInFlight.Add(tag);
|
||||
_ = RunRichWriteAsync(_driver, _invoker, ResolveHost(tag), msg, replyTo, Self,
|
||||
_writeDispatchGate!, reservation!, _writeTimeout, _writeClock, _incarnation);
|
||||
}
|
||||
|
||||
private sealed class WriteLifetime(WriteAdmissionTicket ticket, CancellationTokenSource cancellation) : IDisposable
|
||||
{
|
||||
public void Dispose() { try { ticket.Dispose(); } finally { cancellation.Dispose(); } }
|
||||
}
|
||||
|
||||
private static async Task RunRichWriteAsync(IDriver driver, IDriverCapabilityInvoker invoker, string hostKey,
|
||||
WriteAttributeWithOutcome msg, IActorRef replyTo, IActorRef self, IWriteDispatchGate gate,
|
||||
LateWriteReservation reservation, TimeSpan timeout, TimeProvider clock, int incarnation)
|
||||
{
|
||||
var physical = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var cancellation = new CancellationTokenSource(timeout, clock);
|
||||
// This task represents the entire physical invocation, including synchronous work before a driver
|
||||
// returns its task. Its permit and payload live until that invocation really exits.
|
||||
reservation.Observe(physical.Task, msg.Claim, new WriteLifetime(msg.Ticket, cancellation));
|
||||
var attempt = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
return await invoker.ExecuteWriteAsync(hostKey, false, ct =>
|
||||
{
|
||||
WriteRequest[] request;
|
||||
try { request = [new WriteRequest(msg.Ticket.Proof.DriverReference, DriverValue(msg.Ticket.Value))]; }
|
||||
catch
|
||||
{
|
||||
var noCall = msg.Claim.Complete(RichRejected) ? RichRejected : msg.Claim.CurrentOutcome ?? RichUnknown;
|
||||
if (!msg.Claim.IsDispatched) physical.TrySetResult(noCall);
|
||||
return ValueTask.FromResult(noCall);
|
||||
}
|
||||
var rejection = gate.TryCommit(msg.Ticket, msg.Claim);
|
||||
if (rejection is not null)
|
||||
{
|
||||
msg.Claim.Complete(rejection);
|
||||
physical.TrySetResult(rejection);
|
||||
return ValueTask.FromResult(rejection);
|
||||
}
|
||||
// The commit above is the linearization point. No await or external callback occurs
|
||||
// between that commit and the invocation below; preemption after commit is post-dispatch.
|
||||
try
|
||||
{
|
||||
if (driver is IWriteOutcomeCapability rich)
|
||||
_ = ObserveRichDriver(rich.WriteWithOutcomesAsync(request, ct), physical);
|
||||
else
|
||||
_ = ObserveLegacyDriver(((IWritable)driver).WriteAsync(request, ct), physical);
|
||||
}
|
||||
catch { physical.TrySetResult(RichUnknown); }
|
||||
return new ValueTask<DataWriteOutcome>(physical.Task);
|
||||
}, cancellation.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
|
||||
if (outcome == RichRejected) physical.TrySetResult(outcome);
|
||||
else msg.Claim.Complete(outcome);
|
||||
return outcome;
|
||||
}
|
||||
});
|
||||
try
|
||||
{
|
||||
var outcome = await attempt.WaitAsync(timeout + WriteAbandonGrace(timeout), clock).ConfigureAwait(false);
|
||||
replyTo.Tell(outcome);
|
||||
}
|
||||
catch
|
||||
{
|
||||
var outcome = msg.Claim.Complete(RichRejected) ? RichRejected : RichUnknown;
|
||||
if (outcome == RichRejected) physical.TrySetResult(outcome);
|
||||
else msg.Claim.Complete(outcome);
|
||||
replyTo.Tell(outcome);
|
||||
}
|
||||
finally { self.Tell(new WriteCompleted(msg.Ticket.Proof.DriverReference, incarnation)); }
|
||||
}
|
||||
|
||||
private static async Task ObserveRichDriver(Task<IReadOnlyList<DataWriteOutcome>> task,
|
||||
TaskCompletionSource<DataWriteOutcome> physical)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await task.ConfigureAwait(false);
|
||||
var outcome = result is { Count: 1 } ? result[0] : RichUnknown;
|
||||
if (outcome.State == DataWriteState.RejectedBeforeDispatch || outcome.State == DataWriteState.Unspecified) outcome = RichUnknown;
|
||||
physical.TrySetResult(outcome);
|
||||
}
|
||||
catch { physical.TrySetResult(RichUnknown); }
|
||||
}
|
||||
|
||||
private static async Task ObserveLegacyDriver(Task<IReadOnlyList<WriteResult>> task,
|
||||
TaskCompletionSource<DataWriteOutcome> physical)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await task.ConfigureAwait(false);
|
||||
physical.TrySetResult(result is { Count: 1 } && IsGoodStatus(result[0].StatusCode)
|
||||
? new(DataWriteState.AcceptedUnconfirmed, result[0].StatusCode, null) : RichUnknown);
|
||||
}
|
||||
catch { physical.TrySetResult(RichUnknown); }
|
||||
}
|
||||
|
||||
private static object? DriverValue(DataValue value) => value.Kind switch
|
||||
{
|
||||
DataValueKind.Null => null,
|
||||
DataValueKind.Bytes => value.GetBytes().ToArray(),
|
||||
DataValueKind.Array => ToDriverArray(value),
|
||||
_ => value.GetScalar(),
|
||||
};
|
||||
|
||||
private static Array ToDriverArray(DataValue value)
|
||||
{
|
||||
var elements = value.GetArray();
|
||||
var type = value.ArrayElementKind switch
|
||||
{
|
||||
DataValueKind.Boolean => typeof(bool), DataValueKind.Int8 => typeof(sbyte), DataValueKind.Int16 => typeof(short),
|
||||
DataValueKind.Int32 => typeof(int), DataValueKind.Int64 => typeof(long), DataValueKind.UInt8 => typeof(byte),
|
||||
DataValueKind.UInt16 => typeof(ushort), DataValueKind.UInt32 => typeof(uint), DataValueKind.UInt64 => typeof(ulong),
|
||||
DataValueKind.Float => typeof(float), DataValueKind.Double => typeof(double), DataValueKind.String => typeof(string),
|
||||
DataValueKind.Timestamp => typeof(DateTimeOffset), DataValueKind.Guid => typeof(Guid),
|
||||
_ => throw new ArgumentException("Unsupported array element kind."),
|
||||
};
|
||||
var dimensions = value.Dimensions!.ToArray();
|
||||
var result = Array.CreateInstance(type, dimensions);
|
||||
var index = new int[dimensions.Length];
|
||||
foreach (var element in elements)
|
||||
{
|
||||
result.SetValue(element, index);
|
||||
for (var d = index.Length - 1; d >= 0; d--)
|
||||
{
|
||||
if (++index[d] < dimensions[d]) break;
|
||||
index[d] = 0;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void LaunchWrite(IWritable writable, WriteAttribute msg, IActorRef replyTo)
|
||||
{
|
||||
_writesInFlight++;
|
||||
@@ -1296,7 +1508,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
|
||||
private void DrainWriteQueue()
|
||||
{
|
||||
if (_driver is not IWritable writable) return;
|
||||
var writable = _driver as IWritable;
|
||||
|
||||
// Expire FIRST, over the whole queue, regardless of free slots: a write past its budget must be answered
|
||||
// now, not whenever a slot next frees and the scan happens to reach it — the host's Ask covers the budget
|
||||
@@ -1308,17 +1520,34 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
node = next;
|
||||
}
|
||||
|
||||
for (var node = _pendingWrites.First; node is not null && _writesInFlight < _maxWritesInFlight;)
|
||||
while (true)
|
||||
{
|
||||
var next = node.Next;
|
||||
var (write, replyTo, _) = node.Value;
|
||||
if (!_tagsInFlight.Contains(write.TagId))
|
||||
var before = _pendingWrites.Count + _pendingRichWrites.Count;
|
||||
for (var node = _pendingWrites.First; writable is not null && node is not null && _writesInFlight < _maxWritesInFlight;)
|
||||
{
|
||||
_pendingWrites.Remove(node);
|
||||
LaunchWrite(writable, write, replyTo);
|
||||
var next = node.Next;
|
||||
var (write, replyTo, _, sequence) = node.Value;
|
||||
if (!_tagsInFlight.Contains(write.TagId) && !_pendingRichWrites.Any(x =>
|
||||
x.Sequence < sequence && x.Write.Ticket.Proof.DriverReference == write.TagId))
|
||||
{
|
||||
_pendingWrites.Remove(node);
|
||||
LaunchWrite(writable, write, replyTo);
|
||||
}
|
||||
node = next;
|
||||
}
|
||||
|
||||
node = next;
|
||||
for (var node = _pendingRichWrites.First; node is not null;)
|
||||
{
|
||||
var next = node.Next;
|
||||
var (write, replyTo, sequence) = node.Value;
|
||||
if (_writeClock.GetElapsedTime(write.Ticket.IssuedAt) > _queuedWriteBudget ||
|
||||
_writeClock.GetTimestamp() >= write.Ticket.Proof.Admission.MonotonicExpiry)
|
||||
{ _pendingRichWrites.Remove(node); RejectRich(write, replyTo, "Write expired before dispatch."); }
|
||||
else if (_writesInFlight < _maxWritesInFlight && !_tagsInFlight.Contains(write.Ticket.Proof.DriverReference)
|
||||
&& !_pendingWrites.Any(x => x.Sequence < sequence && x.Write.TagId == write.Ticket.Proof.DriverReference))
|
||||
{ _pendingRichWrites.Remove(node); LaunchRichWrite(write, replyTo); }
|
||||
node = next;
|
||||
}
|
||||
if (_writesInFlight >= _maxWritesInFlight || before == _pendingWrites.Count + _pendingRichWrites.Count) break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1349,6 +1578,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
_pendingWrites.RemoveFirst();
|
||||
node.Value.ReplyTo.Tell(new WriteAttributeResult(false, reason));
|
||||
}
|
||||
while (_pendingRichWrites.First is { } rich)
|
||||
{
|
||||
_pendingRichWrites.RemoveFirst();
|
||||
RejectRich(rich.Value.Write, rich.Value.ReplyTo, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -2162,6 +2396,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <inheritdoc />
|
||||
protected override void PostStop()
|
||||
{
|
||||
if (_writeIncarnation is { } writeIncarnation) _writeRouteState?.RetireDriver(_driverInstanceId, writeIncarnation);
|
||||
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireDriver(_driverInstanceId, incarnation);
|
||||
// Archreview 03/S15 — announce comms loss on the way out. Every OTHER route into Reconnecting
|
||||
// (watchdog trip, failed initial connect, Force Reconnect) announces it from the Reconnecting
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
@@ -113,6 +114,11 @@ public interface IHistoryUpdateRoleView
|
||||
public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRoleSource, IHistorizationRoleView,
|
||||
IHistoryUpdateRoleView
|
||||
{
|
||||
public RedundancyRoleView(DataWriteDispatchFence? dispatchFence = null) => DispatchFence = dispatchFence ?? new();
|
||||
public DataWriteDispatchFence DispatchFence { get; }
|
||||
private sealed record PrimaryVerdict(bool Allowed, long Generation);
|
||||
private PrimaryVerdict _primaryVerdict = new(PrimaryGatePolicy.ShouldServiceAsPrimary(null, 1), 0);
|
||||
public long PrimaryGeneration => Volatile.Read(ref _primaryVerdict).Generation;
|
||||
// seeded CLOSED, unlike the data-plane verdict. HistoryUpdate waits for a real redundancy verdict
|
||||
// (PrimaryGatePolicy.ShouldServeHistoryUpdate); a node that never publishes here is not a driver node with a
|
||||
// redundancy manager, and such a node does not register this view as its gate source.
|
||||
@@ -130,9 +136,6 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
|
||||
// a node nothing has reported a role for, on a cluster with no driver peer, is a single-node
|
||||
// deployment and may claim. The moment a snapshot arrives this is replaced by the real verdict,
|
||||
// and a multi-driver cluster's unknown role denies.
|
||||
private volatile bool _shouldActAsPrimary =
|
||||
PrimaryGatePolicy.ShouldServiceAsPrimary(localRole: null, driverMemberCount: 1);
|
||||
|
||||
// Seeded for the unknown-role case from the same policy that will later publish here: a node
|
||||
// nothing has reported a role for captures, exactly as an unpaired or single-node deployment must.
|
||||
// Defaulting closed would leave a deployment that never publishes a role with no trend data at all.
|
||||
@@ -146,7 +149,7 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
|
||||
public bool ShouldRecordHistorizedValues => _shouldRecordHistorizedValues;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool ShouldActAsPrimary => _shouldActAsPrimary;
|
||||
public bool ShouldActAsPrimary => Volatile.Read(ref _primaryVerdict).Allowed;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool ShouldServeHistoryUpdate => _shouldServeHistoryUpdate;
|
||||
@@ -158,7 +161,15 @@ public sealed class RedundancyRoleView : IRedundancyRoleView, IDriverPrimaryRole
|
||||
public void Publish(bool shouldDrainAlarmHistory) => _shouldDrainAlarmHistory = shouldDrainAlarmHistory;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void PublishPrimaryRole(bool shouldActAsPrimary) => _shouldActAsPrimary = shouldActAsPrimary;
|
||||
public void PublishPrimaryRole(bool shouldActAsPrimary)
|
||||
{
|
||||
using (DispatchFence.Enter())
|
||||
{
|
||||
var current = _primaryVerdict;
|
||||
if (current.Generation == 0 || current.Allowed != shouldActAsPrimary)
|
||||
Volatile.Write(ref _primaryVerdict, new(shouldActAsPrimary, checked(current.Generation + 1)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void PublishHistorizationRole(bool shouldRecordHistorizedValues)
|
||||
|
||||
@@ -57,6 +57,8 @@ public static class ServiceCollectionExtensions
|
||||
/// <returns>The same <paramref name="services"/> instance for chaining.</returns>
|
||||
public static IServiceCollection AddOtOpcUaRuntime(this IServiceCollection services)
|
||||
{
|
||||
// Authority and role publishers share the same ordering point as rich write dispatch.
|
||||
services.TryAddSingleton<DataWriteDispatchFence>();
|
||||
services.TryAddSingleton<IAlarmHistorianSink>(NullAlarmHistorianSink.Instance);
|
||||
services.TryAddSingleton<IHistorianDataSource>(NullHistorianDataSource.Instance);
|
||||
// Historian tag provisioning. Null default (no-op) so the AddressSpaceApplier resolves a real
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
using System.Security.Cryptography;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
|
||||
public sealed class GrpcDataValueFingerprintTests
|
||||
{
|
||||
[Fact]
|
||||
public void Retained_values_and_owned_copies_have_the_same_fingerprint_after_inputs_are_mutated()
|
||||
{
|
||||
byte[] bytes = [1, 2, 3, 4];
|
||||
object[] elements = [1, 2];
|
||||
int[] shape = [2];
|
||||
using var value = DataValue.FromBytes(bytes);
|
||||
using var retained = value.Retain();
|
||||
using var array = DataValue.FromArray(DataValueKind.Int32, elements, shape);
|
||||
bytes[0] = 99;
|
||||
elements[0] = 99;
|
||||
shape[0] = 1;
|
||||
using var expectedBytes = DataValue.FromBytes([1, 2, 3, 4]);
|
||||
using var expectedArray = DataValue.FromArray(DataValueKind.Int32, [1, 2], [2]);
|
||||
|
||||
Fingerprint(value).ShouldBe(Fingerprint(retained));
|
||||
Fingerprint(value).ShouldBe(Fingerprint(expectedBytes));
|
||||
Fingerprint(array).ShouldBe(Fingerprint(expectedArray));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprint_distinguishes_declared_scalar_kind_and_array_element_kind()
|
||||
{
|
||||
using var signed = DataValue.FromScalar(DataValueKind.Int32, 1);
|
||||
using var unsigned = DataValue.FromScalar(DataValueKind.UInt32, 1u);
|
||||
using var signedArray = DataValue.FromArray(DataValueKind.Int32, [1], [1]);
|
||||
using var unsignedArray = DataValue.FromArray(DataValueKind.UInt32, [1u], [1]);
|
||||
|
||||
Fingerprint(signed).ShouldNotBe(Fingerprint(unsigned));
|
||||
Fingerprint(signedArray).ShouldNotBe(Fingerprint(unsignedArray));
|
||||
Fingerprint(signed).ShouldNotBe(Fingerprint(signedArray));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprint_distinguishes_array_shape_byte_content_and_null_from_empty_values()
|
||||
{
|
||||
using var flat = DataValue.FromArray(DataValueKind.Int32, [1, 2], [2]);
|
||||
using var matrix = DataValue.FromArray(DataValueKind.Int32, [1, 2], [1, 2]);
|
||||
using var bytes = DataValue.FromBytes([1, 2]);
|
||||
using var reversed = DataValue.FromBytes([2, 1]);
|
||||
using var nullValue = DataValue.Null();
|
||||
using var emptyBytes = DataValue.FromBytes([]);
|
||||
using var emptyText = DataValue.FromScalar(DataValueKind.String, "");
|
||||
using var emptyArray = DataValue.FromArray(DataValueKind.Int32, [], [0]);
|
||||
|
||||
Fingerprint(flat).ShouldNotBe(Fingerprint(matrix));
|
||||
Fingerprint(bytes).ShouldNotBe(Fingerprint(reversed));
|
||||
var emptyFingerprints = new[] { Fingerprint(nullValue), Fingerprint(emptyBytes),
|
||||
Fingerprint(emptyText), Fingerprint(emptyArray) };
|
||||
emptyFingerprints.Distinct(StringComparer.Ordinal).Count().ShouldBe(emptyFingerprints.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprint_preserves_ordinal_utf16_code_units_including_unpaired_surrogates()
|
||||
{
|
||||
using var first = DataValue.FromScalar(DataValueKind.String, "\ud800");
|
||||
using var second = DataValue.FromScalar(DataValueKind.String, "\ud801");
|
||||
using var replacement = DataValue.FromScalar(DataValueKind.String, "\ufffd");
|
||||
using var arrayFirst = DataValue.FromArray(DataValueKind.String, ["a\ud800"], [1]);
|
||||
using var arraySecond = DataValue.FromArray(DataValueKind.String, ["a\ud801"], [1]);
|
||||
|
||||
Fingerprint(first).ShouldNotBe(Fingerprint(second));
|
||||
Fingerprint(first).ShouldNotBe(Fingerprint(replacement));
|
||||
Fingerprint(arrayFirst).ShouldNotBe(Fingerprint(arraySecond));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprint_preserves_float_and_double_bit_patterns_including_nan_and_signed_zero()
|
||||
{
|
||||
var singleNanOne = BitConverter.Int32BitsToSingle(unchecked((int)0x7fc00001u));
|
||||
var singleNanTwo = BitConverter.Int32BitsToSingle(unchecked((int)0x7fc00002u));
|
||||
var doubleNanOne = BitConverter.Int64BitsToDouble(unchecked((long)0x7ff8000000000001ul));
|
||||
var doubleNanTwo = BitConverter.Int64BitsToDouble(unchecked((long)0x7ff8000000000002ul));
|
||||
using var firstSingle = DataValue.FromScalar(DataValueKind.Float, singleNanOne);
|
||||
using var secondSingle = DataValue.FromScalar(DataValueKind.Float, singleNanTwo);
|
||||
using var firstDouble = DataValue.FromScalar(DataValueKind.Double, doubleNanOne);
|
||||
using var secondDouble = DataValue.FromScalar(DataValueKind.Double, doubleNanTwo);
|
||||
using var positiveZero = DataValue.FromScalar(DataValueKind.Double, 0d);
|
||||
using var negativeZero = DataValue.FromScalar(DataValueKind.Double, BitConverter.Int64BitsToDouble(long.MinValue));
|
||||
using var firstArray = DataValue.FromArray(DataValueKind.Float, [singleNanOne], [1]);
|
||||
using var secondArray = DataValue.FromArray(DataValueKind.Float, [singleNanTwo], [1]);
|
||||
|
||||
Fingerprint(firstSingle).ShouldNotBe(Fingerprint(secondSingle));
|
||||
Fingerprint(firstDouble).ShouldNotBe(Fingerprint(secondDouble));
|
||||
Fingerprint(positiveZero).ShouldNotBe(Fingerprint(negativeZero));
|
||||
Fingerprint(firstArray).ShouldNotBe(Fingerprint(secondArray));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disposed_lease_cannot_be_fingerprinted_but_an_independent_retained_lease_can()
|
||||
{
|
||||
var value = DataValue.FromBytes([1, 2]);
|
||||
using var retained = value.Retain();
|
||||
value.Dispose();
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
|
||||
Should.Throw<ObjectDisposedException>(() => value.AppendSemanticFingerprint(hash));
|
||||
var retainedDigest = Fingerprint(retained);
|
||||
using var expected = DataValue.FromBytes([1, 2]);
|
||||
retainedDigest.ShouldBe(Fingerprint(expected));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprinting_large_owned_bytes_does_not_allocate_a_second_payload_sized_buffer()
|
||||
{
|
||||
using var value = DataValue.FromBytes(new byte[2_000_000]);
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
value.AppendSemanticFingerprint(hash);
|
||||
_ = hash.GetHashAndReset();
|
||||
var before = GC.GetAllocatedBytesForCurrentThread();
|
||||
value.AppendSemanticFingerprint(hash);
|
||||
_ = hash.GetHashAndReset();
|
||||
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
|
||||
|
||||
allocated.ShouldBeLessThan(64_000L, "fingerprinting must stream the owned payload instead of copying it");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fingerprint_appends_to_the_existing_hash_without_resetting_its_prefix()
|
||||
{
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
using var first = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
using var second = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
first.AppendData([1]);
|
||||
second.AppendData([2]);
|
||||
value.AppendSemanticFingerprint(first);
|
||||
value.AppendSemanticFingerprint(second);
|
||||
|
||||
Convert.ToHexString(first.GetHashAndReset()).ShouldNotBe(Convert.ToHexString(second.GetHashAndReset()));
|
||||
}
|
||||
|
||||
private static string Fingerprint(DataValue value)
|
||||
{
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
value.AppendSemanticFingerprint(hash);
|
||||
return Convert.ToHexString(hash.GetHashAndReset());
|
||||
}
|
||||
}
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P05")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataModbusWriteOutcomeTests
|
||||
{
|
||||
private static readonly RawTagEntry[] Tags =
|
||||
[
|
||||
new("reg", """{"region":"HoldingRegisters","address":10,"dataType":"UInt16"}""", false),
|
||||
new("next", """{"region":"HoldingRegisters","address":11,"dataType":"UInt16"}""", false),
|
||||
new("coil", """{"region":"Coils","address":12}""", false),
|
||||
new("coils", """{"region":"Coils","address":30,"isArray":true,"arrayLength":2}""", false),
|
||||
new("array", """{"region":"HoldingRegisters","address":20,"dataType":"UInt16","isArray":true,"arrayLength":2}""", false),
|
||||
];
|
||||
|
||||
private static async Task<ModbusDriver> CreateAsync(ScriptedTransport transport, bool suppress = false, bool fc23 = false, bool singleSend = true)
|
||||
{
|
||||
var driver = new ModbusDriver(new ModbusDriverOptions
|
||||
{
|
||||
Host = "fake", RawTags = Tags, WriteOnChangeOnly = suppress,
|
||||
UseFC23ForMultiRegisterWrites = fc23, Probe = new ModbusProbeOptions { Enabled = false },
|
||||
}, "rich-modbus", _ => singleSend ? new SingleSendFake(transport) : transport);
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
return driver;
|
||||
}
|
||||
|
||||
private sealed class SingleSendFake(ScriptedTransport inner) : IModbusWriteOnceTransport
|
||||
{
|
||||
public Task ConnectAsync(CancellationToken ct) => inner.ConnectAsync(ct);
|
||||
public Task<byte[]> SendAsync(byte unit, byte[] pdu, CancellationToken ct) => inner.SendAsync(unit, pdu, ct);
|
||||
public Task<byte[]> SendWithoutRetryAsync(byte unit, byte[] pdu, CancellationToken ct) => inner.SendAsync(unit, pdu, ct);
|
||||
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("reg", 6)]
|
||||
[InlineData("coil", 5)]
|
||||
[InlineData("coils", 15)]
|
||||
[InlineData("array", 16)]
|
||||
public async Task Valid_echo_confirms_real_write_effect(string tag, int expectedFunction)
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
await using var driver = await CreateAsync(transport);
|
||||
object value = tag == "coil" ? true : tag == "coils" ? new[] { true, false } : tag == "array" ? new ushort[] { 2, 3 } : (ushort)42;
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new(tag, value)], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
transport.Sent.Single().Pdu[0].ShouldBe((byte)expectedFunction);
|
||||
if (tag == "reg") transport.Bank.HoldingRegisters[10].ShouldBe((ushort)42);
|
||||
if (tag == "coil") transport.Bank.Coils[12].ShouldBeTrue();
|
||||
if (tag == "coils") transport.Bank.Coils[30..32].ShouldBe(new[] { true, false });
|
||||
if (tag == "array") transport.Bank.HoldingRegisters[20..22].ShouldBe(new ushort[] { 2, 3 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FC23_confirmation_requires_valid_readback_frame()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
await using var driver = await CreateAsync(transport, fc23: true);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("array", new ushort[] { 2, 3 })], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
transport.Sent.Single().Pdu[0].ShouldBe((byte)0x17);
|
||||
transport.Bank.HoldingRegisters[20..22].ShouldBe(new ushort[] { 2, 3 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Wrong_function_in_FC23_response_is_unknown_even_after_device_commit()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
transport.Handler = async (unit, pdu, ct) =>
|
||||
{
|
||||
var ack = await transport.Bank.SendAsync(unit, pdu, ct);
|
||||
ack[0] = 0x10;
|
||||
return ack;
|
||||
};
|
||||
await using var driver = await CreateAsync(transport, fc23: true);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("array", new ushort[] { 2, 3 })], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
transport.Bank.HoldingRegisters[20..22].ShouldBe(new ushort[] { 2, 3 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FC23_mismatched_exception_after_commit_is_unknown_without_fallback_replay()
|
||||
{
|
||||
var effects = 0;
|
||||
var registers = new ushort[2];
|
||||
await using var server = new ScriptedModbusTcpServer
|
||||
{
|
||||
RawReply = (_, header, pdu) =>
|
||||
{
|
||||
if (pdu[0] == 0x17)
|
||||
{
|
||||
registers[0] = (ushort)((pdu[10] << 8) | pdu[11]);
|
||||
registers[1] = (ushort)((pdu[12] << 8) | pdu[13]);
|
||||
Interlocked.Increment(ref effects);
|
||||
// Matching MBAP transaction and unit, but FC06's exception, not FC23's.
|
||||
return ScriptedModbusTcpServer.Adu(header, [0x86, 0x01]);
|
||||
}
|
||||
if (pdu[0] == 0x10)
|
||||
{
|
||||
registers[0] = (ushort)((pdu[6] << 8) | pdu[7]);
|
||||
registers[1] = (ushort)((pdu[8] << 8) | pdu[9]);
|
||||
Interlocked.Increment(ref effects);
|
||||
return ScriptedModbusTcpServer.Adu(header, pdu[..5]);
|
||||
}
|
||||
throw new InvalidOperationException("Unexpected request.");
|
||||
},
|
||||
};
|
||||
await using var driver = new ModbusDriver(new ModbusDriverOptions
|
||||
{
|
||||
Host = "127.0.0.1", Port = server.Port, RawTags = Tags,
|
||||
UseFC23ForMultiRegisterWrites = true, AutoReconnect = true,
|
||||
Timeout = TimeSpan.FromSeconds(2), Probe = new ModbusProbeOptions { Enabled = false },
|
||||
}, "fc23-mismatched-exception");
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync(
|
||||
[new("array", new ushort[] { 2, 3 })], TestContext.Current.CancellationToken);
|
||||
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
server.Requests.ShouldBe(1);
|
||||
Volatile.Read(ref effects).ShouldBe(1);
|
||||
registers.ShouldBe(new ushort[] { 2, 3 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FC23_matching_illegal_function_falls_back_once_to_FC16()
|
||||
{
|
||||
var effects = 0;
|
||||
var registers = new ushort[2];
|
||||
await using var server = new ScriptedModbusTcpServer
|
||||
{
|
||||
RawReply = (_, header, pdu) =>
|
||||
{
|
||||
if (pdu[0] == 0x17)
|
||||
return ScriptedModbusTcpServer.Adu(header, [0x97, 0x01]);
|
||||
if (pdu[0] == 0x10)
|
||||
{
|
||||
registers[0] = (ushort)((pdu[6] << 8) | pdu[7]);
|
||||
registers[1] = (ushort)((pdu[8] << 8) | pdu[9]);
|
||||
Interlocked.Increment(ref effects);
|
||||
return ScriptedModbusTcpServer.Adu(header, pdu[..5]);
|
||||
}
|
||||
throw new InvalidOperationException("Unexpected request.");
|
||||
},
|
||||
};
|
||||
await using var driver = new ModbusDriver(new ModbusDriverOptions
|
||||
{
|
||||
Host = "127.0.0.1", Port = server.Port, RawTags = Tags,
|
||||
UseFC23ForMultiRegisterWrites = true, AutoReconnect = true,
|
||||
Timeout = TimeSpan.FromSeconds(2), Probe = new ModbusProbeOptions { Enabled = false },
|
||||
}, "fc23-valid-fallback");
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync(
|
||||
[new("array", new ushort[] { 2, 3 })], TestContext.Current.CancellationToken);
|
||||
|
||||
result.Single().State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
server.Requests.ShouldBe(2);
|
||||
Volatile.Read(ref effects).ShouldBe(1);
|
||||
registers.ShouldBe(new ushort[] { 2, 3 });
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("short")]
|
||||
[InlineData("wrong-function")]
|
||||
[InlineData("wrong-address")]
|
||||
[InlineData("wrong-value")]
|
||||
public async Task Malformed_or_mismatched_echo_cannot_confirm_device_effect(string mutation)
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
transport.Handler = async (unit, pdu, ct) =>
|
||||
{
|
||||
var ack = await transport.Bank.SendAsync(unit, pdu, ct);
|
||||
var reply = (byte[])ack.Clone();
|
||||
if (mutation == "short") return reply[..2];
|
||||
if (mutation == "wrong-function") reply[0] ^= 1;
|
||||
if (mutation == "wrong-address") reply[2] ^= 1;
|
||||
if (mutation == "wrong-value") reply[4] ^= 1;
|
||||
return reply;
|
||||
};
|
||||
await using var driver = await CreateAsync(transport);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
transport.Bank.HoldingRegisters[10].ShouldBe((ushort)42);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_value_is_rejected_before_any_transport_call()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
await using var driver = await CreateAsync(transport);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("reg", "not-a-number")], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
transport.TotalSends.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Legacy_only_transport_cannot_dispatch_a_rich_write_but_remains_usable_by_legacy_writes()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
await using var driver = await CreateAsync(transport, singleSend: false);
|
||||
var rich = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
rich.Single().State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
transport.TotalSends.ShouldBe(0);
|
||||
var legacy = await driver.WriteAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
legacy.Single().StatusCode.ShouldBe(0u);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
transport.Bank.HoldingRegisters[10].ShouldBe((ushort)42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lost_reply_after_device_commit_is_unknown_and_never_retried()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
transport.Handler = async (unit, pdu, ct) =>
|
||||
{
|
||||
await transport.Bank.SendAsync(unit, pdu, ct);
|
||||
throw new TimeoutException("response lost after commit");
|
||||
};
|
||||
await using var driver = await CreateAsync(transport);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
transport.Bank.HoldingRegisters[10].ShouldBe((ushort)42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Socket_drop_after_commit_does_not_trigger_transport_reconnect_and_replay()
|
||||
{
|
||||
var effects = 0;
|
||||
await using var server = new ScriptedModbusTcpServer
|
||||
{
|
||||
RawReply = (_, _, pdu) =>
|
||||
{
|
||||
if (pdu[0] == 0x06) Interlocked.Increment(ref effects);
|
||||
return null;
|
||||
},
|
||||
Script = _ => ScriptedModbusTcpServer.Action.Drop,
|
||||
};
|
||||
await using var driver = new ModbusDriver(new ModbusDriverOptions
|
||||
{
|
||||
Host = "127.0.0.1", Port = server.Port, RawTags = Tags,
|
||||
AutoReconnect = true, Timeout = TimeSpan.FromSeconds(2),
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
}, "rich-loopback");
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync(
|
||||
[new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
server.Requests.ShouldBe(1);
|
||||
Volatile.Read(ref effects).ShouldBe(1);
|
||||
server.AcceptedConnections.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Socket_response_with_wrong_unit_cannot_confirm_the_write()
|
||||
{
|
||||
await using var server = new ScriptedModbusTcpServer
|
||||
{
|
||||
RawReply = (_, header, pdu) =>
|
||||
{
|
||||
var reply = ScriptedModbusTcpServer.Adu(header, pdu);
|
||||
reply[6] ^= 1;
|
||||
return reply;
|
||||
},
|
||||
};
|
||||
await using var driver = new ModbusDriver(new ModbusDriverOptions
|
||||
{
|
||||
Host = "127.0.0.1", Port = server.Port, RawTags = Tags,
|
||||
AutoReconnect = true, Timeout = TimeSpan.FromSeconds(2),
|
||||
Probe = new ModbusProbeOptions { Enabled = false },
|
||||
}, "rich-wrong-unit");
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync(
|
||||
[new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
server.Requests.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cancellation_after_device_commit_is_unknown_and_never_replayed()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
using var canceled = new CancellationTokenSource();
|
||||
transport.Handler = async (unit, pdu, ct) =>
|
||||
{
|
||||
await transport.Bank.SendAsync(unit, pdu, ct);
|
||||
canceled.Cancel();
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return pdu;
|
||||
};
|
||||
await using var driver = await CreateAsync(transport);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("reg", (ushort)42)], canceled.Token);
|
||||
result.Single().State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
transport.Bank.HoldingRegisters[10].ShouldBe((ushort)42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Batch_preserves_item_outcomes_and_never_sends_prevalidation_failure()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
transport.Handler = async (unit, pdu, ct) =>
|
||||
{
|
||||
var ack = await transport.Bank.SendAsync(unit, pdu, ct);
|
||||
if (pdu[2] == 11) throw new TimeoutException("lost response");
|
||||
return ack;
|
||||
};
|
||||
await using var driver = await CreateAsync(transport);
|
||||
var results = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync(
|
||||
[new("reg", (ushort)1), new("missing", 5), new("next", (ushort)2)], TestContext.Current.CancellationToken);
|
||||
results.Select(r => r.State).ShouldBe([DataWriteState.DriverConfirmedSuccess, DataWriteState.RejectedBeforeDispatch, DataWriteState.OutcomeUnknown]);
|
||||
transport.TotalSends.ShouldBe(2);
|
||||
transport.Bank.HoldingRegisters[10].ShouldBe((ushort)1);
|
||||
transport.Bank.HoldingRegisters[11].ShouldBe((ushort)2);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(2, DataWriteState.DriverConfirmedFailure)]
|
||||
[InlineData(11, DataWriteState.OutcomeUnknown)]
|
||||
public async Task Only_a_definitive_device_exception_is_confirmed_failure(int exceptionCode, DataWriteState expected)
|
||||
{
|
||||
var transport = new ScriptedTransport { Handler = (_, pdu, _) => Task.FromException<byte[]>(new ModbusException(pdu[0], (byte)exceptionCode, "exception")) };
|
||||
await using var driver = await CreateAsync(transport);
|
||||
var result = await ((IWriteOutcomeCapability)driver).WriteWithOutcomesAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken);
|
||||
result.Single().State.ShouldBe(expected);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Suppressed_duplicate_is_not_reported_as_a_new_device_confirmation()
|
||||
{
|
||||
var transport = new ScriptedTransport();
|
||||
await using var driver = await CreateAsync(transport, suppress: true);
|
||||
var capability = (IWriteOutcomeCapability)driver;
|
||||
(await capability.WriteWithOutcomesAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken)).Single().State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
(await capability.WriteWithOutcomesAsync([new("reg", (ushort)42)], TestContext.Current.CancellationToken)).Single().State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
transport.TotalSends.ShouldBe(1);
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Server;
|
||||
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.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P05")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataMappedWriteCompletionTests : IAsyncLifetime
|
||||
{
|
||||
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otua-mapped-write-{Guid.NewGuid():N}");
|
||||
private OpcUaApplicationHost _host = null!;
|
||||
private OtOpcUaSdkServer _server = null!;
|
||||
private OtOpcUaNodeManager _manager = null!;
|
||||
private EquipmentVariableState _node = null!;
|
||||
private static readonly DateTime AuthoritativeTimestamp = new(2026, 10, 4, 12, 34, 56, DateTimeKind.Utc);
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
public async ValueTask InitializeAsync()
|
||||
{
|
||||
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(
|
||||
new OpcUaApplicationHostOptions { ApplicationName = "MappedWriteCompletion", ApplicationUri = $"urn:MappedWriteCompletion:{Guid.NewGuid():N}", PublicHostname = "localhost", OpcUaPort = port, PkiStoreRoot = _pki },
|
||||
NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), Ct);
|
||||
_host = started.Host;
|
||||
_server = started.Server;
|
||||
_manager = _server.NodeManager!;
|
||||
_manager.EnsureVariable("v", null, "Value", "Int32", true, AddressSpaceRealm.Raw);
|
||||
_manager.WriteValue("v", 7, OpcUaStatus.Good, AuthoritativeTimestamp, AddressSpaceRealm.Raw);
|
||||
_node = (EquipmentVariableState)_manager.TryGetVariable("v", AddressSpaceRealm.Raw)!;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _host.DisposeAsync();
|
||||
if (Directory.Exists(_pki)) Directory.Delete(_pki, true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DataWriteState.RejectedBeforeDispatch)]
|
||||
[InlineData(DataWriteState.DriverConfirmedFailure)]
|
||||
public async Task Definitive_failure_restores_authoritative_value(DataWriteState state)
|
||||
{
|
||||
var source = InstallWrite();
|
||||
Write(42).ShouldBe(ServiceResult.Good);
|
||||
SdkValueBoundary.ToClr(_node.Value).ShouldBe(42);
|
||||
source.SetResult(new(state, StatusCodes.BadDeviceFailure.Code, "refused"));
|
||||
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
SdkValueBoundary.ToClr(_node.Value).ShouldBe(7);
|
||||
_node.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
_node.Timestamp.ToDateTime().ShouldBe(AuthoritativeTimestamp);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(DataWriteState.OutcomeUnknown)]
|
||||
[InlineData(DataWriteState.AcceptedUnconfirmed)]
|
||||
public async Task Ambiguous_outcomes_stay_uncertain_until_fresh_source_data(DataWriteState state)
|
||||
{
|
||||
var source = InstallWrite();
|
||||
Write(42).ShouldBe(ServiceResult.Good);
|
||||
source.SetResult(new(state, 0, null));
|
||||
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
_node.StatusCode.ShouldBe(StatusCodes.UncertainLastUsableValue);
|
||||
SdkValueBoundary.ToClr(_node.Value).ShouldBe(7);
|
||||
_node.Timestamp.ToDateTime().ShouldBe(AuthoritativeTimestamp);
|
||||
_manager.WriteValue("v", 42, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
_node.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Late_failure_cannot_overwrite_fresh_equal_valued_source_sample()
|
||||
{
|
||||
var source = InstallWrite();
|
||||
Write(42).ShouldBe(ServiceResult.Good);
|
||||
_manager.WriteValue("v", 42, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
source.SetResult(new(DataWriteState.DriverConfirmedFailure, 0, null));
|
||||
await Task.Yield();
|
||||
// The completion is synchronously testable through the manager's returned completion task.
|
||||
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
SdkValueBoundary.ToClr(_node.Value).ShouldBe(42);
|
||||
_node.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Older_failure_cannot_overwrite_newer_equal_valued_write()
|
||||
{
|
||||
var first = InstallWrite();
|
||||
Write(42).ShouldBe(ServiceResult.Good);
|
||||
var firstCompletion = _completion!;
|
||||
var second = InstallWrite();
|
||||
Write(42).ShouldBe(ServiceResult.Good);
|
||||
first.SetResult(new(DataWriteState.DriverConfirmedFailure, 0, null));
|
||||
await firstCompletion.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
SdkValueBoundary.ToClr(_node.Value).ShouldBe(42);
|
||||
_node.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
second.SetResult(new(DataWriteState.DriverConfirmedSuccess, 0, null));
|
||||
await _completion!.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Old_failure_cannot_overwrite_recreated_node_with_same_id_and_value()
|
||||
{
|
||||
var first = InstallWrite();
|
||||
Write(42).ShouldBe(ServiceResult.Good);
|
||||
var firstCompletion = _completion!;
|
||||
_manager.RemoveVariableNode("v", AddressSpaceRealm.Raw).ShouldBeTrue();
|
||||
_manager.EnsureVariable("v", null, "Replacement", "Int32", true, AddressSpaceRealm.Raw);
|
||||
_manager.WriteValue("v", 42, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
var replacement = _manager.TryGetVariable("v", AddressSpaceRealm.Raw)!;
|
||||
replacement.ShouldNotBeSameAs(_node);
|
||||
first.SetResult(new(DataWriteState.DriverConfirmedFailure, 0, null));
|
||||
await firstCompletion.WaitAsync(TimeSpan.FromSeconds(5), Ct);
|
||||
SdkValueBoundary.ToClr(replacement.Value).ShouldBe(42);
|
||||
replacement.StatusCode.ShouldBe(StatusCodes.Good);
|
||||
}
|
||||
|
||||
private Task? _completion;
|
||||
private TaskCompletionSource<DataWriteOutcome> InstallWrite()
|
||||
{
|
||||
var result = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_node.OnWriteValue = (ISystemContext context, NodeState node, NumericRange range, QualifiedName encoding,
|
||||
ref Variant value, ref StatusCode status, ref DateTimeUtc timestamp) =>
|
||||
{
|
||||
_completion = _manager.ObserveMappedWriteCompletion(result.Task, "v", AddressSpaceRealm.Raw,
|
||||
SdkValueBoundary.ToClr(value), SdkValueBoundary.ToClr(_node.Value), _node.StatusCode,
|
||||
_node.Timestamp.ToDateTime(), _node.ActiveWriteStamp!.Value);
|
||||
return ServiceResult.Good;
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
private ServiceResult Write(int value) => _node.WriteAttribute(new ServerSystemContext(_server.CurrentInstance),
|
||||
Attributes.Value, default, new Opc.Ua.DataValue(Variant.From(value)));
|
||||
|
||||
}
|
||||
+57
@@ -208,6 +208,63 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
old.IsActive.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
[Trait("Phase", "P05")]
|
||||
public async Task Coordinator_backed_source_callback_does_not_wait_for_role_refresh_fence()
|
||||
{
|
||||
var fence = new DataWriteDispatchFence();
|
||||
var authority = new DataPlaneAuthorityState(fence);
|
||||
var activation = new CatalogActivation(fence);
|
||||
var liveServing = BootIdentity;
|
||||
var coordinator = new LocalCatalogCoordinator(activation, authority, () => Volatile.Read(ref liveServing));
|
||||
var attempt = Prepare(coordinator, Artifact());
|
||||
coordinator.Complete(attempt, true).ShouldBeTrue();
|
||||
coordinator.Current.ShouldNotBeNull().Serving.Role.ShouldBe("Primary");
|
||||
using var hub = HubTest.Create(bytes: 1_000_000);
|
||||
var publisher = new SourceSamplePublisher(hub, () => coordinator.Serving);
|
||||
var producer = publisher.RegisterDriverIncarnation("driver");
|
||||
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType("Int32", false)).ShouldBeTrue();
|
||||
publisher.EnsureDriverBinding("cluster", "driver", "ref", producer).ShouldBeTrue();
|
||||
publisher.TryCaptureDriver("driver", "ref", producer, out var ticket).ShouldBeTrue();
|
||||
var initialTime = new DateTime(2026, 11, 15, 8, 0, 0, DateTimeKind.Utc);
|
||||
publisher.TryPublish(ticket, new DataValueSnapshot(1, OpcUaStatus.Good, initialTime, null)).ShouldBeTrue();
|
||||
Volatile.Write(ref liveServing, BootIdentity with { Role = "Secondary" });
|
||||
|
||||
using var release = new ManualResetEventSlim();
|
||||
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var holder = Task.Run(() =>
|
||||
{
|
||||
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); }
|
||||
}, TestContext.Current.CancellationToken);
|
||||
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var callback = Task.Run(() =>
|
||||
{
|
||||
started.TrySetResult();
|
||||
return publisher.TryPublish(ticket, new DataValueSnapshot(2, OpcUaStatus.Good, initialTime.AddSeconds(1), null));
|
||||
}, TestContext.Current.CancellationToken);
|
||||
bool returnedBeforeRelease;
|
||||
try
|
||||
{
|
||||
await started.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
returnedBeforeRelease = ReferenceEquals(await Task.WhenAny(callback,
|
||||
Task.Delay(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)), callback);
|
||||
}
|
||||
finally { release.Set(); }
|
||||
await holder.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await callback.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
|
||||
returnedBeforeRelease.ShouldBeTrue("a source callback must not wait for a dispatch-fence holder");
|
||||
publisher.IsDriverIncarnationActive("driver", producer).ShouldBeTrue();
|
||||
publisher.TryCaptureDriver("driver", "ref", producer, out var current).ShouldBeTrue();
|
||||
var freshTime = initialTime.AddSeconds(2);
|
||||
publisher.TryPublish(current, new DataValueSnapshot(3, OpcUaStatus.Good, freshTime, null)).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var fresh = hub.Read(current);
|
||||
fresh.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(3);
|
||||
fresh.Sample!.SourceTimestampUtc.ShouldBe(new DateTimeOffset(freshTime));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_and_publish_actor_join_one_attempt_and_wait_for_successful_topology()
|
||||
{
|
||||
|
||||
+677
@@ -0,0 +1,677 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Akka.Actor;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
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.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
|
||||
public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
|
||||
{
|
||||
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
[Fact]
|
||||
public async Task Revocation_after_actor_launch_but_before_the_invoker_delegate_prevents_the_device_call()
|
||||
{
|
||||
var driver = new RichDriver();
|
||||
var gate = new RecordingGate();
|
||||
var invoker = new PausedWriteInvoker();
|
||||
var observer = new LateWriteObserver(2, TimeSpan.FromMinutes(1));
|
||||
var actor = Connect(driver, gate, observer, invoker);
|
||||
var (ticket, claim) = NewWrite("one", 1);
|
||||
var response = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
|
||||
|
||||
await invoker.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
gate.Revoke();
|
||||
invoker.Release.TrySetResult();
|
||||
|
||||
(await response.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
driver.Calls.ShouldBe(0);
|
||||
claim.IsDispatched.ShouldBeFalse();
|
||||
invoker.SawIdempotent.ShouldBeFalse("writes must not be retried");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("unchanged")]
|
||||
[InlineData("key-version")]
|
||||
[InlineData("key-principal")]
|
||||
[InlineData("expiry")]
|
||||
[InlineData("remap")]
|
||||
[InlineData("role")]
|
||||
[InlineData("host-role-event")]
|
||||
[InlineData("host-membership-event")]
|
||||
[InlineData("incarnation")]
|
||||
[InlineData("current-key-expiry-fence")]
|
||||
public async Task Real_catalog_policy_and_actor_revalidate_at_the_driver_invocation(string change)
|
||||
{
|
||||
var clock = new PolicyCompletionClock();
|
||||
var fence = new DataWriteDispatchFence();
|
||||
var authority = new DataPlaneAuthorityState(fence);
|
||||
var activation = new CatalogActivation(fence);
|
||||
var role = new RedundancyRoleView(fence);
|
||||
role.PublishPrimaryRole(true);
|
||||
var serving = new ServingIdentity("node-a", "serving", "Primary", 0, 0);
|
||||
var coordinator = new LocalCatalogCoordinator(activation, authority, () => serving);
|
||||
var bytes = Encoding.UTF8.GetBytes("""
|
||||
{
|
||||
"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
|
||||
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
|
||||
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
|
||||
"NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":16}],
|
||||
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
|
||||
"DriverInstances":[{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}],
|
||||
"Devices":[{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}],
|
||||
"Tags":[{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}],
|
||||
"TagGroups":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
|
||||
"DataConnections":[],"RemoteNamespaceMappings":[],
|
||||
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":8}]
|
||||
}
|
||||
""");
|
||||
if (change == "current-key-expiry-fence")
|
||||
{
|
||||
var root = JsonNode.Parse(bytes)!.AsObject();
|
||||
root["ApiKeys"]![0]!["ExpiresUtc"] = clock.GetUtcNow().AddSeconds(1).UtcDateTime.ToString("O");
|
||||
bytes = Encoding.UTF8.GetBytes(root.ToJsonString());
|
||||
}
|
||||
var attempt = coordinator.BeginAttempt("catalog-revision");
|
||||
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
|
||||
using (var parsed = DeploymentArtifact.Open(bytes))
|
||||
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue();
|
||||
coordinator.Complete(attempt, true).ShouldBeTrue();
|
||||
var catalog = coordinator.Current.ShouldNotBeNull();
|
||||
var node = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
|
||||
node.Metadata.Writable.ShouldBeTrue();
|
||||
var key = authority.Current.FindUsableKey("peer-key", clock.GetUtcNow().UtcDateTime).ShouldNotBeNull();
|
||||
DateTimeOffset? callerExpiry = change == "current-key-expiry-fence" ? null
|
||||
: clock.GetUtcNow() + (change == "expiry" ? TimeSpan.FromSeconds(1) : TimeSpan.FromMinutes(5));
|
||||
var invoker = new PausedWriteInvoker();
|
||||
var driver = new RichDriver();
|
||||
var routes = new WriteRouteState(fence);
|
||||
var policy = new DataOperationPolicy(authority,
|
||||
new CompletionSignalingEvaluator(new TriePermissionEvaluator(authority.Tries, clock), clock), clock);
|
||||
var gate = new DataWriteDispatchGate(coordinator, activation, authority, policy, role, routes, clock,
|
||||
new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
|
||||
BlockingHistorization? blockedHistorization = null;
|
||||
BlockingHistoryUpdate? blockedHistoryUpdate = null;
|
||||
IActorRef? roleHost = null;
|
||||
var memberCount = 1;
|
||||
if (change is "host-role-event" or "host-membership-event")
|
||||
{
|
||||
if (change == "host-role-event") blockedHistorization = new BlockingHistorization();
|
||||
else blockedHistoryUpdate = new BlockingHistoryUpdate();
|
||||
roleHost = Sys.ActorOf(DriverHostActor.Props(NewInMemoryDbFactory(),
|
||||
ZB.MOM.WW.OtOpcUa.Commons.Types.NodeId.Parse("node-a"),
|
||||
localRoles: new HashSet<string> { "driver" }, primaryRoleSource: role,
|
||||
historizationRoleView: blockedHistorization, historyUpdateRoleView: blockedHistoryUpdate,
|
||||
driverMemberCountProvider: () => Volatile.Read(ref memberCount)));
|
||||
await roleHost.Ask<ActorIdentity>(new Identify("host-started"), Timeout, TestContext.Current.CancellationToken);
|
||||
}
|
||||
var actor = Connect(driver, gate, new LateWriteObserver(2, TimeSpan.FromMinutes(1), clock), invoker,
|
||||
writeTimeout: TimeSpan.FromSeconds(10), writeClock: clock, writeRouteState: routes);
|
||||
var incarnation = routes.CurrentDriverIncarnation("driver").ShouldNotBeNull();
|
||||
var target = routes.Publish(node.Metadata.View, "driver", "Plant/Driver/Device/Speed", incarnation);
|
||||
var now = clock.GetTimestamp();
|
||||
var admission = new DataWriteAdmission("peer", node.Metadata.View, catalog.AuthorityEpoch,
|
||||
catalog.Serving.CatalogEpoch, "serving", incarnation, "real-gate", now + 60 * clock.TimestampFrequency,
|
||||
key.ApiKeyId, callerExpiry, DataCallerIdentity.CredentialVersionFor(key));
|
||||
var proof = new WriteRouteProof(admission,
|
||||
new(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray()),
|
||||
node.EntityKind, node.EntityId, node.Source, "driver", target.DriverReference,
|
||||
target.RouteGeneration, role.PrimaryGeneration);
|
||||
var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, 7), now);
|
||||
var registry = new WriteOperationRegistry("serving", 8, 8192, TimeSpan.FromMinutes(1), clock);
|
||||
var claim = registry.Claim("peer", "real-gate", "serving", SHA256.HashData([1, 2, 3])).Claim.ShouldNotBeNull();
|
||||
var response = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
await invoker.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
switch (change)
|
||||
{
|
||||
case "key-version":
|
||||
case "key-principal":
|
||||
authority.Apply("cluster", "changed", [new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Enabled = true,
|
||||
Principal = change == "key-principal" ? "other" : "peer", SecretHash = change == "key-version" ? "replacement" : "hash" }],
|
||||
[new NodeAcl { NodeAclId = "acl", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster,
|
||||
PermissionFlags = NodePermissions.WriteOperate }], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
break;
|
||||
case "expiry": clock.Advance(TimeSpan.FromSeconds(2)); break;
|
||||
case "remap": routes.Publish(node.Metadata.View, "other", "other/path", "other-incarnation"); break;
|
||||
case "role": role.PublishPrimaryRole(false); role.PublishPrimaryRole(true); break;
|
||||
case "incarnation": routes.RetireDriver("driver", incarnation); routes.BeginDriverIncarnation("driver"); break;
|
||||
case "current-key-expiry-fence":
|
||||
{
|
||||
using var releaseFence = new ManualResetEventSlim();
|
||||
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var holder = Task.Run(() =>
|
||||
{
|
||||
using (fence.Enter()) { held.TrySetResult(); releaseFence.Wait(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); }
|
||||
}, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await held.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
invoker.Release.TrySetResult();
|
||||
// The wrapped evaluator arms a signal for the *last* policy UTC read. It returns
|
||||
// the captured pre-expiry instant even if the test advances the clock immediately.
|
||||
await clock.AfterPolicyUtc.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
clock.Advance(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
finally { releaseFence.Set(); await holder.WaitAsync(Timeout, TestContext.Current.CancellationToken); }
|
||||
break;
|
||||
}
|
||||
case "host-role-event":
|
||||
blockedHistorization!.Arm();
|
||||
roleHost!.Tell(new RedundancyStateChanged([
|
||||
new NodeRedundancyState(ZB.MOM.WW.OtOpcUa.Commons.Types.NodeId.Parse("node-a"), RedundancyRole.Secondary,
|
||||
IsClusterLeader: false, IsDriverPrimary: false, AsOfUtc: DateTime.UtcNow)], CorrelationId.NewId()));
|
||||
await blockedHistorization!.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
role.ShouldActAsPrimary.ShouldBeFalse("the write verdict must publish before the historian callback can block");
|
||||
role.PrimaryGeneration.ShouldBeGreaterThan(proof.PrimaryGeneration);
|
||||
break;
|
||||
case "host-membership-event":
|
||||
blockedHistoryUpdate!.Arm();
|
||||
Volatile.Write(ref memberCount, 2);
|
||||
roleHost!.Tell(new Akka.Cluster.ClusterEvent.MemberUp(Akka.Cluster.Cluster.Get(Sys).SelfMember));
|
||||
await blockedHistoryUpdate.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
role.ShouldActAsPrimary.ShouldBeFalse("MemberUp must publish the write verdict before the history-update callback blocks");
|
||||
role.PrimaryGeneration.ShouldBeGreaterThan(proof.PrimaryGeneration);
|
||||
break;
|
||||
}
|
||||
invoker.Release.TrySetResult();
|
||||
var outcome = await response.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
if (change == "unchanged")
|
||||
{ outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); driver.Calls.ShouldBe(1); }
|
||||
else
|
||||
{ outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); driver.Calls.ShouldBe(0); claim.IsDispatched.ShouldBeFalse(); }
|
||||
}
|
||||
finally { blockedHistorization?.Release.Set(); blockedHistoryUpdate?.Release.Set(); invoker.Release.TrySetResult(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_terminal_proven_no_call_claim_cannot_invoke_a_driver_after_its_ticket_is_released()
|
||||
{
|
||||
var driver = new RichDriver();
|
||||
var invoker = new PausedWriteInvoker();
|
||||
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)), invoker);
|
||||
var (ticket, claim) = NewWrite("no-call", 1);
|
||||
var response = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
|
||||
await invoker.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
|
||||
claim.Complete(new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "deadline before dispatch")).ShouldBeTrue();
|
||||
ticket.Dispose();
|
||||
invoker.Release.TrySetResult();
|
||||
(await response.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
claim.IsDispatched.ShouldBeFalse();
|
||||
driver.Calls.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Queued_write_revalidates_after_an_earlier_write_finishes()
|
||||
{
|
||||
var driver = new RichDriver { Hold = true };
|
||||
var gate = new RecordingGate();
|
||||
var observer = new LateWriteObserver(2, TimeSpan.FromMinutes(1));
|
||||
var actor = Connect(driver, gate, observer, maxWrites: 1);
|
||||
var (firstTicket, firstClaim) = NewWrite("first", 1);
|
||||
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(firstTicket, firstClaim), Timeout, TestContext.Current.CancellationToken);
|
||||
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
|
||||
var (secondTicket, secondClaim) = NewWrite("second", 2);
|
||||
var probe = CreateTestProbe();
|
||||
probe.Send(actor, new DriverInstanceActor.WriteAttributeWithOutcome(secondTicket, secondClaim));
|
||||
probe.Send(actor, new Identify("queue-barrier"));
|
||||
probe.ExpectMsg<ActorIdentity>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
gate.Revoke();
|
||||
driver.Release.TrySetResult();
|
||||
|
||||
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
probe.ExpectMsg<DataWriteOutcome>(Timeout, cancellationToken: TestContext.Current.CancellationToken).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
driver.Calls.ShouldBe(1);
|
||||
secondClaim.IsDispatched.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Legacy_good_without_an_explicit_completion_guarantee_is_unconfirmed()
|
||||
{
|
||||
var driver = new LegacyDriver();
|
||||
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
|
||||
var (ticket, claim) = NewWrite("legacy", 1);
|
||||
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
|
||||
result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
driver.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Token_ignoring_driver_stays_charged_and_its_actual_late_success_refines_unknown()
|
||||
{
|
||||
var driver = new RichDriver { Hold = true };
|
||||
var observer = new LateWriteObserver(1, TimeSpan.FromMinutes(1));
|
||||
var actor = Connect(driver, new RecordingGate(), observer, maxWrites: 1,
|
||||
writeTimeout: TimeSpan.FromMilliseconds(200));
|
||||
var (ticket, claim) = NewWrite("hung", 1);
|
||||
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
|
||||
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
|
||||
// The actor has abandoned its wait, but the actual token-ignoring driver is still alive.
|
||||
// A second operation cannot escape the separate physical outstanding-call limit.
|
||||
var (secondTicket, secondClaim) = NewWrite("capacity", 2);
|
||||
var second = await actor.Ask<DataWriteOutcome>(
|
||||
new DriverInstanceActor.WriteAttributeWithOutcome(secondTicket, secondClaim), Timeout, TestContext.Current.CancellationToken);
|
||||
second.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
secondClaim.IsDispatched.ShouldBeFalse();
|
||||
driver.Calls.ShouldBe(1);
|
||||
|
||||
driver.Release.TrySetResult();
|
||||
AwaitCondition(() => claim.CurrentOutcome?.State == DataWriteState.DriverConfirmedSuccess, Timeout, TestContext.Current.CancellationToken);
|
||||
driver.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Timed_out_physical_write_rejects_the_same_target_while_a_different_target_progresses()
|
||||
{
|
||||
var driver = new RichDriver { Hold = true, HoldFirstOnly = true };
|
||||
// The observation window expires before abandonment; physical ownership must still remain.
|
||||
var observer = new LateWriteObserver(2, TimeSpan.FromMilliseconds(50));
|
||||
var actor = Connect(driver, new RecordingGate(), observer, maxWrites: 1,
|
||||
writeTimeout: TimeSpan.FromMilliseconds(200));
|
||||
var (firstTicket, firstClaim) = NewWrite("held", 1, "plant/tag-a");
|
||||
try
|
||||
{
|
||||
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(firstTicket, firstClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
|
||||
var (sameTicket, sameClaim) = NewWrite("same", 2, "plant/tag-a");
|
||||
var same = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(sameTicket, sameClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
same.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
sameClaim.IsDispatched.ShouldBeFalse();
|
||||
driver.Calls.ShouldBe(1, "the first physical write still owns this canonical target");
|
||||
|
||||
var (otherTicket, otherClaim) = NewWrite("other", 3, "plant/tag-b");
|
||||
var other = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(otherTicket, otherClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
other.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
driver.Calls.ShouldBe(2);
|
||||
}
|
||||
finally { driver.Release.TrySetResult(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replacement_actor_cannot_write_a_target_still_held_by_the_previous_actor()
|
||||
{
|
||||
var observer = new LateWriteObserver(2, TimeSpan.FromMinutes(1));
|
||||
var oldDriver = new RichDriver { Hold = true, HoldFirstOnly = true };
|
||||
var oldActor = Connect(oldDriver, new RecordingGate(), observer, maxWrites: 1,
|
||||
writeTimeout: TimeSpan.FromMilliseconds(200));
|
||||
var (oldTicket, oldClaim) = NewWrite("old", 1, "plant/tag-a");
|
||||
try
|
||||
{
|
||||
var first = oldActor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(oldTicket, oldClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
await oldDriver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
Watch(oldActor);
|
||||
Sys.Stop(oldActor);
|
||||
ExpectTerminated(oldActor, Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
var replacementDriver = new RichDriver { DriverInstanceId = "DRIVER" };
|
||||
var replacement = Connect(replacementDriver, new RecordingGate(), observer, maxWrites: 1);
|
||||
var (sameTicket, sameClaim) = NewWrite("replacement-same", 2, "plant/tag-a", "DRIVER");
|
||||
var same = await replacement.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(sameTicket, sameClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
same.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
sameClaim.IsDispatched.ShouldBeFalse();
|
||||
replacementDriver.Calls.ShouldBe(0);
|
||||
|
||||
var (otherTicket, otherClaim) = NewWrite("replacement-other", 3, "plant/tag-b", "DRIVER");
|
||||
var other = await replacement.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(otherTicket, otherClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
other.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
|
||||
oldDriver.Release.TrySetResult();
|
||||
AwaitCondition(() => oldClaim.CurrentOutcome?.State == DataWriteState.DriverConfirmedSuccess,
|
||||
Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
DataWriteOutcome? after = null;
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
var (retryTicket, retryClaim) = NewWrite($"after-{i}", 4, "plant/tag-a", "DRIVER");
|
||||
after = await replacement.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(retryTicket, retryClaim),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
if (after.State == DataWriteState.DriverConfirmedSuccess) break;
|
||||
after.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
}
|
||||
after.ShouldNotBeNull().State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
replacementDriver.Calls.ShouldBe(2, "only the other target and the post-completion write reached the device");
|
||||
}
|
||||
finally { oldDriver.Release.TrySetResult(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Synchronous_driver_throw_after_dispatch_is_unknown()
|
||||
{
|
||||
var driver = new SynchronousThrowDriver();
|
||||
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
|
||||
var (ticket, claim) = NewWrite("throw", 1);
|
||||
var outcome = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
|
||||
outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
claim.IsDispatched.ShouldBeTrue();
|
||||
driver.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_driver_blocking_before_returning_its_task_remains_physically_charged()
|
||||
{
|
||||
using var release = new ManualResetEventSlim();
|
||||
var driver = new SynchronousBlockingDriver(release);
|
||||
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)),
|
||||
maxWrites: 1, writeTimeout: TimeSpan.FromMilliseconds(200));
|
||||
var (ticket, claim) = NewWrite("blocking", 1);
|
||||
var first = actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await driver.Entered.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
(await first.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
var (laterTicket, laterClaim) = NewWrite("later", 2);
|
||||
var later = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(laterTicket, laterClaim), Timeout, TestContext.Current.CancellationToken);
|
||||
later.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
laterClaim.IsDispatched.ShouldBeFalse();
|
||||
driver.Calls.ShouldBe(1);
|
||||
}
|
||||
finally { release.Set(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Supervision_restart_fences_the_old_driver_incarnation_even_when_the_actor_ref_is_reused()
|
||||
{
|
||||
var driver = new RichDriver();
|
||||
var routes = new WriteRouteState(new DataWriteDispatchFence());
|
||||
var parent = CreateTestProbe();
|
||||
var actor = parent.ChildActorOf(DriverInstanceActor.PropsForRichWrites(driver, commsLossTimeout: TimeSpan.Zero,
|
||||
writeRouteState: routes), new OneForOneStrategy(_ => Directive.Restart), TestContext.Current.CancellationToken);
|
||||
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
||||
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
var incarnation = routes.CurrentDriverIncarnation("driver");
|
||||
incarnation.ShouldNotBeNullOrWhiteSpace();
|
||||
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
|
||||
var oldRoute = routes.Publish(view, "driver", "plant/tag", incarnation!);
|
||||
routes.IsCurrent(view, oldRoute).ShouldBeTrue();
|
||||
|
||||
// Restart in place: the same IActorRef addresses a new actor object around the same driver object.
|
||||
actor.Tell(Kill.Instance);
|
||||
parent.FishForMessage(m => m is DriverInstanceActor.ReprovisionRequested, Timeout,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
var replacement = routes.CurrentDriverIncarnation("driver");
|
||||
replacement.ShouldNotBe(incarnation);
|
||||
routes.IsCurrent(view, oldRoute).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Host_retires_the_write_incarnation_before_stopping_a_child(bool operatorRestart)
|
||||
{
|
||||
var db = NewInMemoryDbFactory();
|
||||
var firstRev = RevisionHash.Parse(new string('a', 64));
|
||||
var secondRev = RevisionHash.Parse(new string('b', 64));
|
||||
var raw = new[] { ("driver", "Modbus", "dev1", "speed", "Int32", true) };
|
||||
var first = V3ArtifactSeeder.SeedV3Deployment(db, firstRev, raw, [], enabled: true);
|
||||
var second = V3ArtifactSeeder.SeedV3Deployment(db, secondRev, raw, [], enabled: false);
|
||||
var node = ZB.MOM.WW.OtOpcUa.Commons.Types.NodeId.Parse("node-1:4053");
|
||||
var fence = new DataWriteDispatchFence();
|
||||
var authority = new DataPlaneAuthorityState(fence);
|
||||
var activation = new CatalogActivation(fence);
|
||||
var role = new RedundancyRoleView(fence);
|
||||
var clock = TimeProvider.System;
|
||||
var serving = new ServingIdentity(node.Value, "serving", "Primary", 0, 0);
|
||||
var catalog = new LocalCatalogCoordinator(activation, authority, () => serving);
|
||||
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
|
||||
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var capabilities = new DataCapabilitiesProvider("c1", () => catalog.Serving, () => catalog.Current is not null, limits);
|
||||
var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(300));
|
||||
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock);
|
||||
var runtime = new DataWriteRuntime(catalog, activation, authority, policy, capabilities, role, clock, bounds,
|
||||
"serving", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1));
|
||||
var driver = new RichDriver();
|
||||
var stopped = new TaskCompletionSource<(string? Incarnation, int Shutdowns)>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
runtime.BeforeDriverStopForTests = id => stopped.TrySetResult((runtime.Routes.CurrentDriverIncarnation(id), driver.Shutdowns));
|
||||
var acks = CreateTestProbe();
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(db, node, acks.Ref, driverFactory: new SingleDriverFactory(driver),
|
||||
localRoles: new HashSet<string> { "driver" }, primaryRoleSource: role, catalogCoordinator: catalog,
|
||||
writeBounds: bounds, writeClock: clock, dataWriteRuntime: runtime));
|
||||
host.Tell(new DispatchDeployment(first, firstRev, CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitCondition(() => runtime.Routes.CurrentDriverIncarnation("driver") is not null, Timeout, TestContext.Current.CancellationToken);
|
||||
if (operatorRestart) host.Tell(new RestartDriver("c1", "driver", "tester", Guid.NewGuid()));
|
||||
else host.Tell(new DispatchDeployment(second, secondRev, CorrelationId.NewId()));
|
||||
|
||||
var observed = await stopped.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
observed.Shutdowns.ShouldBe(0, "the child has not yet run PostStop");
|
||||
observed.Incarnation.ShouldBeNull("host retirement must precede the asynchronous child stop");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Gateway_timeout_uses_the_injected_write_clock_and_proves_no_call_before_rejection()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(100));
|
||||
var role = new RedundancyRoleView(new DataWriteDispatchFence());
|
||||
var routes = new WriteRouteState(role.DispatchFence);
|
||||
var host = CreateTestProbe();
|
||||
var route = new ActorDataWriteRoute(() => host.Ref, routes, role, bounds, clock);
|
||||
var (ticket, claim) = NewWrite("gateway-timeout", 1);
|
||||
var pending = route.DispatchAsync(ticket, claim, CancellationToken.None);
|
||||
host.ExpectMsg<DriverHostActor.RouteRichWrite>(Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
await clock.WaitForTimerDueAtAsync(clock.Start + bounds.GatewayAsk, Timeout);
|
||||
pending.IsCompleted.ShouldBeFalse();
|
||||
clock.Advance(bounds.GatewayAsk);
|
||||
(await pending.WaitAsync(Timeout, TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
claim.IsDispatched.ShouldBeFalse();
|
||||
}
|
||||
|
||||
private IActorRef Connect(IDriver driver, IWriteDispatchGate gate, LateWriteObserver observer,
|
||||
IDriverCapabilityInvoker? invoker = null, int maxWrites = 4, TimeSpan? writeTimeout = null,
|
||||
TimeProvider? writeClock = null, WriteRouteState? writeRouteState = null)
|
||||
{
|
||||
var parent = CreateTestProbe();
|
||||
var actor = parent.ChildActorOf(DriverInstanceActor.PropsForRichWrites(driver, invoker: invoker,
|
||||
commsLossTimeout: TimeSpan.Zero, maxWritesInFlight: maxWrites,
|
||||
writeTimeout: writeTimeout ?? Timeout, writeDispatchGate: gate, lateWriteObserver: observer,
|
||||
writeClock: writeClock, writeRouteState: writeRouteState));
|
||||
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
||||
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
return actor;
|
||||
}
|
||||
|
||||
private static (WriteAdmissionTicket Ticket, WriteClaim Claim) NewWrite(string operation, int value,
|
||||
string driverReference = "plant/tag", string driverInstanceId = "driver")
|
||||
{
|
||||
var now = TimeProvider.System.GetTimestamp();
|
||||
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
|
||||
var admission = new DataWriteAdmission("peer", view, 1, 1, "serving", "driver-incarnation", operation,
|
||||
now + 60 * TimeProvider.System.TimestampFrequency, "key", DateTimeOffset.UtcNow.AddMinutes(1), "key-version");
|
||||
var scope = new FrozenWriteScope("cluster", NodeHierarchyKind.Raw, ImmutableArray.Create("plant", "tag"));
|
||||
var proof = new WriteRouteProof(admission, scope, "RawTag", "tag", null, driverInstanceId, driverReference, 1, 1);
|
||||
var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, value), now);
|
||||
var registry = new WriteOperationRegistry("serving", 8, 8192, TimeSpan.FromMinutes(1));
|
||||
var claim = registry.Claim("peer", operation, "serving", SHA256.HashData(Encoding.UTF8.GetBytes(operation))).Claim!;
|
||||
return (ticket, claim);
|
||||
}
|
||||
|
||||
private sealed class RecordingGate : IWriteDispatchGate
|
||||
{
|
||||
private int _revoked;
|
||||
public void Revoke() => Volatile.Write(ref _revoked, 1);
|
||||
public DataWriteOutcome? TryCommit(WriteAdmissionTicket ticket, WriteClaim claim)
|
||||
{
|
||||
if (Volatile.Read(ref _revoked) != 0)
|
||||
return new(DataWriteState.RejectedBeforeDispatch, 0x801F0000u, "revoked");
|
||||
if (!claim.TryMarkDispatched())
|
||||
return new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "claim already terminal");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private class LegacyDriver : IDriver, IWritable
|
||||
{
|
||||
private int _calls;
|
||||
private int _shutdowns;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public int Shutdowns => Volatile.Read(ref _shutdowns);
|
||||
protected void RecordCall() => Interlocked.Increment(ref _calls);
|
||||
public string DriverInstanceId { get; init; } = "driver";
|
||||
public string DriverType => "test";
|
||||
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
public Task ShutdownAsync(CancellationToken cancellationToken) { Interlocked.Increment(ref _shutdowns); return Task.CompletedTask; }
|
||||
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
{
|
||||
RecordCall();
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>([new(0)]);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SingleDriverFactory(IDriver driver) : IDriverFactory
|
||||
{
|
||||
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
|
||||
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) => driver;
|
||||
}
|
||||
|
||||
private sealed class BlockingHistorization : IHistorizationRoleView
|
||||
{
|
||||
private int _armed;
|
||||
public bool ShouldRecordHistorizedValues => true;
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ManualResetEventSlim Release { get; } = new();
|
||||
public void Arm() => Volatile.Write(ref _armed, 1);
|
||||
public void PublishHistorizationRole(bool shouldRecordHistorizedValues)
|
||||
{
|
||||
if (Volatile.Read(ref _armed) == 0) return;
|
||||
Entered.TrySetResult();
|
||||
Release.Wait(TimeSpan.FromSeconds(15), CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class BlockingHistoryUpdate : IHistoryUpdateRoleView
|
||||
{
|
||||
private int _armed;
|
||||
public bool ShouldServeHistoryUpdate => false;
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ManualResetEventSlim Release { get; } = new();
|
||||
public void Arm() => Volatile.Write(ref _armed, 1);
|
||||
public void PublishHistoryUpdateRole(bool shouldServeHistoryUpdate)
|
||||
{
|
||||
if (Volatile.Read(ref _armed) == 0) return;
|
||||
Entered.TrySetResult();
|
||||
Release.Wait(TimeSpan.FromSeconds(15), CancellationToken.None);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PolicyCompletionClock : TimeProvider
|
||||
{
|
||||
private readonly ManualTimeProvider _inner = new();
|
||||
private int _signalNextUtc;
|
||||
public TaskCompletionSource AfterPolicyUtc { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public void SignalAfterEvaluation() => Volatile.Write(ref _signalNextUtc, 1);
|
||||
public void Advance(TimeSpan by) => _inner.Advance(by);
|
||||
public override long TimestampFrequency => _inner.TimestampFrequency;
|
||||
public override long GetTimestamp() => _inner.GetTimestamp();
|
||||
public override DateTimeOffset GetUtcNow()
|
||||
{
|
||||
var captured = _inner.GetUtcNow();
|
||||
if (Interlocked.Exchange(ref _signalNextUtc, 0) != 0) AfterPolicyUtc.TrySetResult();
|
||||
return captured;
|
||||
}
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) =>
|
||||
_inner.CreateTimer(callback, state, dueTime, period);
|
||||
}
|
||||
|
||||
private sealed class CompletionSignalingEvaluator(IPermissionEvaluator inner, PolicyCompletionClock clock) : IPermissionEvaluator
|
||||
{
|
||||
public AuthorizationDecision Authorize(UserAuthorizationState session, OpcUaOperation operation, NodeScope scope)
|
||||
{
|
||||
var result = inner.Authorize(session, operation, scope);
|
||||
clock.SignalAfterEvaluation();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RichDriver : LegacyDriver, IWriteOutcomeCapability
|
||||
{
|
||||
public bool Hold { get; init; }
|
||||
public bool HoldFirstOnly { get; init; }
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public async Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RecordCall();
|
||||
Entered.TrySetResult();
|
||||
if (Hold && (!HoldFirstOnly || Calls == 1)) await Release.Task;
|
||||
return [new(DataWriteState.DriverConfirmedSuccess, 0, null)];
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SynchronousThrowDriver : LegacyDriver, IWriteOutcomeCapability
|
||||
{
|
||||
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RecordCall();
|
||||
throw new InvalidOperationException("driver failed before returning a task");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SynchronousBlockingDriver(ManualResetEventSlim release) : LegacyDriver, IWriteOutcomeCapability
|
||||
{
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RecordCall();
|
||||
Entered.TrySetResult();
|
||||
release.Wait(TimeSpan.FromSeconds(15), CancellationToken.None);
|
||||
return Task.FromResult<IReadOnlyList<DataWriteOutcome>>([new(DataWriteState.DriverConfirmedSuccess, 0, null)]);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class PausedWriteInvoker : IDriverCapabilityInvoker
|
||||
{
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public bool SawIdempotent { get; private set; }
|
||||
public ValueTask<TResult> ExecuteAsync<TResult>(DriverCapability capability, string hostName,
|
||||
Func<CancellationToken, ValueTask<TResult>> callSite, CancellationToken cancellationToken) => callSite(cancellationToken);
|
||||
public ValueTask ExecuteAsync(DriverCapability capability, string hostName,
|
||||
Func<CancellationToken, ValueTask> callSite, CancellationToken cancellationToken) => callSite(cancellationToken);
|
||||
public async ValueTask<TResult> ExecuteWriteAsync<TResult>(string hostName, bool isIdempotent,
|
||||
Func<CancellationToken, ValueTask<TResult>> callSite, CancellationToken cancellationToken)
|
||||
{
|
||||
SawIdempotent = isIdempotent;
|
||||
Entered.TrySetResult();
|
||||
await Release.Task;
|
||||
return await callSite(cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P05")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataLateWriteTests
|
||||
{
|
||||
private static readonly DataWriteOutcome Unknown = new(DataWriteState.OutcomeUnknown, 0, null);
|
||||
private static readonly DataWriteOutcome Success = new(DataWriteState.DriverConfirmedSuccess, 0, null);
|
||||
private static WriteClaim DispatchedClaim()
|
||||
{
|
||||
var registry = new WriteOperationRegistry("inc", 2, 4096, TimeSpan.FromMinutes(1));
|
||||
var claim = registry.Claim("p", "op", "inc", new byte[32]).Claim!;
|
||||
claim.TryMarkDispatched().ShouldBeTrue();
|
||||
claim.Complete(Unknown).ShouldBeTrue();
|
||||
return claim;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reserved_observer_records_actual_late_result_and_releases_owned_lifetime()
|
||||
{
|
||||
var observer = new LateWriteObserver(1, TimeSpan.FromSeconds(10));
|
||||
var claim = DispatchedClaim();
|
||||
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var lifetime = new CountingLifetime();
|
||||
observer.TryReserve(out var reservation).ShouldBeTrue();
|
||||
reservation!.Observe(source.Task, claim, lifetime);
|
||||
observer.TryReserve(out _).ShouldBeFalse();
|
||||
source.SetResult(Success);
|
||||
await WaitUntil(() => claim.CurrentOutcome == Success && lifetime.Count == 1);
|
||||
(await claim.Completion).ShouldBe(Unknown);
|
||||
observer.TryReserve(out var next).ShouldBeTrue();
|
||||
next!.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Expired_observer_retains_physical_capacity_and_lifetime_until_driver_really_finishes()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var observer = new LateWriteObserver(1, TimeSpan.FromSeconds(10), clock);
|
||||
var claim = DispatchedClaim();
|
||||
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var lifetime = new CountingLifetime();
|
||||
observer.TryReserve(out var reservation).ShouldBeTrue();
|
||||
reservation!.Observe(source.Task, claim, lifetime);
|
||||
clock.Advance(TimeSpan.FromSeconds(11));
|
||||
observer.TryReserve(out _).ShouldBeFalse();
|
||||
lifetime.Count.ShouldBe(0);
|
||||
source.SetResult(Success);
|
||||
await WaitUntil(() => lifetime.Count == 1);
|
||||
claim.CurrentOutcome.ShouldBe(Unknown);
|
||||
observer.TryReserve(out var next).ShouldBeTrue();
|
||||
next!.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Already_completed_driver_is_observed_and_reservation_dispose_is_idempotent()
|
||||
{
|
||||
var observer = new LateWriteObserver(1, TimeSpan.FromSeconds(10));
|
||||
var claim = DispatchedClaim();
|
||||
var lifetime = new CountingLifetime();
|
||||
observer.TryReserve(out var reservation).ShouldBeTrue();
|
||||
reservation!.Observe(Task.FromResult(Success), claim, lifetime);
|
||||
reservation.Dispose();
|
||||
await WaitUntil(() => lifetime.Count == 1 && claim.CurrentOutcome == Success);
|
||||
observer.TryReserve(out var next).ShouldBeTrue();
|
||||
next!.Dispose();
|
||||
next.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Confirmation_after_unknown_retention_gets_its_own_retry_window()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var registry = new WriteOperationRegistry("inc", 1, 4096, TimeSpan.FromMinutes(1), clock);
|
||||
var claim = registry.Claim("p", "op", "inc", new byte[32]).Claim!;
|
||||
claim.TryMarkDispatched().ShouldBeTrue();
|
||||
claim.Complete(Unknown).ShouldBeTrue();
|
||||
var observer = new LateWriteObserver(1, TimeSpan.FromMinutes(5), clock);
|
||||
var source = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var lifetime = new CountingLifetime();
|
||||
observer.TryReserve(out var reservation).ShouldBeTrue();
|
||||
reservation!.Observe(source.Task, claim, lifetime);
|
||||
clock.Advance(TimeSpan.FromMinutes(2));
|
||||
source.SetResult(Success);
|
||||
await WaitUntil(() => lifetime.Count == 1);
|
||||
var duplicate = registry.Claim("p", "op", "inc", new byte[32]);
|
||||
duplicate.Kind.ShouldBe(WriteClaimKind.Existing);
|
||||
duplicate.Claim!.CurrentOutcome.ShouldBe(Success);
|
||||
(await duplicate.Claim.Completion).ShouldBe(Unknown);
|
||||
}
|
||||
|
||||
private static async Task WaitUntil(Func<bool> condition)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
while (!condition()) await Task.Delay(1, timeout.Token);
|
||||
}
|
||||
|
||||
private sealed class CountingLifetime : IDisposable
|
||||
{
|
||||
private int _count;
|
||||
public int Count => Volatile.Read(ref _count);
|
||||
public void Dispose() => Interlocked.Increment(ref _count);
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
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.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
|
||||
public sealed class GrpcDataWriteAdmissionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Authority_publication_is_ordered_with_dispatch_and_notifications_run_outside_the_fence()
|
||||
{
|
||||
var fence = new DataWriteDispatchFence();
|
||||
var authority = new DataPlaneAuthorityState(fence);
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var notificationCanEnter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
authority.Changed += snapshot =>
|
||||
{
|
||||
// A different thread must acquire the dispatch fence while this callback runs. A reentrant
|
||||
// acquisition on the notification thread would not detect holding the fence across callbacks.
|
||||
var enteredFence = new ManualResetEventSlim();
|
||||
_ = Task.Run(() => { using (fence.Enter()) enteredFence.Set(); }, TestContext.Current.CancellationToken);
|
||||
notificationCanEnter.TrySetResult(enteredFence.Wait(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken));
|
||||
};
|
||||
|
||||
using var release = new ManualResetEventSlim();
|
||||
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var owner = Task.Run(() =>
|
||||
{
|
||||
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
||||
}, TestContext.Current.CancellationToken);
|
||||
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var apply = Task.Run(() =>
|
||||
{
|
||||
entered.TrySetResult();
|
||||
authority.Apply("cluster", "revision-1", Array.Empty<ApiKey>(), Array.Empty<NodeAcl>(),
|
||||
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
}, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
// Publication, not merely its Changed event, is ordered against the dispatch commit.
|
||||
(await Task.WhenAny(apply, Task.Delay(150, TestContext.Current.CancellationToken))).ShouldNotBe(apply);
|
||||
authority.Current.HasArtifact.ShouldBeFalse();
|
||||
}
|
||||
finally { release.Set(); }
|
||||
|
||||
await owner.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await apply.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
(await notificationCanEnter.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue("Changed must run outside the dispatch fence");
|
||||
authority.Current.HasArtifact.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_catalog_invalidation_cannot_publish_inside_a_dispatch_commit()
|
||||
{
|
||||
var fence = new DataWriteDispatchFence();
|
||||
var catalog = new CatalogActivation(fence);
|
||||
var epoch = catalog.Begin("first");
|
||||
catalog.AuthorityInstalled(epoch, 1).ShouldBeTrue();
|
||||
catalog.Complete(epoch, true).ShouldBeTrue();
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var release = new ManualResetEventSlim();
|
||||
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var owner = Task.Run(() =>
|
||||
{
|
||||
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
||||
}, TestContext.Current.CancellationToken);
|
||||
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var invalidate = Task.Run(() => { started.TrySetResult(); return catalog.Begin("second"); }, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await started.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
(await Task.WhenAny(invalidate, Task.Delay(150, TestContext.Current.CancellationToken))).ShouldNotBe(invalidate);
|
||||
catalog.Current.IsReady.ShouldBeTrue();
|
||||
}
|
||||
finally { release.Set(); }
|
||||
|
||||
await owner.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
(await invalidate.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeGreaterThan(epoch);
|
||||
catalog.Current.IsReady.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Demotion_and_repromotion_advance_the_primary_generation_even_when_the_final_verdict_matches()
|
||||
{
|
||||
var role = new RedundancyRoleView(new DataWriteDispatchFence());
|
||||
role.PublishPrimaryRole(true);
|
||||
var before = role.PrimaryGeneration;
|
||||
role.PublishPrimaryRole(false);
|
||||
var demoted = role.PrimaryGeneration;
|
||||
role.PublishPrimaryRole(true);
|
||||
|
||||
demoted.ShouldBeGreaterThan(before);
|
||||
role.PrimaryGeneration.ShouldBeGreaterThan(demoted);
|
||||
role.ShouldActAsPrimary.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void First_primary_publication_establishes_a_generation_without_heartbeat_churn()
|
||||
{
|
||||
var role = new RedundancyRoleView(new DataWriteDispatchFence());
|
||||
role.ShouldActAsPrimary.ShouldBeTrue(); // the legacy seed is preserved
|
||||
role.PrimaryGeneration.ShouldBe(0);
|
||||
role.PublishPrimaryRole(true);
|
||||
var established = role.PrimaryGeneration;
|
||||
established.ShouldBeGreaterThan(0);
|
||||
role.PublishPrimaryRole(true);
|
||||
role.PrimaryGeneration.ShouldBe(established);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Route_proof_is_invalidated_by_remap_and_does_not_revive_when_the_original_route_returns()
|
||||
{
|
||||
var state = new WriteRouteState(new DataWriteDispatchFence());
|
||||
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
|
||||
var original = state.Publish(view, "driver", "plant/tag", "incarnation-1");
|
||||
state.IsCurrent(view, original).ShouldBeTrue();
|
||||
state.Publish(view, "other-driver", "plant/other", "incarnation-2");
|
||||
state.IsCurrent(view, original).ShouldBeFalse();
|
||||
var restored = state.Publish(view, "driver", "plant/tag", "incarnation-1");
|
||||
state.IsCurrent(view, original).ShouldBeFalse();
|
||||
state.IsCurrent(view, restored).ShouldBeTrue();
|
||||
restored.RouteGeneration.ShouldBeGreaterThan(original.RouteGeneration);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Executor_keeps_partial_batch_results_in_input_order_and_does_not_dispatch_a_type_mismatch()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var route = new RecordingRoute(fixture.Raw);
|
||||
var executor = CreateExecutor(fixture, route);
|
||||
using var first = DataValue.FromScalar(DataValueKind.Int32, 1);
|
||||
using var wrong = DataValue.FromScalar(DataValueKind.String, "wrong type");
|
||||
using var last = DataValue.FromScalar(DataValueKind.Int32, 2);
|
||||
var remaining = TimeSpan.FromSeconds(5);
|
||||
var results = await executor.WriteAsync(new([
|
||||
new("a", "ok", fixture.Raw, first, 1, fixture.Serving.Incarnation, remaining),
|
||||
new("b", "bad-type", fixture.Raw, wrong, 1, fixture.Serving.Incarnation, remaining),
|
||||
new("c", "failed", fixture.Raw, last, 1, fixture.Serving.Incarnation, remaining)],
|
||||
LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
|
||||
results.Select(x => x.CorrelationId).ShouldBe(["a", "b", "c"]);
|
||||
results.Select(x => x.Outcome.State).ShouldBe([DataWriteState.DriverConfirmedSuccess,
|
||||
DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedFailure]);
|
||||
route.Dispatched.Order().ShouldBe(["failed", "ok"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Executor_joins_concurrent_duplicate_with_a_different_remaining_budget()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var route = new RecordingRoute(fixture.Raw) { Hold = true };
|
||||
var executor = CreateExecutor(fixture, route);
|
||||
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
using var duplicateValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
var first = executor.WriteAsync(new([new("first", "same-operation", fixture.Raw, firstValue, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var duplicate = executor.WriteAsync(new([new("duplicate", "same-operation", fixture.Raw, duplicateValue, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(4))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
route.Release.TrySetResult();
|
||||
|
||||
var firstResult = await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var duplicateResult = await duplicate.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
firstResult.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
duplicateResult.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
route.Dispatched.ShouldBe(["same-operation"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Equivalent_origin_cluster_spelling_uses_the_catalog_resolved_view_for_duplicate_identity()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var route = new RecordingRoute(fixture.Raw) { Hold = true };
|
||||
var executor = CreateExecutor(fixture, route);
|
||||
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
var first = executor.WriteAsync(new([new("first", "canonical-view", fixture.Raw, firstValue, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var equivalent = fixture.Raw with { Address = fixture.Raw.Address with { OriginClusterId = "CLUSTER" } };
|
||||
var second = executor.WriteAsync(new([new("second", "canonical-view", equivalent, secondValue, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
route.Release.TrySetResult();
|
||||
|
||||
(await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))
|
||||
.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
(await second.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))
|
||||
.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
route.Dispatched.ShouldBe(["canonical-view"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ordinally_distinct_authorized_views_with_unpaired_surrogates_cannot_share_an_operation()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var existing = fixture.Catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
|
||||
var first = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/\ud800" },
|
||||
Subject = "Plant/Driver/Device/\ud800" };
|
||||
var second = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/\ud801" },
|
||||
Subject = "Plant/Driver/Device/\ud801" };
|
||||
LocalDataNode MakeNode(string id, DataView view, string leaf) => existing with
|
||||
{
|
||||
EntityId = id,
|
||||
Metadata = existing.Metadata with { View = view, BrowseName = leaf },
|
||||
Scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw,
|
||||
Segments = ["Plant", "Driver", "Device", leaf] },
|
||||
};
|
||||
var nodes = fixture.Catalog.Nodes.Concat([MakeNode("surrogate-a", first, "\ud800"), MakeNode("surrogate-b", second, "\ud801")]);
|
||||
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
|
||||
var catalog = new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), nodes,
|
||||
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw,
|
||||
RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }]);
|
||||
var route = new RecordingRoute(first, second);
|
||||
var executor = CreateExecutor(fixture, route, catalog: catalog);
|
||||
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
var one = await executor.WriteAsync(new([new("one", "same-id", first, firstValue, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
var two = await executor.WriteAsync(new([new("two", "same-id", second, secondValue, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
|
||||
one.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
two.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
route.Dispatched.ShouldBe(["same-id"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Canceling_one_waiter_does_not_cancel_the_shared_dispatched_write()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var route = new RecordingRoute(fixture.Raw) { Hold = true };
|
||||
var executor = CreateExecutor(fixture, route);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
using var canceledWaiter = new CancellationTokenSource();
|
||||
var batch = new WriteBatch([new("first", "shared", fixture.Raw, value, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget);
|
||||
var first = executor.WriteAsync(batch, canceledWaiter.Token);
|
||||
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var second = executor.WriteAsync(batch, TestContext.Current.CancellationToken);
|
||||
canceledWaiter.Cancel();
|
||||
route.Release.TrySetResult();
|
||||
try { await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
||||
catch (OperationCanceledException) { }
|
||||
|
||||
(await second.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldHaveSingleItem().Outcome.State
|
||||
.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
route.Dispatched.ShouldBe(["shared"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Executor_does_not_refine_an_unknown_after_the_observation_window_ends()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var route = new ExpiredObservationRoute(fixture.Raw, fixture.Clock);
|
||||
var executor = CreateExecutor(fixture, route);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
var batch = new WriteBatch([new("first", "late-result", fixture.Raw, value, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget);
|
||||
var first = await executor.WriteAsync(batch, TestContext.Current.CancellationToken);
|
||||
var duplicate = await executor.WriteAsync(batch, TestContext.Current.CancellationToken);
|
||||
|
||||
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
duplicate.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
route.Dispatches.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("expired")]
|
||||
[InlineData("principal")]
|
||||
[InlineData("version")]
|
||||
[InlineData("budget")]
|
||||
public async Task Executor_rejects_unusable_original_credentials_and_insufficient_budget_before_any_route_call(string reason)
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var route = new RecordingRoute(fixture.Raw);
|
||||
var context = reason switch
|
||||
{
|
||||
"expired" => fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow() },
|
||||
"principal" => fixture.Context with { PrincipalId = "different-principal" },
|
||||
"version" => fixture.Context with { CredentialVersion = "replaced-key-version" },
|
||||
_ => fixture.Context,
|
||||
};
|
||||
var executor = CreateExecutor(fixture, route, context);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
var remaining = reason == "budget" ? TimeSpan.FromMilliseconds(1) : TimeSpan.FromSeconds(5);
|
||||
var result = await executor.WriteAsync(new([new("one", "operation", fixture.Raw, value, 1,
|
||||
fixture.Serving.Incarnation, remaining)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
|
||||
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
route.Dispatched.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
private static DataWriteExecutor CreateExecutor(LocalDataFixture fixture, IDataWriteRoute route,
|
||||
DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null)
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
||||
authority.Apply("cluster", "first", [key],
|
||||
[new NodeAcl { NodeAclId = "write", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder,
|
||||
ScopeId = "folder", PermissionFlags = NodePermissions.WriteOperate }],
|
||||
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
||||
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, fixture.Clock), fixture.Clock);
|
||||
var registry = new WriteOperationRegistry(fixture.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), fixture.Clock);
|
||||
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
|
||||
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var capabilities = new DataCapabilitiesProvider("cluster", () => fixture.Serving, () => true, limits);
|
||||
return new DataWriteExecutor(context ?? fixture.Context, () => catalog ?? fixture.Catalog, policy, capabilities, route,
|
||||
registry, new WriteValueBudget(16_384), fixture.Clock, new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
|
||||
}
|
||||
|
||||
private sealed class RecordingRoute(DataView view, DataView? alternate = null) : IDataWriteRoute
|
||||
{
|
||||
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _dispatched = new();
|
||||
private readonly LateWriteObserver _observer = new(16, TimeSpan.FromMinutes(1));
|
||||
public bool Hold { get; init; }
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public string[] Dispatched => _dispatched.ToArray();
|
||||
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
|
||||
{
|
||||
target = requested == view || requested == alternate
|
||||
? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null;
|
||||
return target is not null;
|
||||
}
|
||||
|
||||
public async Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
|
||||
{
|
||||
var operation = ticket.Proof.Admission.OperationId;
|
||||
_observer.TryReserve(out var reservation).ShouldBeTrue();
|
||||
var physical = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
reservation.ShouldNotBeNull().Observe(physical.Task, claim, ticket);
|
||||
_dispatched.Enqueue(operation);
|
||||
claim.TryMarkDispatched().ShouldBeTrue();
|
||||
Entered.TrySetResult();
|
||||
if (Hold) await Release.Task;
|
||||
var outcome = operation == "failed"
|
||||
? new DataWriteOutcome(DataWriteState.DriverConfirmedFailure, 0x80000000u, "device rejected")
|
||||
: new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
|
||||
physical.TrySetResult(outcome);
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ExpiredObservationRoute(DataView view, ManualTimeProvider clock) : IDataWriteRoute
|
||||
{
|
||||
public int Dispatches { get; private set; }
|
||||
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
|
||||
{
|
||||
target = requested == view ? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null;
|
||||
return target is not null;
|
||||
}
|
||||
|
||||
public Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
|
||||
{
|
||||
Dispatches++;
|
||||
claim.TryMarkDispatched().ShouldBeTrue();
|
||||
var observer = new LateWriteObserver(1, TimeSpan.FromMilliseconds(100), new StepPastRetentionClock(clock));
|
||||
observer.TryReserve(out var reservation).ShouldBeTrue();
|
||||
var confirmed = new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
|
||||
// The completed physical task lets Observe settle the expired result synchronously, before the
|
||||
// host route returns the same definitive outcome to the executor.
|
||||
reservation.ShouldNotBeNull().Observe(Task.FromResult(confirmed), claim, ticket);
|
||||
return Task.FromResult(confirmed);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class StepPastRetentionClock(ManualTimeProvider clock) : TimeProvider
|
||||
{
|
||||
private int _reads;
|
||||
public override long TimestampFrequency => clock.TimestampFrequency;
|
||||
public override DateTimeOffset GetUtcNow() => clock.GetUtcNow();
|
||||
public override long GetTimestamp()
|
||||
{
|
||||
if (Interlocked.Increment(ref _reads) == 2) clock.Advance(TimeSpan.FromSeconds(1));
|
||||
return clock.GetTimestamp();
|
||||
}
|
||||
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) =>
|
||||
clock.CreateTimer(callback, state, dueTime, period);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
|
||||
public sealed class GrpcDataWriteCompositionTests
|
||||
{
|
||||
[Fact]
|
||||
public void Runtime_registration_shares_the_publication_fence_with_authority_and_primary_state()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
// Host registers authority before adding the runtime services. Construction must still
|
||||
// receive the same fence as the role publisher and the later catalog activation.
|
||||
services.AddSingleton<DataPlaneAuthorityState>();
|
||||
services.AddSingleton<CatalogActivation>();
|
||||
services.AddOtOpcUaRuntime();
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var fence = provider.GetRequiredService<DataWriteDispatchFence>();
|
||||
ReferenceEquals(fence, provider.GetRequiredService<DataPlaneAuthorityState>().DispatchFence).ShouldBeTrue();
|
||||
ReferenceEquals(fence, provider.GetRequiredService<RedundancyRoleView>().DispatchFence).ShouldBeTrue();
|
||||
ReferenceEquals(fence, provider.GetRequiredService<CatalogActivation>().DispatchFence).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Runtime_registration_preserves_an_explicit_fence_and_is_idempotent()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
var fence = new DataWriteDispatchFence();
|
||||
services.AddSingleton(fence);
|
||||
services.AddSingleton<DataPlaneAuthorityState>();
|
||||
services.AddOtOpcUaRuntime();
|
||||
services.AddOtOpcUaRuntime();
|
||||
using var provider = services.BuildServiceProvider();
|
||||
|
||||
var registered = provider.GetServices<DataWriteDispatchFence>().ToArray();
|
||||
registered.Length.ShouldBe(1);
|
||||
ReferenceEquals(registered[0], fence).ShouldBeTrue();
|
||||
ReferenceEquals(fence, provider.GetRequiredService<DataPlaneAuthorityState>().DispatchFence).ShouldBeTrue();
|
||||
ReferenceEquals(fence, provider.GetRequiredService<RedundancyRoleView>().DispatchFence).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P05")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataWriteRegistryTests
|
||||
{
|
||||
private static readonly byte[] Hash = new byte[32];
|
||||
private static readonly DataWriteOutcome Success = new(DataWriteState.DriverConfirmedSuccess, 0, null);
|
||||
private static WriteOperationRegistry Registry(int count = 4, long bytes = 4096, ManualTimeProvider? clock = null) =>
|
||||
new("inc-1", count, bytes, TimeSpan.FromSeconds(10), clock);
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_duplicates_share_one_claim_and_waiter_cancellation_does_not_cancel_work()
|
||||
{
|
||||
var registry = Registry();
|
||||
var results = await Task.WhenAll(Enumerable.Range(0, 32).Select(_ => Task.Run(() =>
|
||||
registry.Claim("principal", "op", "inc-1", Hash))));
|
||||
results.Count(r => r.Kind == WriteClaimKind.Owner).ShouldBe(1);
|
||||
var owner = results.Single(r => r.Kind == WriteClaimKind.Owner).Claim!;
|
||||
results.ShouldAllBe(r => ReferenceEquals(r.Claim, owner));
|
||||
owner.TryMarkDispatched().ShouldBeTrue();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var detached = owner.Completion.WaitAsync(cancellation.Token);
|
||||
cancellation.Cancel();
|
||||
await Should.ThrowAsync<OperationCanceledException>(async () => await detached);
|
||||
owner.Complete(Success).ShouldBeTrue();
|
||||
(await owner.Completion).ShouldBe(Success);
|
||||
registry.Claim("principal", "op", "inc-1", Hash).Claim!.CurrentOutcome.ShouldBe(Success);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Hash_is_copied_and_conflicting_payload_or_stale_incarnation_cannot_dispatch()
|
||||
{
|
||||
var registry = Registry();
|
||||
var semantic = new byte[32];
|
||||
var owner = registry.Claim("principal", "op", "inc-1", semantic);
|
||||
semantic[0] = 1;
|
||||
registry.Claim("principal", "op", "inc-1", semantic).Kind.ShouldBe(WriteClaimKind.Conflict);
|
||||
registry.Claim("principal", "op", "old-inc", Hash).Kind.ShouldBe(WriteClaimKind.Stale);
|
||||
registry.Claim("principal", "op", "inc-1", Hash).Claim.ShouldBeSameAs(owner.Claim);
|
||||
registry.Claim("other-principal", "op", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
|
||||
Should.Throw<ArgumentException>(() => registry.Claim("principal", "bad", "inc-1", new byte[31]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Principal_identity_is_case_insensitive_but_operation_id_is_ordinal()
|
||||
{
|
||||
var registry = Registry();
|
||||
var first = registry.Claim("Service-Principal", "Operation", "inc-1", Hash);
|
||||
registry.Claim("service-principal", "Operation", "inc-1", Hash).Claim.ShouldBeSameAs(first.Claim);
|
||||
registry.Claim("service-principal", "operation", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Inflight_entries_are_never_evicted_and_completed_retention_uses_monotonic_time()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var registry = Registry(count: 1, clock: clock);
|
||||
var claim = registry.Claim("p", "one", "inc-1", Hash).Claim!;
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
registry.Claim("p", "two", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
|
||||
registry.Claim("p", "one", "inc-1", Hash).Claim.ShouldBeSameAs(claim);
|
||||
claim.Complete(new(DataWriteState.RejectedBeforeDispatch, 0, null)).ShouldBeTrue();
|
||||
clock.WallClockOffset = TimeSpan.FromDays(30);
|
||||
registry.Claim("p", "two", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
|
||||
clock.Advance(TimeSpan.FromSeconds(11));
|
||||
registry.Claim("p", "two", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retained_byte_capacity_rejects_without_evicting_existing_claim()
|
||||
{
|
||||
var registry = Registry(bytes: 1);
|
||||
registry.Claim("principal", "op", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Late_refinement_updates_snapshot_without_changing_already_completed_unknown_task()
|
||||
{
|
||||
var claim = Registry().Claim("p", "one", "inc-1", Hash).Claim!;
|
||||
claim.TryMarkDispatched().ShouldBeTrue();
|
||||
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, 0, null);
|
||||
claim.Complete(unknown).ShouldBeTrue();
|
||||
claim.LateRefine(Success).ShouldBeTrue();
|
||||
(await claim.Completion).ShouldBe(unknown);
|
||||
claim.CurrentOutcome.ShouldBe(Success);
|
||||
claim.LateRefine(new(DataWriteState.RejectedBeforeDispatch, 0, null)).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user