diff --git a/docs/plans/evidence/grpc-data/README.md b/docs/plans/evidence/grpc-data/README.md index d7ae1ec7e..2b1e02a7c 100644 --- a/docs/plans/evidence/grpc-data/README.md +++ b/docs/plans/evidence/grpc-data/README.md @@ -23,7 +23,7 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation- | 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 | Passed | 347/347 applicable tests; Astra approved frozen source and evidence | | P07 | TLS/provisioning/node+cluster clients | Passed; Astra approved | 393/393 applicable tests, zero failures/skips; final frozen run `20261116T160335.804917Z-5a4994c32d15` | -| P08 | Raw/UNS projection and adapter | Pending | | +| P08 | Raw/UNS projection and adapter | In progress | Cache/continuation, SDK adapter and shared provenance/write-generation packets; P07 committed `5ea64b4b6` | | P09 | Authoring/diagnostics/docs | Pending | | | P10 | Local Docker/CLI/probe integration | Pending | | | P11 | Scaling/recovery measurements | Pending | | @@ -216,3 +216,62 @@ After that final repair, frozen run `20261116T155343.945235Z-be0fbabc1a44` passe The accepted ordering variance moves creation of Task 15's `GrpcDataTlsWireTests` and `GrpcDataListenerIsolationWireTests` to P10 with their actual TLS fixtures; both remain required integration classes/scenarios alongside the existing mesh auth/boundary selectors. No wire-test requirement is waived. P10 still requires actual TLS/listener isolation, Docker/CLI/probes, deployed credential rotation/restart/failover, and SQL migration/concurrency/rollback evidence. P11 measurements and the P12 full-solution/final Astra gate remain pending. P07 approval permits its commit and dependent P08 work, without claiming those later results. Before commit, P08 preparation found that a Browse lease/continuation could outlive the original authenticated target credential. The commit was held. Actual RED `20261116T160304.904551Z-9a7e5ce79d56` passed 5/6 local-connection cases; the repair caps both durations by positive remaining original credential lifetime and denies expiry during completion. GetMetadata objects have no separate lease, so P08 must retain the Browse/request-start authority boundary. The superseding frozen full run `20261116T160335.804917Z-5a4994c32d15` passed **393/393**, zero failures/skips (H91/R220/C41/K20/P21). Astra independently reconciled all five TRXs, unchanged HEAD, tracked diff SHA-256 `55029f7b6c6323a87dd3d8b96a988928d1eaee5e3889e1f57c4b07e4bd5771ae`, and all 50 new source/test hashes before review-document edits, then reaffirmed P07 approval. This is the final approved P07 candidate; the later-phase obligations above remain unchanged. + + +## P08 execution notes + +P07 was committed as `5ea64b4b6` following the superseding 393/393 approval. P08 uses three Terra/high owners: federated browse/cache/continuations, SDK/import adapter, and the coordinated response-provenance/write-generation prerequisite. Root owns disjoint identifier helpers, actual actor/DI wiring, test gates and commits. Astra reviewed the [shared contract directions](p08-contract-astra-review.md) before their implementation. No P08 implementation approval is implied. + +Initial API REDs: Runtime `20261116T161350.550609Z-b289570bead9`, Commons `20261116T161401.268233Z-bec228e3d1f2`, Abstractions `20261116T161402.696381Z-217aeea97bc9`. The first Runtime compile also identified a fixture's invalid readonly modifier. After correction, `20261116T161848.889849Z-a552bdcdeca8` caught two direct test capability calls lacking the repository analyzer's invocation boundary; the lifetime-specific test now has a local documented suppression rather than changing production resilience policy. Commons and identifier-helper units passed in `161902` and `161906`. + +Actual Runtime behavioral RED `20261116T162054.919610Z-b4b4c464db98` executed 59 cases, 55 passing and four expected failures: browse Serving was absent, an old peer without generation enforcement received a write attempt, a strict generation mismatch dispatched, and server admission claimed/dispatched a stale generation. The protocol owner repaired those paths after this evidence and added further intent/dedup coverage; that extended candidate has not yet passed a Runtime gate. + +The following compilation checkpoints captured the new empty-page lease/local-authority snapshot API (`162527`), SDK selected-parent readiness callback (`162535`), and canonical projected dependency reference helper (`162540`). Only the required declarations were added for cache/SDK tests so their actual behavior can be tested before repair. Full P08 readiness, mapped publication and continuation integration remain incomplete. No P10 network/SQL/Docker/CLI or P12 full-solution gate has run. + +Subsequent behavioral REDs covered expired empty-parent metadata and pinned retired capacity (`162731`), SDK pending/unavailable parent browsing (`163623`), strict endpoint discovery and operation-ID generation ABA (`165730`), and coalesced browse waiters plus old-peer write-capability masking (`170143`). Repairs preserve independent origin metadata and local placement, positive serving-generation write preconditions and nonretryable unknown outcomes for fingerprint conflicts. The typed import adapter buffers an initial snapshot until completion and carries original age/proof to the local actor path. SDK structural materialization rejects missing parents, collisions and unsupported multidimensional values. These component changes do not establish complete deployment or subscription-delivery integration. + +Frozen candidate `20261116T173939.484558Z-8643fe4bed4a` passed **192/192** applicable P08 tests, zero failures/skips: Runtime77, SDK66, Commons19, Abstractions6, Host24. The two actual Host actor-routing tests also passed independently in `20261116T173854.399123Z-b8a29debfb68`; they verify immutable typed sample/age/proof delivery, exact canonical dependency keys and retirement ownership. This is a component checkpoint, not P08 completion or Astra implementation approval. Subsequent adversarial regressions and actual mapping activation, prepared-page application and Publish/Republish guards remain in progress. + +The expanded frozen component run `20261116T174648.173110Z-a7493b3b99cc` passed **239/239**, zero failures/skips (Runtime107, SDK66, Commons35, Abstractions6, Host25). Astra independently verified those TRXs and recorded seven cache/resolver findings in the [component review](p08-component-astra-review.md). Their test-first repair packet includes expired-capacity reclamation, pinned renewal, complete key/authority byte charges, mapping-relative depth, aggregate mapping limits, retained canceled physical jobs, and indexed publication accounting. All Task17 regressions subsequently passed in the focused `20261116T205413.529548Z-51b69f23923e` run and the broader affected Runtime runs; independent re-review remains pending. + +The deployed mapping lifecycle now uses the actual shared catalog parent/scope and closes at the next attempt. Actual DriverHost and standalone publisher artifact tests cover A-only placement, activation/removal, failed rebuild closure and a delayed notification overtaken by a new attempt. The SDK page-applier tests cover commit/rollback and current deferred sink binding. Namespace-classifier behavioral RED `20261116T210026.155857Z-1279e7ada45b` established that an opaque-looking local identifier was incorrectly treated as mapped; the repaired SDK gate includes the explicitly selected PhaseP03 mapped-subject class so this case cannot be omitted by a PhaseP08 trait filter. + +Runtime `20261116T211515.808137Z-a386b1678e2c` executed 153 cases: **152 passed**, with one intentional failing BrowseNext controller declaration (Unavailable instead of Pending). This run includes passing demand pin/admission/materialization fencing, the repaired actual dependency consumer callback, all Task17 repairs and earlier adapter/write/lifecycle regressions. Read/write/stream registry operations and live SDK BrowseNext and delivery are not yet complete. Host `20261116T211611.741758Z-853745ec24f8` passed **28/28**, zero skips, including the composed services, typed actor value routing, physical sink byte ownership, coalesced retirement control and new-host activation recovery. These are component gates, not P08 approval or a full-solution test run. + +An additional targeted SDK loopback service gate is being introduced under `wire/P08`, separate from unit results, to establish actual Publish/Republish guards before mapped monitored-item admission. It does not replace P10 Docker/CLI or the final P12 suite. + +### P08 lifetime, delivery ownership and async input checkpoints + +The actual SDK loopback delivery gate first passed eight cases, then expanded to expose stale-age, ambiguous equal-sample and aggregate candidate-pressure failures. These wire checks remain separate from unit selectors and do not replace P10 Docker/CLI validation. The current SDK unit checkpoint `20261116T225359.539290Z-9405383e3f48` passed **86/86**, including atomic materialization pin/retire, bounded node reclamation, same-placement renewal and candidate-budget tests. Actual async BrowseNext and mapped Write service coverage remain outstanding. + +Astra's publisher follow-up identified unknown-upper-age acceptance, queued physical payload ownership and same-key replacement metadata escaping control-byte accounting. Behavioral RED `20261116T222720.282316Z-9388d6644958` established those defects. The repaired Host checkpoint `20261116T225508.244742Z-9156f4fc4faf` passed **36/36** with zero skips, including paused Host/SDK/mux/subscriber queue cases. This is a component gate, not overall P08 approval. + +Async alarm evidence behavioral RED `20261116T224350.906936Z-be2190a3f70a` established that a later authorized input could revive an older evaluation and emitted events lost original evidence. Exact input capture and event evidence passed the applicable new and existing alarm gate `20261116T225200.651858Z-897fa6a2a544`. Physical retained-byte ownership through evaluator/worker timeout is being added, with guard missing-API RED `20261116T225719.244944Z-c016540ff99c`; its validation and the combined runtime/SDK integration gate are pending. No P08 completion, Docker scenario or full-solution result is claimed here. + +The subsequent scoped Astra audit found four additional blockers: HashSet slot reuse could reorder pending values; recovery/command alarm templates interpolated transient remote inputs without captured authority; Shadow copied projected snapshots outside physical accounting; and VirtualTag/Calculation async paths erased proof or physical ownership. They are being repaired before overall phase approval. Publisher ordering had actual `[3,2]` versus `[2,3]` RED at both handoffs in `20261116T231506.771099Z-3ab79dfd1368`; monotonic enqueue ordering repairs passed with all **48/48 Host** cases in `20261116T232503.133922Z-add1a24bea07`. Local derived-output acceptance is documented in [the ownership contract](p08-derived-input-authority.md). + +The alarm template/Shadow regressions first failed in `20261116T230615.393720Z-0e229df1ad7b` and passed **9/9** in `20261116T230755.693788Z-2dfbd331f185`. Broader alarm and guard checks passed in `20261116T231915.507171Z-98bf23158f9a` and `20261116T231926.535007Z-33dc90f4f50b`. The real process-freeze/worker-clock wire selector passed **14/14** in `20261116T230845.719415Z-worker-physical-wire`, including retention through transport timeout until actual worker response. + +Runtime `20261116T232328.651999Z-148d1774bbf8` passed **220/221**: consumer/VT proof and ownership, subscribe-only fresh snapshot, SDK incarnation pin and aggregate interest transitions passed; the deliberately empty configured acquisition owner remained RED. Calculation's focused gate `20261116T232057.618152Z-e65220f5c66a` passed **18/18**. SDK units passed **86/86** in `20261116T232535.449662Z-0588b22716e7`; actual async Browse/Write service validation is separate and pending. Abstractions `20261116T232555.826300Z-f558d40d19d7` passed 8/9 and established the retained-input helper enumerated 100,002 inputs before rejecting rather than stopping at its entry bound. No partial checkpoint is overall P08 approval. + +### P08 combined unit checkpoint and composed review obligations + +The complete applicable unit checkpoint passed **525/525**, zero failures/skips, across Runtime227 (`20261116T235746.192492Z-847c5916c696`), SDK86 (`235433.692433Z-b374ae6b3bd7`), Commons35 (`235457.385910Z-212d2a872d40`), Abstractions9 (`235501.156297Z-5103100582e6`), Host64 including affected startup classes (`235906.607962Z-7c6d2dfff2af`), CoreAlarms64 (`235540.600462Z-39de665789e1`), Guard18 (`235549.638106Z-077eb660d915`) and Calculation22 (`235559.716791Z-2a26d00f7fc2`). Runtime's earlier failures were compilation errors in the new headless fixture, corrected before its successful rerun. This is a component checkpoint, not overall P08 approval. + +The headless wire gate `20261117T000216.912451Z-configured-discovery-wire` passed **2/2** through real deployed placement, resolver/cache/applier, SDK node manager and configured subscription ownership, including forged locators, expiry/reacquisition and teardown. Its initial fixture is a root with immediate value children; it does not establish nested branches, mapped root leaves or an external SDK client's use of the real Browse authorization registry. Astra's combined review identified those missing composed behaviors, plus node-owned whole-page closures escaping per-node charges and quadratic repeated page guards. All five remain repair obligations before phase approval. + +The new cursor-expiry wire regression produced actual behavioral RED in `20261117T000933.301106Z-sdk-cursor-expiry-red`: a token expiring during a blocked fetch still returned success. Earlier attempts were test-compilation failures, not behavioral evidence. Typed hierarchy/root-leaf API RED is `20261117T001126.915571Z-dcb1ecaa9e59`; the minimal default-false port then established **3/3 actual REDs** in `20261117T001344.375169Z-1c7fc329749b` (Raw hierarchy, UNS hierarchy, atomic root-leaf promotion). These repairs are in progress. + +The publisher source-identity regression failed in `20261116T233727.834161Z-publisher-source-identity-red`; the current full Host checkpoint verifies the captured identity fence and old-witness retirement repair. An exploratory wiring check in `234719.874164Z-configured-wiring-red` encountered a stale prebuilt constructor and is not valid DI behavioral RED; the subsequent full-graph Host64 gate is the authoritative composition check. + +P11 must additionally measure slow-client fairness: the current per-item fresh-snapshot request restarts its shared cohort. A per-registration rebind/snapshot or separately bounded recovery cohort is required if a slow subscriber's recovery interrupts otherwise healthy registrations. This is a recorded limitation pending the planned fairness experiment, not an advertised scaling result. No Docker/CLI workload or full-solution gate has run. + +The superseding P08 applicable unit checkpoint `20261117T012625.071224Z-d57c015b4536` passed **542/542**, none skipped: Runtime239, SDK91, Commons35, Abstractions9, Host64, CoreAlarms64, Guard18, Calculation22. It includes typed Raw/UNS hierarchy, root-leaf renewal, structural array metadata and owned array read/subscribe/write conversion, independent retained read-source SDK pins, targeted source retirement, detached constant-work node/page guards, complete parent/child proof-size charges, retired configured-capability graph collection, and forced-retirement physical quota plus opposite-lock disposal regression. This is not overall P08 approval; actual composed wire behavior and mapped-MI periodic revalidation remain required. + +SDK physical quota RED `20261117T011310.449174Z-0dc51b1fb85a` passed3/failed1 because a removed pinned root leaf freed capacity early. Runtime retained-source RED `20261117T012300.896375Z-90f143221646` passed16/failed1 because a retained read source did not hold its SDK incarnation. Both are repaired in the superseding checkpoint. Astra's subsequent source review closed the detached guard, primitive capability stamp, full proof-size estimator and lock-independent retired accounting findings, while identifying mapped monitored-item periodic revalidation as a separate open liveness defect. + +The final P08 deltas add the affected local monitored-item revalidation classes: SDK **112/112** (`20261117T013314.505188Z-b855823bfb0f`), and Runtime **242/242** (`20261117T013927.511739Z-3a684df4cbce`). Together with the unchanged six project results from the 542 checkpoint, the current applicable phase evidence is **566 passed, zero failed/skipped**. Actual SDK wire Browse/delivery passed **28/28** (`20261117T013207.676008Z-sdk-projection-wire`), including the revalidation regression whose original behavioral RED is `20261117T012941.753385Z-sdk-revalidation-red`. The real composed Raw/UNS/local-ACL suite passed **6/6** in `20261117T013019.915593Z-composed-raw-uns-wire`; a final run against the latest Runtime source follows. + +Astra's final source pass found invalidation control IDs accumulating without owned sources and a mapping-lock/publication-lock cycle. The bounded-queue regression reproduced **10001 pending instead of 1** (`20261117T013439.745777Z-6bc9df4d4d69`); a further attachment-race regression reproduced stranded pins (`20261117T013827.442802Z-e086385c96cd`). The final Runtime gate validates a separate nonblocking retirement gate, membership bounded to owned source buckets, exact generation filtering, correct disposal synchronization and attach-before-final-validation cleanup. These are actual behavioral REDs and repairs; the intermediate `013618` run failed test-analyzer compilation and is not behavioral evidence. + +Final composed wire confirmation `20261117T014136.461398Z-final-p08-composed-wire` passed **6/6**, no skips, using the exact Runtime/SDK graph built by the final Runtime unit run. It verifies nested Raw pages/array metadata, UNS projection, local denied-sibling filtering, mapped root-leaf headless/read/monitor composition, deployment capability expiry/reuse and configured lifecycle acquisition. P10 six-process Docker/CLI scenarios, P11 workloads and P12 full-suite verification remain outstanding. diff --git a/docs/plans/evidence/grpc-data/p08-component-astra-review.md b/docs/plans/evidence/grpc-data/p08-component-astra-review.md new file mode 100644 index 000000000..4666bc5ac --- /dev/null +++ b/docs/plans/evidence/grpc-data/p08-component-astra-review.md @@ -0,0 +1,62 @@ +# P08 component review — open findings + +Astra (`gpt-6-astra`, xhigh) independently verified the frozen component checkpoint `20261116T174648.173110Z-a7493b3b99cc`: 239 tests passed, none failed or skipped (Runtime107, SDK66, Commons35, Abstractions6, Host25). Later SDK and deployment-lifecycle edits are outside that checkpoint. This review does not approve P08 or the final implementation. + +The shared write/provenance delta was reviewed: exact-match strict endpoint discovery, no strict retry after send, fingerprint Conflict/Stale reported as Unknown, and preservation of undispatched strict items when legacy retry metadata fails. No additional replay defect was found in that delta. + +Task17 requires these repairs before approval: + +1. **P1 — Physical work admission:** last-waiter cancellation removes a fetch from the coalescing dictionary before queued/running work and cleanup finish. Bound and retain physical work ownership independently of joinable waiters. +2. **P2 — Reclamation:** expired unpinned parents/nodes continue consuming capacity until mapping invalidation. Reclaim them without requiring deployment. +3. **P2 — Pinned renewal:** a pinned old node blocks replacement by a fresh same-placement proof after lease expiry. Permit bounded renewal without reviving the old lease or prematurely releasing old ownership charges. +4. **P2 — Mapping node limits:** enforce aggregate retained nodes across all pages and parents for each mapping, rather than only a per-page count. +5. **P2 — Projection depth:** measure remote depth from the configured mapping anchor, independently of existing local ancestry. +6. **P2 — Byte accounting:** include retained query/filter/cursor/caller and authority/ancestry metadata, or bound these fields conservatively before retention. +7. **P2 — Publication work:** replace full-cache byte recounts and scans of unrelated pages under the global lock with maintained accounting and appropriate sibling indexes. + +Each finding needs a focused regression, repair, applicable gate and Astra re-review. Actual prepared-page SDK application, deployed DI/lifecycle behavior, and final Publish/Republish authorization remain separate required integration checks. + +## Follow-up review + +Astra source-verified the physical-job, renewal-version, aggregate mapping, relative-depth, byte-accounting and indexed-publication repairs against the frozen `212038` source hashes. The run had one unrelated intentional Read-registry failure. Reclamation remains partially open, and the controller review found these three P2 items: + +1. `ProjectedBrowseAccess` returns cache `Unavailable` without scheduling renewal after a normal lease expiry. A controller-level ready → expiry → new physical fetch → ready regression is required; invalid cursors and denied callers must remain denied. +2. Cache reclamation runs only under global capacity pressure. A mapping at its own node limit must also reclaim expired unpinned nodes while global capacity remains available. +3. Controller authority guards call the external `Active` enumeration, which JSON-copies all mappings on each check. Add an indexed exact-placement/current-authority API; retain defensive copying at the external enumeration boundary. + +These findings are assigned for test-first repair. No P08 approval has been given. SDK source renewal, automatic monitored-item recovery, original queued-sample guards and actual BrowseNext delivery remain in progress outside this scoped review. + +## Final P08 phase reconciliation — 2026-11-17 + +This section supersedes the open dispositions above while preserving their checkpoint history. Astra (`gpt-6-astra`, xhigh) completed the independent P08 source and evidence review. **P08 is approved:** no material findings remain open in the reviewed P08 scope, and the final composed Raw/UNS wire rerun passed against the final Runtime graph. This is a phase approval, not the P12 final implementation approval. + +The original seven Task17 findings and the controller follow-ups are closed: physical fetch ownership survives waiter cancellation; expired unpinned entries are reclaimed under both global and mapping pressure; renewal retains old pinned charges; aggregate node/depth/query-byte limits are enforced; and indexed accounting avoids unrelated-page scans. Controller renewal, exact invalid-continuation propagation, indexed placement checks, prepared cursor ownership and strict write provenance have been reviewed through their repairs. + +The subsequent P08 integration findings are also closed in source: + +- The actual registry authorizes Browse, and the SDK materializes typed branches, supported one-dimensional arrays and explicitly mapped root leaves. Root-leaf promotion and renewal preserve exact placement and lifetime ownership. +- Per-item materialization guards and parent-page version guards no longer retain sibling pages or repeatedly scan their contents. The shared `ProjectedProofSize` estimator includes both metadata views, stable IDs, serving fields and authority paths. Configured capabilities retain primitive mapping fields and an independent activation stamp, rather than old placement arrays. +- SDK retirement keeps bytes and node counts charged until physical pins drain. Drain callbacks use independent atomic accounting and acquire no SDK lock. Tombstoned monitored items clear their demand, definition and source-evidence references. Source states own exact SDK and cache pins, clear them on invalidation, and use an indexed mapping retirement path. +- Source invalidation callbacks do not acquire the Runtime admission lock while mapping activation owns its lock. Pending retirement work is restricted to owned source buckets; empty-bucket removal clears pending work. Source attachment publishes its bucket before a final validity check, so concurrent invalidation cannot strand pins. +- Periodic SDK revalidation uses current demand/definition authority independently of receiving an initial sample. Restoration resolves the actual projected SDK node. Final Publish/Republish checks retain original sample-age evidence and revoke stale authority without refreshing timestamps. +- Projected downstream consumers preserve the captured input proof through local derived-output acceptance. Physical script/calculation work retains its budget after logical timeout; alarm control/recovery paths do not adopt transient projected inputs, and unsupported projected Shadow execution is suppressed. These changes preserve the existing durable alarm command semantics and local-only behavior. + +### Independently reconciled evidence + +The reviewer read the run manifests and TRX counters; no builds or tests were executed by the reviewer. + +| Evidence | Verified result | Scope | +| --- | --- | --- | +| `20261117T012625.071224Z-d57c015b4536` | 542/542, zero failed or skipped | Complete applicable P08 checkpoint: Runtime239, SDK91, Commons35, Abstractions9, Host64, ScriptedAlarms64, Scripting18, Calculation22. | +| `20261117T013314.505188Z-b855823bfb0f` | 112/112, zero failed or skipped | Final affected SDK unit row, including local Stage6 and stale monitored-node regressions; supersedes SDK91. | +| `20261117T013927.511739Z-3a684df4cbce` | 242/242, zero failed or skipped | Final applicable Runtime row, including all 20 projected-access cases; supersedes Runtime239. | +| `20261117T013207.676008Z-sdk-projection-wire` | 28/28, zero failed or skipped | Actual SDK browse, delivery and monitored-item revalidation wire tests. | +| `20261117T014136.461398Z-final-p08-composed-wire` | 6/6, zero failed or skipped | Actual SDK/Runtime/fixture-peer Raw and UNS composition on the final Runtime graph: configured acquisition/retirement, nested browse/array metadata, mapped root-leaf read/monitoring, caller filtering and capability reuse. Supersedes the earlier green composed run `20261117T013019.915593Z-composed-raw-uns-wire`. | + +The reconciled unit selection is **566 passed**, using the final Runtime242 and SDK112 rows plus the six unchanged rows from the complete checkpoint. This is a reconciliation of applicable rows, not a claim that one command executed all 566 cases. + +Behavioral failure evidence was also checked: SDK revalidation failed in `20261117T012941.753385Z-sdk-revalidation-red`; the source-attachment race failed in `20261117T013827.442802Z-e086385c96cd` (19 passed, one failed), then passed in the final Runtime row. The separate retirement-gate and bounded-queue packet passed 19/19 in `20261117T013717.014141Z-8c67752417ea`. + +The complete checkpoint identifies HEAD `5ea64b4b6ced9b1927307bd90c2fdddef8fac087` with dirty-diff SHA-256 `90e8c58c6229e60eb2f6ef9ede2648a6003e2acabe4248e1b9134c584fb052cc`; its recorded untracked hashes matched the reviewed cache, applier, controller, proof estimator, capability and lifetime files. The final Runtime manifest identifies the same HEAD with dirty-diff SHA-256 `2f1da0c12d60dc71bab50f0190c91f1f89191fe7fa05e0d2d538e8bc382fd4d0`. Later independent P09/P10 work is outside this P08 review and is not covered by these results. + +P10 actual TLS/HTTP ingress, Docker/SQL and CLI integration obligations remain required. P11 performance/fairness work, including cohort-refresh fairness, and P12 full-solution verification and final Astra review remain required. The SDK wire results above do not substitute for those gates. diff --git a/docs/plans/evidence/grpc-data/p08-contract-astra-review.md b/docs/plans/evidence/grpc-data/p08-contract-astra-review.md new file mode 100644 index 000000000..7af85c47c --- /dev/null +++ b/docs/plans/evidence/grpc-data/p08-contract-astra-review.md @@ -0,0 +1,13 @@ +# P08 shared contract checkpoint + +This records Astra's read-only P08 contract review after P07 commit `5ea64b4b6`. It approves the directions below, not the incomplete implementation or SDK integration. + +- Preserve exact ServingIdentity from the same verified Browse/Metadata response or immutable local catalog snapshot. Child metadata catalog revisions and branch lease epochs must agree with that identity. Never fetch capabilities later to fill missing provenance. +- Expose immutable stream-establishment Serving through an optional IDataSubscriptionProvenance interface. Forward it unchanged through the deployed lease wrapper; missing provenance remains unavailable. +- GetMetadata has no independent authority TTL. Cache it only under an active, exact-Serving Browse lease anchored before the original request and intersected with local/mapping/key authority. Browse leases and continuations already cap original target credential expiry in P07. +- Add optional ExpectedServingGeneration on WriteItem and protobuf tag 8, with an explicitly negotiated enforcement capability/minor. Reject supplied nonpositive/mismatching generations after authorization and before claiming or dispatching. Include presence and value in both mutation fingerprints. +- A caller-supplied generation is strict intent: preserve its complete view, catalog and incarnation through selection/retries. Refresh requires an intentional new attempt. Originally absent expectations retain explicitly unbound legacy behavior; only independently proven RejectedBeforeDispatch permits its existing per-item failover, with no success/Unknown/missing-response replay. +- Use distinct fixed mapped Raw/UNS namespace URIs. Unknown or retired IDs in those namespaces always deny, ahead of legacy ACL bypasses; no unbounded tombstone registry. Canonical dependency keys must additionally distinguish ordinary Raw paths, mapped Raw and mapped UNS. +- Default sharing to the same view within its configured connection/security scope. Full ServingGeneration belongs in keys and proofs. StableSourceId alone proves neither driver/virtual source-kind equivalence nor cross-view/export/principal equivalence. + +SDK/import owners additionally identified implementation obligations: preserve original remote metadata separately from local mapped placement, perform remote page fetch outside SDK Lock, commit continuations only after successful guarded materialization, preserve original ingress-age bounds through imported publication, and gate queued Publish plus Republish in every redundancy mode before enabling mapped monitored-item creation. Actual SDK, array-shape, collision, lifetime, expiry and recovery evidence is still required. diff --git a/docs/plans/evidence/grpc-data/p08-derived-input-authority.md b/docs/plans/evidence/grpc-data/p08-derived-input-authority.md new file mode 100644 index 000000000..a02c10dce --- /dev/null +++ b/docs/plans/evidence/grpc-data/p08-derived-input-authority.md @@ -0,0 +1,5 @@ +# Projected input to derived local output + +A virtual-tag or calculation run captures the imported sample's own authority and source identity. Before accepting a result into the local derived-output publish seam, the owner must recheck that captured sample and source. Revocation during a run, or replacement of its source, prevents the old run from being accepted as Good. After acceptance the result is a local computed sample; existing local publication and history semantics apply to that accepted sample. + +Projected input payloads retained in caches, pending evaluations, and physical script execution are independently charged to a process-wide budget. Projected pending calculation work coalesces by calculation tag. A timeout or cancellation does not release an executing script's charge: the physical runner releases it only when the underlying execution actually ends. A consumer, evaluator, or external runner without the ownership contract fails closed for projected inputs. diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 4aea49d0c..f0d227584 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -463,20 +463,42 @@ "P08": [ { "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj", - "filter": "(Feature=GrpcData&Phase=P08)", + "filter": "(Feature=GrpcData&Phase=P08)|FullyQualifiedName~.GrpcDataLocalConnectionTests.|FullyQualifiedName~.GrpcDataWriteAdmissionTests.|FullyQualifiedName~.GrpcDataConnectionClientTests.|FullyQualifiedName~.DependencyMuxActorTests.|FullyQualifiedName~.VirtualTagActorTests.|FullyQualifiedName~.DependencyConsumerMuxAdapterTests.|FullyQualifiedName~.GrpcDataCatalogStagingTests.|FullyQualifiedName~.ContinuousHistorizationRecorderAppendPipelineTests.|FullyQualifiedName~.ScriptedAlarmHostActorTests.|FullyQualifiedName~.DependencyMuxTagUpstreamSourceTests.", "new_classes": [ "GrpcDataFederatedBrowseTests", "GrpcDataContinuationTests", - "GrpcDataAdapterLifecycleTests" + "GrpcDataAdapterLifecycleTests", + "GrpcDataProjectionApplierTests", + "GrpcDataProjectedRouteTests", + "GrpcDataProjectedAccessTests", + "GrpcDataConfiguredInterestTests", + "GrpcDataConfiguredAcquisitionTests" ], - "existing_classes": [] + "existing_classes": [ + "GrpcDataLocalConnectionTests", + "GrpcDataWriteAdmissionTests", + "GrpcDataConnectionClientTests", + "DependencyMuxActorTests", + "VirtualTagActorTests", + "DependencyConsumerMuxAdapterTests", + "GrpcDataCatalogStagingTests", + "ContinuousHistorizationRecorderAppendPipelineTests", + "ScriptedAlarmHostActorTests", + "DependencyMuxTagUpstreamSourceTests" + ] }, { "project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj", - "filter": "(Feature=GrpcData&Phase=P08)|FullyQualifiedName~.NodeManagerAclEnforcementTests.|FullyQualifiedName~.NodeManagerModelChangeFilterTests.|FullyQualifiedName~.NodeManagerModelChangeOnAddTests.|FullyQualifiedName~.NodeManagerSurgicalRemoveTests.|FullyQualifiedName~.AddressSpaceApplierRawUnsTests.|FullyQualifiedName~.AddressSpaceApplierHierarchyTests.|FullyQualifiedName~.UnsReferenceBackingParityTests.", + "filter": "(Feature=GrpcData&Phase=P08)|FullyQualifiedName~.NodeManagerAclEnforcementTests.|FullyQualifiedName~.NodeManagerModelChangeFilterTests.|FullyQualifiedName~.NodeManagerModelChangeOnAddTests.|FullyQualifiedName~.NodeManagerSurgicalRemoveTests.|FullyQualifiedName~.AddressSpaceApplierRawUnsTests.|FullyQualifiedName~.AddressSpaceApplierHierarchyTests.|FullyQualifiedName~.UnsReferenceBackingParityTests.|FullyQualifiedName~.GrpcDataMappedSubjectTests.|FullyQualifiedName~.NodeManagerStage6EnforcementTests.|FullyQualifiedName~.NodeManagerStaleMonitoredNodeTests.", "new_classes": [ "GrpcDataSdkBrowseReadinessTests", - "GrpcDataSdkMappedAccessTests" + "GrpcDataSdkMappedAccessTests", + "GrpcDataSdkProjectionTests", + "GrpcDataSdkContinuationTests", + "GrpcDataCandidateBudgetTests", + "GrpcDataProjectedNodeLifetimeTests", + "GrpcDataSdkProjectionLifetimeTests", + "GrpcDataSdkHierarchyTests" ], "existing_classes": [ "NodeManagerAclEnforcementTests", @@ -485,7 +507,81 @@ "NodeManagerSurgicalRemoveTests", "AddressSpaceApplierRawUnsTests", "AddressSpaceApplierHierarchyTests", - "UnsReferenceBackingParityTests" + "UnsReferenceBackingParityTests", + "GrpcDataMappedSubjectTests", + "NodeManagerStage6EnforcementTests", + "NodeManagerStaleMonitoredNodeTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/ZB.MOM.WW.OtOpcUa.Commons.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P08)|FullyQualifiedName~.GrpcDataCodecTests.|FullyQualifiedName~.GrpcDataResponseServingTests.|FullyQualifiedName~.DeferredAddressSpaceSinkTests.", + "new_classes": [], + "existing_classes": [ + "GrpcDataCodecTests", + "GrpcDataResponseServingTests", + "DeferredAddressSpaceSinkTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P08)", + "new_classes": [ + "GrpcDataProjectedIdentityTests", + "ProjectedInputBudgetTests" + ], + "existing_classes": [] + }, + { + "project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj", + "filter": "FullyQualifiedName~.GrpcDataServiceDispatchTests.|FullyQualifiedName~.GrpcDataPublicationHandoffTests.|FullyQualifiedName~.GrpcDataRuntimeRegistrationTests.|FullyQualifiedName~.GrpcDataIngressAuthTests.|FullyQualifiedName~.GrpcDataListenerTests.|FullyQualifiedName~.GrpcDataProjectionRoutingTests.|FullyQualifiedName~.RoslynVirtualTagEvaluatorScriptRunnerTests.|FullyQualifiedName~.RoslynVirtualTagEvaluatorAsyncTests.|FullyQualifiedName~.OtOpcUaServerHostedServiceStartFailureTests.|FullyQualifiedName~.OtOpcUaServerHostedServiceRevalidationTests.|FullyQualifiedName~.OtOpcUaServerHostedServiceBindingFailureTests.|FullyQualifiedName~.OtOpcUaServerHostedServiceHistoryUpdateTests.", + "new_classes": [ + "GrpcDataProjectionRoutingTests" + ], + "existing_classes": [ + "GrpcDataServiceDispatchTests", + "GrpcDataPublicationHandoffTests", + "GrpcDataRuntimeRegistrationTests", + "GrpcDataIngressAuthTests", + "GrpcDataListenerTests", + "RoslynVirtualTagEvaluatorScriptRunnerTests", + "RoslynVirtualTagEvaluatorAsyncTests", + "OtOpcUaServerHostedServiceStartFailureTests", + "OtOpcUaServerHostedServiceRevalidationTests", + "OtOpcUaServerHostedServiceBindingFailureTests", + "OtOpcUaServerHostedServiceHistoryUpdateTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P08)|FullyQualifiedName~.ScriptedAlarmEngineTests.|FullyQualifiedName~.ScriptedAlarmEngineScriptRunnerTests.", + "new_classes": [ + "GrpcDataAlarmEvidenceTests" + ], + "existing_classes": [ + "ScriptedAlarmEngineTests", + "ScriptedAlarmEngineScriptRunnerTests" + ] + }, + { + "project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests.csproj", + "filter": "FullyQualifiedName~.ScriptRunGuardTests.", + "new_classes": [], + "existing_classes": [ + "ScriptRunGuardTests" + ] + }, + { + "project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests.csproj", + "filter": "(Feature=GrpcData&Phase=P08)|FullyQualifiedName~.CalculationDriverBatchPumpTests.|FullyQualifiedName~.CalculationDriverInputQualityTests.|FullyQualifiedName~.CalculationEvaluatorRunGuardTests.|FullyQualifiedName~.CalculationDriverScriptRunnerTests.", + "new_classes": [ + "GrpcDataCalculationOwnershipTests" + ], + "existing_classes": [ + "CalculationDriverBatchPumpTests", + "CalculationDriverInputQualityTests", + "CalculationEvaluatorRunGuardTests", + "CalculationDriverScriptRunnerTests" ] } ], diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index ed9326895..192ad1a9a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -729,8 +729,11 @@ public static class DataProtoMapper ExpectedCatalogRevision = i.ExpectedCatalogRevision, ExpectedServingIncarnation = i.ExpectedServingIncarnation, RemainingBudgetTicks = i.RemainingBudget.Ticks, + ExpectedServingGeneration = i.ExpectedServingGeneration ?? 0, } ); + for (var index = 0; index < x.Items.Count; index++) + if (x.Items[index].ExpectedServingGeneration is null) v.Items[index].ClearExpectedServingGeneration(); return v; } @@ -751,7 +754,8 @@ public static class DataProtoMapper { ArgumentException.ThrowIfNullOrWhiteSpace(item.OperationId); ArgumentException.ThrowIfNullOrWhiteSpace(item.ExpectedServingIncarnation); - if (item.ExpectedCatalogRevision <= 0 || item.RemainingBudgetTicks <= 0) + if (item.ExpectedCatalogRevision <= 0 || item.RemainingBudgetTicks <= 0 || + item.HasExpectedServingGeneration && item.ExpectedServingGeneration <= 0) throw new ArgumentException("Invalid write preconditions."); } var items = new List(); @@ -766,7 +770,8 @@ public static class DataProtoMapper TypedValueCodec.Decode(i.Value, maxElements, maxBytes), i.ExpectedCatalogRevision, i.ExpectedServingIncarnation, - TimeSpan.FromTicks(i.RemainingBudgetTicks) + TimeSpan.FromTicks(i.RemainingBudgetTicks), + i.HasExpectedServingGeneration ? i.ExpectedServingGeneration : null ) ); return new(items, DecodeBudget(x.Budget)); @@ -962,6 +967,7 @@ public static class DataProtoMapper ExpectedCatalogRevision = item.ExpectedCatalogRevision, ExpectedServingIncarnation = item.ExpectedServingIncarnation, }; + if (item.ExpectedServingGeneration is { } generation) wire.ExpectedServingGeneration = generation; return System.Security.Cryptography.SHA256.HashData(wire.ToByteArray()); } @@ -988,6 +994,7 @@ public static class DataProtoMapper CompactCodecVersion = x.CompactCodecVersion, SubscriptionAgeReadiness = x.SubscriptionAgeReadiness, ResponseServingIdentity = x.ResponseServingIdentity, + WriteServingGenerationEnforced = x.WriteServingGenerationEnforced, Limits = new W.Limits { MaxPageItems = l.MaxPageItems, @@ -1053,7 +1060,8 @@ public static class DataProtoMapper x.CompactCodecVersion, x.ClusterId, x.SubscriptionAgeReadiness, - x.ResponseServingIdentity + x.ResponseServingIdentity, + x.WriteServingGenerationEnforced ); result.Validate(); return result; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Engines/IVirtualTagEvaluator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Engines/IVirtualTagEvaluator.cs index 228fb54e6..adaf5c851 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Engines/IVirtualTagEvaluator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Engines/IVirtualTagEvaluator.cs @@ -149,3 +149,16 @@ public sealed class NullVirtualTagEvaluator : IVirtualTagEvaluator public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary dependencies) => VirtualTagEvalResult.NoChange; } + +/// An evaluator that owns projected input memory through physical script completion. +public interface IProjectedVirtualTagEvaluator : IVirtualTagEvaluator +{ + /// Evaluates an imported snapshot, taking ownership of its physical lease on entry. + /// The virtual-tag identity. + /// The expression to run. + /// The captured inputs. + /// Ownership of the imported input memory. + /// The evaluation result. + Task EvaluateProjectedAsync(string virtualTagId, string expression, + IReadOnlyDictionary dependencies, IDisposable physicalLease); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs index 21be4c4ac..c27b54f8d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/DeferredAddressSpaceSink.cs @@ -1,3 +1,5 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa; /// @@ -12,7 +14,7 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa; /// no-op against , so the actor stays safe to /// receive messages from the moment it boots. /// -public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink +public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink { private volatile IOpcUaAddressSpaceSink _inner = NullOpcUaAddressSpaceSink.Instance; @@ -22,6 +24,13 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical public void SetSink(IOpcUaAddressSpaceSink? sink) => _inner = sink ?? NullOpcUaAddressSpaceSink.Instance; + /// Resolves an optional capability against the currently bound SDK sink. + public T? GetCapability() where T : class => _inner as T; + + /// + public bool TryPublish(IReadOnlyList values) => + _inner is IProjectedValueSink projected && projected.TryPublish(values); + /// public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) => _inner.WriteValue(nodeId, value, statusCode, sourceTimestampUtc, realm); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto index 2a8180c31..3d1629a2c 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Protos/data_connection.proto @@ -113,6 +113,7 @@ message CapabilitiesResponse { string cluster_id = 10; bool subscription_age_readiness = 11; bool response_serving_identity = 12; + bool write_serving_generation_enforced = 13; } message Metadata { View view = 1; @@ -186,6 +187,7 @@ message WriteItem { int64 expected_catalog_revision = 5; string expected_serving_incarnation = 6; int64 remaining_budget_ticks = 7; + optional int64 expected_serving_generation = 8; } message WriteRequest { repeated WriteItem items = 1; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index 068c8dc50..e3b06f61f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -246,7 +246,8 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess } public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness, DataOperations Operations, IReadOnlySet ValueKinds, DataLimits Limits, bool CompactBatches, - int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false) + int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false, + bool WriteServingGenerationEnforced = false) { public void Validate() { @@ -276,7 +277,7 @@ public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, Serv } public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank, IReadOnlyList Dimensions, bool Writable, DataOperations AllowedOperations, long CatalogRevision, - string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null) + string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null) { public void Validate() { @@ -311,4 +312,4 @@ public sealed record DataMetadata(DataView View, string BrowseName, string NodeK } public sealed record DataItemResult(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic); public sealed record DataBrowseBranch(DataView Parent, DataItemStatus Status, IReadOnlyList Items, - bool Complete, string? Continuation, MetadataLease? Lease); + bool Complete, string? Continuation, MetadataLease? Lease, ServingIdentity? Serving = null); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index 0e28e9d7c..b6e71faa3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -22,7 +22,7 @@ public sealed record ReadResult(string CorrelationId, DataItemStatus Status, Dat } } public sealed record WriteItem(string CorrelationId, string OperationId, DataView View, DataValue Value, - long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget); + long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget, long? ExpectedServingGeneration = null); /// /// Admission binds the stable principal and original credential separately. Before dispatch, /// recheck the original key's current principal and credential version against authority and its @@ -131,6 +131,12 @@ public interface IDataSubscription : IAsyncDisposable Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken); IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken); } +/// Immutable serving identity captured when the subscription was established. +public interface IDataSubscriptionProvenance +{ + ServingIdentity Serving { get; } +} + /// One lifetime-scoped delivery mode, separate from direct enumeration. public interface IDataSubscriptionTransport : IDataSubscription { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedDataIds.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedDataIds.cs new file mode 100644 index 000000000..3110e4657 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedDataIds.cs @@ -0,0 +1,78 @@ +using System.Text.Json; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +/// Disjoint local identifiers for mapped nodes. Decoding never establishes authorization. +public static class ProjectedDataIds +{ + public const string RawNamespaceUri = "https://zb.com/otopcua/mapped/raw"; + public const string UnsNamespaceUri = "https://zb.com/otopcua/mapped/uns"; + private const string Prefix = "p1."; + private const int MaximumIdentifierLength = 16_384; + private sealed record Identity(string MappingId, DataAddress Origin); + + public static string NamespaceUri(DataRealm realm) => realm switch + { + DataRealm.Raw => RawNamespaceUri, + DataRealm.Uns => UnsNamespaceUri, + _ => throw new ArgumentOutOfRangeException(nameof(realm)) + }; + + public static bool IsMappedNamespace(string namespaceUri) => + namespaceUri is RawNamespaceUri or UnsNamespaceUri; + + /// A portable dependency key, distinct from ordinary unqualified local paths. + public static string DependencyReference(DataRealm realm, string localIdentifier) + { + if (!TryDecodeIdentifier(localIdentifier, out _, out _)) throw new ArgumentException("Invalid projected identifier.", nameof(localIdentifier)); + return "nsu=" + NamespaceUri(realm) + ";s=" + localIdentifier; + } + + public static bool TryParseDependencyReference(string reference, out DataRealm realm, out string localIdentifier) + { + realm = DataRealm.Unspecified; localIdentifier = string.Empty; + if (reference is null) return false; + foreach (var candidate in new[] { DataRealm.Raw, DataRealm.Uns }) + { + var prefix = "nsu=" + NamespaceUri(candidate) + ";s="; + if (!reference.StartsWith(prefix, StringComparison.Ordinal)) continue; + var identifier = reference[prefix.Length..]; + if (!TryDecodeIdentifier(identifier, out _, out _)) return false; + realm = candidate; localIdentifier = identifier; return true; + } + return false; + } + + public static string Identifier(string mappingId, DataAddress origin) + { + ArgumentException.ThrowIfNullOrWhiteSpace(mappingId); + if (mappingId.Length > 256) throw new ArgumentOutOfRangeException(nameof(mappingId)); + ArgumentNullException.ThrowIfNull(origin); + origin.Validate(); + var payload = JsonSerializer.SerializeToUtf8Bytes(new Identity(mappingId, origin)); + if (payload.Length > (MaximumIdentifierLength - Prefix.Length) * 3 / 4) + throw new ArgumentOutOfRangeException(nameof(origin)); + return Prefix + Convert.ToBase64String(payload).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + public static bool TryDecodeIdentifier(string identifier, out string mappingId, out DataAddress? origin) + { + mappingId = string.Empty; origin = null; + if (identifier is null || identifier.Length > MaximumIdentifierLength || !identifier.StartsWith(Prefix, StringComparison.Ordinal)) + return false; + var encoded = identifier[Prefix.Length..]; + if (encoded.Length == 0 || encoded.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '-' and not '_')) return false; + try + { + var padded = encoded.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight((padded.Length + 3) / 4 * 4, '='); + var parsed = JsonSerializer.Deserialize(Convert.FromBase64String(padded)); + if (parsed?.Origin is null || !string.Equals(Identifier(parsed.MappingId, parsed.Origin), identifier, StringComparison.Ordinal)) + return false; + mappingId = parsed.MappingId; origin = parsed.Origin; + return true; + } + catch (Exception error) when (error is JsonException or FormatException or ArgumentException) + { return false; } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedInputBudget.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedInputBudget.cs new file mode 100644 index 000000000..73079b2a4 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedInputBudget.cs @@ -0,0 +1,74 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +/// Process-wide retained input budget shared across script owners and redeploys. +public static class ProjectedInputBudget +{ + /// Current process-wide retained input limit in bytes. + public const long MaximumBytes = 16 * 1024 * 1024; + private const int MaximumSnapshots = 10_000; + private static long s_used; + + /// Bytes currently reserved by projected input owners. + public static long RetainedBytes => Interlocked.Read(ref s_used); + + /// Charges captured projected snapshots until the returned lease is disposed. + public static bool TryRetain(IEnumerable snapshots, out IDisposable? lease) + { + lease = null; + var values = new List(); + long charge = 0; + try + { + foreach (var snapshot in snapshots) + { + if (values.Count == MaximumSnapshots || snapshot is null) return false; + charge = checked(charge + Estimate(snapshot.Value)); + if (charge > MaximumBytes) return false; + values.Add(snapshot); + } + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + if (charge == 0) return true; + while (true) + { + var used = Interlocked.Read(ref s_used); + if (charge > MaximumBytes - used) return false; + if (Interlocked.CompareExchange(ref s_used, used + charge, used) == used) break; + } + lease = new Lease(values.ToArray(), charge); + return true; + } + + private static long Estimate(object? value) + { + checked + { + long size = 512; + if (value is string text) size += 2L * text.Length; + else if (value is byte[] bytes) size += bytes.LongLength; + else if (value is Array array) + { + if (array.Rank > 4 || array.LongLength > 65536) throw new ArgumentException("Unsupported input array."); + var elementType = array.GetType().GetElementType(); + if (elementType is null || !(elementType.IsPrimitive || elementType == typeof(string) || + elementType == typeof(Guid) || elementType == typeof(DateTime) || elementType == typeof(DateTimeOffset))) + throw new ArgumentException("Unsupported input array."); + size += 128 + 48L * array.LongLength; + if (elementType == typeof(string)) foreach (var element in array) size += 2L * ((string?)element ?? "").Length; + } + else if (value is not null && !(value.GetType().IsPrimitive || value is Guid or DateTime or DateTimeOffset or decimal)) + throw new ArgumentException("Unsupported input value."); + if (size > 4 * 1024 * 1024) throw new ArgumentException("Input is too large."); + return size; + } + } + + private sealed class Lease(DataValueSnapshot[] snapshots, long charge) : IDisposable + { + private DataValueSnapshot[]? _snapshots = snapshots; + public void Dispose() + { + if (Interlocked.Exchange(ref _snapshots, null) is not null) Interlocked.Add(ref s_used, -charge); + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs new file mode 100644 index 000000000..40ec96f50 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/ProjectedValuePublication.cs @@ -0,0 +1,26 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +/// Captured sample/route authority, independent of each local monitored item's caller. +public interface IProjectedSamplePublicationProof +{ + /// Checks the original live source, route, role and lease without network work. + bool IsValid { get; } + /// Stable source ownership; distinct sample witnesses may share this identity. + object SourceIdentity => this; + /// Source and route lifetime, independent of one sample's age. + bool IsSourceValid => IsValid; + TimeProvider Clock { get; } + /// Synchronously invalidates value readiness after failed or lost ingress; metadata may remain browsable. + void Invalidate(); +} + +/// An imported sample retaining original ingress age through local actor and SDK queues. +public sealed record ProjectedValueWrite(DataRealm Realm, string LocalIdentifier, long ProjectionGeneration, + ServingIdentity Serving, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds, long ReceivedTimestamp, + IProjectedSamplePublicationProof Proof, bool IsCompleteSnapshot = false); + +/// Applies imported values only after checking their captured proof at the actual SDK boundary. +public interface IProjectedValueSink +{ + bool TryPublish(IReadOnlyList values); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IDependencyConsumer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IDependencyConsumer.cs index bbe5adbab..dbae6ffc2 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IDependencyConsumer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IDependencyConsumer.cs @@ -42,3 +42,16 @@ public interface IDependencyConsumer /// The source timestamp of the change. void OnDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc); } + +/// A dependency consumer that retains and checks the authority of imported samples. +public interface IProjectedDependencyConsumer +{ + /// Receives an imported dependency together with its exact sample authority. + /// The dependency reference. + /// The imported value. + /// The imported status code. + /// The source timestamp. + /// The captured sample and source authority. + void OnProjectedDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc, + DataConnections.IProjectedSamplePublicationProof proof); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/IAlarmInputEvidence.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/IAlarmInputEvidence.cs new file mode 100644 index 000000000..7fb68f36c --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/IAlarmInputEvidence.cs @@ -0,0 +1,21 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; + +/// Original input authority captured independently of later input replacement. +public interface IAlarmInputEvidence +{ + bool IsValid { get; } +} + +/// Provides evidence for the exact immutable snapshot read by an evaluation. +public interface IAlarmInputEvidenceSource +{ + IAlarmInputEvidence? CaptureEvidence(DataValueSnapshot exactSnapshot); +} + +/// Reserves the retained input bytes through physical script completion. +public interface IAlarmInputPhysicalEvidence : IAlarmInputEvidence +{ + bool TryRetainPhysical(DataValueSnapshot exactSnapshot, out IDisposable? lease); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs index b7e79c8b9..06b4ed634 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -547,12 +547,15 @@ public sealed class ScriptedAlarmEngine : IDisposable var projections = new List(_alarms.Count); foreach (var (alarmId, state) in _alarms) { + var inputs = new Dictionary(StringComparer.Ordinal); + RefillReadCache(inputs, state.Inputs); + var captured = CaptureInputs(state, inputs); projections.Add(new ScriptedAlarmProjection( AlarmId: alarmId, Severity: state.Definition.Severity, - Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, TryLookup), + Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, LookupControlValue), Condition: state.Condition, - WorstInputStatusCode: LastWorstStatus(alarmId))); + WorstInputStatusCode: captured.Evidence is { IsValid: false } ? 0x80310000u : LastWorstStatus(alarmId))); } return projections; @@ -890,6 +893,9 @@ public sealed class ScriptedAlarmEngine : IDisposable state.Definition.AlarmId, _ => new AlarmScratch(state.Inputs, state.Logger, _clock)); RefillReadCache(scratch.ReadCache, state.Inputs); + var captured = CaptureInputs(state, scratch.ReadCache); + scratch.HasProjectedInputs = captured.Evidence is not null; + if (captured.Evidence is { IsValid: false }) return seed; // Worst OPC UA quality across the alarm's inputs, computed BEFORE the readiness // short-circuit so an outright-Bad input is still observed. A bucket change with no state @@ -908,18 +914,20 @@ public sealed class ScriptedAlarmEngine : IDisposable // bucket — annotate it out of band so a comms-lost / Bad-input scripted condition reports // Bad, mirroring the native OT path. if (TrackQualityBucket(state.Definition.AlarmId, worstStatus)) - pendingEmissions.Add(BuildQualityEmission(state, seed, worstStatus)); + pendingEmissions.Add(BuildQualityEmission(state, seed, worstStatus, captured)); return seed; } - var context = scratch.Context; + var context = captured.Evidence is null ? scratch.Context + : new AlarmPredicateContext(captured.Values, state.Logger, _clock); + if (!TryRetainInputs(captured, out var physicalLease)) return seed; bool predicateTrue; try { predicateTrue = await _guard.RunAsync( state.Definition.AlarmId, state.Definition.PredicateScriptSource, state.Evaluator!, context, - _scriptTimeout, ct) + _scriptTimeout, ct, physicalLease) .ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) @@ -950,6 +958,7 @@ public sealed class ScriptedAlarmEngine : IDisposable state.Logger.Error(ex, "Alarm predicate threw — state unchanged"); return seed; } + if (captured.Evidence is { IsValid: false }) return seed; MirrorPredicate(state, scratch, ScriptRunOutcome.Ok(predicateTrue)); scratch.LastNonCompletion = null; @@ -961,7 +970,7 @@ public sealed class ScriptedAlarmEngine : IDisposable var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc); var transition = result.Emission != EmissionKind.None - ? BuildEmission(state, result.State, result.Emission, worstStatus) + ? BuildEmission(state, result.State, result.Emission, worstStatus, captured) : null; if (transition is not null) { @@ -972,7 +981,7 @@ public sealed class ScriptedAlarmEngine : IDisposable else if (qualityBucketChanged) { // No transition (or a Suppressed one) but the quality bucket moved — annotate out of band. - pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus)); + pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus, captured)); } return result.State; } @@ -984,7 +993,7 @@ public sealed class ScriptedAlarmEngine : IDisposable /// private void MirrorPredicate(AlarmState state, AlarmScratch scratch, ScriptRunOutcome published) { - if (_shadow is null) return; + if (_shadow is null || scratch.HasProjectedInputs) return; _shadow.Mirror(new ScriptInvocation( state.Definition.AlarmId, ScriptContextKind.AlarmPredicate, state.Definition.PredicateScriptSource, scratch.ReadCache, _scriptTimeout), published); @@ -1030,6 +1039,7 @@ public sealed class ScriptedAlarmEngine : IDisposable var runner = _runner!; var after = new AlarmConditionState[items.Count]; var scratches = new AlarmScratch[items.Count]; + var capturedInputs = new CapturedInputs[items.Count]; var worst = new uint[items.Count]; var slot = new int[items.Count]; var invocations = new List(items.Count); @@ -1041,21 +1051,39 @@ public sealed class ScriptedAlarmEngine : IDisposable var scratch = scratches[i] = _scratchByAlarmId.GetOrAdd( state.Definition.AlarmId, _ => new AlarmScratch(state.Inputs, state.Logger, _clock)); RefillReadCache(scratch.ReadCache, state.Inputs); + var captured = capturedInputs[i] = CaptureInputs(state, scratch.ReadCache); worst[i] = WorstInputStatus(scratch.ReadCache); - if (!AreInputsReady(scratch.ReadCache)) + if (!AreInputsReady(scratch.ReadCache) || captured.Evidence is { IsValid: false }) { slot[i] = -1; continue; } + if (!TryRetainInputs(captured, out var physicalLease)) + { + slot[i] = -1; + continue; + } + if (physicalLease is not null && runner is not IPhysicalScriptRunner) + { + physicalLease.Dispose(); + slot[i] = -1; + continue; + } slot[i] = invocations.Count; // A copy: the runner may still read the inputs after the caller has its answer (a soft timeout), and the // scratch is refilled by the next pass. invocations.Add(new ScriptInvocation(state.Definition.AlarmId, ScriptContextKind.AlarmPredicate, state.Definition.PredicateScriptSource, - new Dictionary(scratch.ReadCache, StringComparer.Ordinal), _scriptTimeout, state.Logger)); + captured.Values, _scriptTimeout, state.Logger, physicalLease)); } - var outcomes = invocations.Count == 0 ? [] : runner.RunBatch(invocations, ct); + IReadOnlyList> outcomes; + try { outcomes = invocations.Count == 0 ? [] : runner.RunBatch(invocations, ct); } + catch + { + foreach (var invocation in invocations) invocation.PhysicalLease?.Dispose(); + throw; + } PredicateBatchSubmittedForTest?.Invoke(invocations.Count); // Pass 2, in order: exactly what the serial path does with each alarm. @@ -1066,20 +1094,21 @@ public sealed class ScriptedAlarmEngine : IDisposable if (slot[i] < 0) { if (TrackQualityBucket(state.Definition.AlarmId, worst[i])) - pendingEmissions.Add(BuildQualityEmission(state, seed, worst[i])); + pendingEmissions.Add(BuildQualityEmission(state, seed, worst[i], capturedInputs[i])); after[i] = seed; continue; } var outcome = await outcomes[slot[i]].ConfigureAwait(false); - after[i] = ApplyPredicateOutcome(state, seed, scratch, worst[i], outcome, nowUtc, ct, pendingEmissions); + after[i] = capturedInputs[i].Evidence is { IsValid: false } ? seed + : ApplyPredicateOutcome(state, seed, scratch, worst[i], outcome, nowUtc, ct, pendingEmissions, capturedInputs[i]); } return after; } /// One runner outcome onto one alarm (the second half of ). private AlarmConditionState ApplyPredicateOutcome(AlarmState state, AlarmConditionState seed, AlarmScratch scratch, - uint worstStatus, ScriptRunOutcome outcome, DateTime nowUtc, CancellationToken ct, List pendingEmissions) + uint worstStatus, ScriptRunOutcome outcome, DateTime nowUtc, CancellationToken ct, List pendingEmissions, CapturedInputs captured) { switch (outcome.Status) { @@ -1115,10 +1144,10 @@ public sealed class ScriptedAlarmEngine : IDisposable var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus); var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc); var transition = result.Emission != EmissionKind.None - ? BuildEmission(state, result.State, result.Emission, worstStatus) + ? BuildEmission(state, result.State, result.Emission, worstStatus, captured) : null; if (transition is not null) pendingEmissions.Add(transition); - else if (qualityBucketChanged) pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus)); + else if (qualityBucketChanged) pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus, captured)); return result.State; } @@ -1216,13 +1245,14 @@ public sealed class ScriptedAlarmEngine : IDisposable /// released. /// private ScriptedAlarmEvent? BuildEmission( - AlarmState state, AlarmConditionState condition, EmissionKind kind, uint worstInputStatus) + AlarmState state, AlarmConditionState condition, EmissionKind kind, uint worstInputStatus, CapturedInputs? captured = null) { // Suppressed kind means shelving ate the emission — we don't fire for subscribers // but the state record still advanced so startup recovery reflects reality. if (kind == EmissionKind.Suppressed || kind == EmissionKind.None) return null; - var message = MessageTemplate.Resolve(state.Definition.MessageTemplate, TryLookup); + var message = MessageTemplate.Resolve(state.Definition.MessageTemplate, + captured?.Evidence is null ? LookupControlValue : path => captured.Values.GetValueOrDefault(path)); return new ScriptedAlarmEvent( AlarmId: state.Definition.AlarmId, EquipmentPath: state.Definition.EquipmentPath, @@ -1249,7 +1279,7 @@ public sealed class ScriptedAlarmEngine : IDisposable HistorizeToAveva: state.Definition.HistorizeToAveva, // The worst input quality at evaluation time rides the transition so the projected // full snapshot keeps quality consistent (no clobber-to-Good). - WorstInputStatusCode: worstInputStatus); + WorstInputStatusCode: worstInputStatus) { InputEvidence = captured?.Evidence }; } /// @@ -1260,19 +1290,20 @@ public sealed class ScriptedAlarmEngine : IDisposable /// no /alerts row, no historian write); the fan-out skips it. /// private ScriptedAlarmEvent BuildQualityEmission( - AlarmState state, AlarmConditionState condition, uint worstInputStatus) + AlarmState state, AlarmConditionState condition, uint worstInputStatus, CapturedInputs? captured = null) => new( AlarmId: state.Definition.AlarmId, EquipmentPath: state.Definition.EquipmentPath, AlarmName: state.Definition.AlarmName, Kind: state.Definition.Kind, Severity: state.Definition.Severity, - Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, TryLookup), + Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, + captured?.Evidence is null ? LookupControlValue : path => captured.Values.GetValueOrDefault(path)), Condition: condition, Emission: EmissionKind.QualityChanged, TimestampUtc: _clock(), HistorizeToAveva: state.Definition.HistorizeToAveva, - WorstInputStatusCode: worstInputStatus); + WorstInputStatusCode: worstInputStatus) { InputEvidence = captured?.Evidence }; /// Worst OPC UA StatusCode across a refilled read cache — the entry with the highest severity /// bits (top 2). An input that has never been pushed is NOT a quality signal: it means "no data", which @@ -1338,6 +1369,7 @@ public sealed class ScriptedAlarmEngine : IDisposable /// private void FireEvent(ScriptedAlarmEvent evt) { + if (evt.InputEvidence is { IsValid: false }) return; try { OnEvent?.Invoke(this, evt); } catch (Exception ex) { @@ -1345,6 +1377,69 @@ public sealed class ScriptedAlarmEngine : IDisposable } } + private sealed record CapturedInputs(Dictionary Values, IAlarmInputEvidence? Evidence); + + private sealed class PhysicalInputLease(IDisposable[] leases) : IDisposable + { + private IDisposable[]? _leases = leases; + public void Dispose() + { + var owned = Interlocked.Exchange(ref _leases, null); + if (owned is null) return; + foreach (var lease in owned) lease.Dispose(); + } + } + + private bool TryRetainInputs(CapturedInputs captured, out IDisposable? lease) + { + lease = null; + if (captured.Evidence is null) return true; + if (!captured.Evidence.IsValid) return false; + var retained = new List(); + try + { + if (_upstream is IAlarmInputEvidenceSource source) + foreach (var snapshot in captured.Values.Values.Distinct(ReferenceEqualityComparer.Instance)) + if (source.CaptureEvidence(snapshot) is IAlarmInputPhysicalEvidence physical) + { + if (!physical.TryRetainPhysical(snapshot, out var owned) || owned is null) return false; + retained.Add(owned); + } + if (!captured.Evidence.IsValid) return false; + if (retained.Count != 0) lease = new PhysicalInputLease(retained.ToArray()); + retained.Clear(); + return true; + } + finally { foreach (var owned in retained) owned.Dispose(); } + } + + private sealed class InputEvidence(IAlarmInputEvidence[] inputs) : IAlarmInputEvidence + { + public bool IsValid => inputs.All(input => input.IsValid); + } + + private CapturedInputs CaptureInputs(AlarmState state, Dictionary inputs) + { + if (_upstream is not IAlarmInputEvidenceSource source || + !inputs.Values.Any(snapshot => source.CaptureEvidence(snapshot) is not null) && + !state.TemplateTokens.Any(path => TryLookup(path) is { } snapshot && source.CaptureEvidence(snapshot) is not null)) + return new CapturedInputs(inputs, null); + var values = new Dictionary(inputs, StringComparer.Ordinal); + foreach (var path in state.TemplateTokens) + if (!values.ContainsKey(path) && TryLookup(path) is { } snapshot) values[path] = snapshot; + var evidence = values.Values.Select(source.CaptureEvidence).OfType().ToArray(); + return new CapturedInputs(values, evidence.Length == 0 ? null : new InputEvidence(evidence)); + } + + // Control/recovery events have durable semantics independent of current inputs. They must not + // embed transient remote values without the original evaluation's authority and physical lease. + private DataValueSnapshot? LookupControlValue(string path) + { + var value = TryLookup(path); + return value is not null && _upstream is IAlarmInputEvidenceSource source && source.CaptureEvidence(value) is not null + ? null : value; + } + private DataValueSnapshot? TryLookup(string path) => _valueCache.TryGetValue(path, out var v) ? v : null; @@ -1624,6 +1719,7 @@ public sealed class ScriptedAlarmEngine : IDisposable /// The reason the last evaluation did not complete (timeout / refused / quarantined), or null /// after a completed run — the once-per-change log gate for PredicateDidNotComplete. public string? LastNonCompletion { get; set; } + public bool HasProjectedInputs { get; set; } /// /// Initializes a new AlarmScratch with the specified inputs, logger, and clock. @@ -1666,7 +1762,12 @@ public sealed record ScriptedAlarmEvent( // since Core.ScriptedAlarms does not reference Commons. The host carries it to the condition // node UNCHANGED — it used to be collapsed to a 3-state bucket and re-expanded, losing the sub-code. // Default 0u == Good keeps every existing constructor call unchanged. - uint WorstInputStatusCode = 0u); + uint WorstInputStatusCode = 0u) +{ + /// Transient exact-input authority for the local final emission boundary. + [System.Text.Json.Serialization.JsonIgnore] + public IAlarmInputEvidence? InputEvidence { get; init; } +} /// /// A loaded alarm's current condition, ready to be projected onto its OPC UA node. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs index cd20b44c7..306a6816f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs @@ -67,7 +67,7 @@ public sealed record ScriptRunnerStatus( /// HMAC-verified compiled images instead of re-entering Roslyn after a restart. /// /// -public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable, IDisposable +public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisposable, IDisposable { /// The worker entry assembly's file name. public const string WorkerAssemblyFileName = "ZB.MOM.WW.OtOpcUa.ScriptWorker.dll"; @@ -366,6 +366,13 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable, public async Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(invocation); + var ownership = new PhysicalLeaseOwnership(invocation.PhysicalLease); + try { return await RunOwnedAsync(invocation, ownership, ct).ConfigureAwait(false); } + finally { ownership.DisposeIfUntransferred(); } + } + + private async Task RunOwnedAsync(ScriptInvocation invocation, PhysicalLeaseOwnership ownership, CancellationToken ct) + { if (Volatile.Read(ref _disposed) != 0) return ScriptRunOutcome.Unavailable(ScriptRunOutcome.RunnerUnavailableReason); var key = InProcessScriptRunner.ScopedKey(invocation.Kind, invocation.Key); @@ -435,7 +442,8 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable, // run by then. var submitted = Stopwatch.GetTimestamp(); var pending = connection.Submit(key, BuildRequest(key, entry, invocation), invocation.Timeout, - _worker.EffectiveHardGrace(invocation.Timeout), SlotRelease(key, state, gate)); + _worker.EffectiveHardGrace(invocation.Timeout), SlotRelease(key, state, gate, ownership)); + ownership.Transfer(); handedOff = true; return await AwaitSubmittedAsync(key, state, invocation, shard, connection, pending, submitted, ct).ConfigureAwait(false); } @@ -478,6 +486,7 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable, { var invocation = invocations[i]; ArgumentNullException.ThrowIfNull(invocation); + if (invocation.PhysicalLease is not null) { outcomes[i] = RunAsync(invocation, ct); continue; } switch (TryPrepareBatchItem(invocation, out var item, out var answered)) { case BatchPreparation.Submit: @@ -555,16 +564,20 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable, /// 32 of 200 refused when the release was an unordered continuation). On a worker death, attribution (strike, /// quarantine, suspect) has already run by then. /// - private Action SlotRelease(string key, KeyState state, SemaphoreSlim? heldGate) + private Action SlotRelease(string key, KeyState state, SemaphoreSlim? heldGate, IDisposable? physicalLease = null) { var released = 0; return () => { if (Interlocked.Exchange(ref released, 1) != 0) return; - SlotReleasingForTest?.Invoke(key); - Volatile.Write(ref state.StalledRun, null); - Interlocked.Exchange(ref state.InFlight, 0); - heldGate?.Release(); + try + { + SlotReleasingForTest?.Invoke(key); + Volatile.Write(ref state.StalledRun, null); + Interlocked.Exchange(ref state.InFlight, 0); + heldGate?.Release(); + } + finally { physicalLease?.Dispose(); } }; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs index 77953ac11..3cdf6e3ca 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs @@ -66,6 +66,9 @@ public interface IScriptRunner IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind); } +/// A runner that owns invocation physical leases until underlying execution actually completes. +public interface IPhysicalScriptRunner : IScriptRunner { } + /// Which script context (and result type) a script compiles against. public enum ScriptContextKind { @@ -86,13 +89,15 @@ public enum ScriptContextKind /// The read cache: dependency snapshots by path. Not mutated until the run completes. /// The soft budget T. /// The per-evaluation script logger ctx.Logger writes through; null ⇒ a silent logger. +/// Retained input ownership transferred to a physical-lifetime-aware runner. public sealed record ScriptInvocation( string Key, ScriptContextKind Kind, string Source, IReadOnlyDictionary Inputs, TimeSpan Timeout, - Serilog.ILogger? ScriptLogger = null); + Serilog.ILogger? ScriptLogger = null, + IDisposable? PhysicalLease = null); /// How an evaluation ended. public enum ScriptRunStatus diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs index 7ed57ee70..6368aa259 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs @@ -18,7 +18,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// existing guard code, so the default mode is unchanged byte for byte. Unlike those paths, this runner remembers /// compile failures by source for every kind (Calculation already did, R07:P4). /// -public sealed class InProcessScriptRunner : IScriptRunner, IDisposable +public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable { private readonly CompiledScriptCache _valueCache = new(); private readonly CompiledScriptCache _predicateCache = new(); @@ -40,6 +40,13 @@ public sealed class InProcessScriptRunner : IScriptRunner, IDisposable public async Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(invocation); + var ownership = new PhysicalLeaseOwnership(invocation.PhysicalLease); + try { return await RunOwnedAsync(invocation, ownership, ct).ConfigureAwait(false); } + finally { ownership.DisposeIfUntransferred(); } + } + + private async Task RunOwnedAsync(ScriptInvocation invocation, PhysicalLeaseOwnership ownership, CancellationToken ct) + { var key = ScopedKey(invocation.Kind, invocation.Key); var failureKey = ScopedKey(invocation.Kind, invocation.Source); if (_compileFailures.TryGetValue(failureKey, out var known)) return ScriptRunOutcome.Failed(known); @@ -54,7 +61,7 @@ public sealed class InProcessScriptRunner : IScriptRunner, IDisposable { var evaluator = await Task.Run(() => _valueCache.GetOrCompile(invocation.Source), ct).ConfigureAwait(false); var context = new VirtualTagContext(invocation.Inputs, static (_, _) => { }, logger); - var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct) + var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct, ownership.Transfer()) .ConfigureAwait(false); return ScriptRunOutcome.Ok(value); } @@ -62,7 +69,7 @@ public sealed class InProcessScriptRunner : IScriptRunner, IDisposable { var evaluator = await Task.Run(() => _predicateCache.GetOrCompile(invocation.Source), ct).ConfigureAwait(false); var context = new AlarmPredicateContext(invocation.Inputs, logger); - var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct) + var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct, ownership.Transfer()) .ConfigureAwait(false); return ScriptRunOutcome.Ok(value); } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/PhysicalLeaseOwnership.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/PhysicalLeaseOwnership.cs new file mode 100644 index 000000000..eeefe5009 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/PhysicalLeaseOwnership.cs @@ -0,0 +1,11 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// Idempotent transfer of a retained physical payload to a runner completion callback. +public sealed class PhysicalLeaseOwnership(IDisposable? lease) : IDisposable +{ + private IDisposable? _lease = lease; + private int _transferred; + public IDisposable? Transfer() { Interlocked.Exchange(ref _transferred, 1); return this; } + public void DisposeIfUntransferred() { if (Volatile.Read(ref _transferred) == 0) Dispose(); } + public void Dispose() => Interlocked.Exchange(ref _lease, null)?.Dispose(); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs index ccce6c8bb..9421b42b7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs @@ -174,15 +174,20 @@ public sealed class ScriptRunGuard /// The key's previous run is still executing. /// The run exceeded . /// was cancelled. + /// Input ownership released on nonadmission or actual evaluator completion. public async Task RunAsync( string key, string? sourceIdentity, ScriptEvaluator evaluator, TContext context, TimeSpan timeout, - CancellationToken ct = default) + CancellationToken ct = default, + IDisposable? physicalLease = null) where TContext : ScriptContext { + var transferred = false; + try + { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(evaluator); ArgumentNullException.ThrowIfNull(context); @@ -267,14 +272,19 @@ public sealed class ScriptRunGuard // evaluation still running" — a Bad publish for a script that had finished. Seen under load: // 24 of 4,800 sequential same-key evaluations. A late-finishing orphan that breached the // allocation budget quarantines its key first, so no re-trigger slips in between. - if (succeeded && BreachedBudget(slot.AllocatedBytes)) - Quarantine(key, state, AllocationReason(slot.AllocatedBytes), "allocation"); - SlotReleasingForTest?.Invoke(key); - Volatile.Write(ref state.RunStartedTimestamp, 0); - Interlocked.Exchange(ref state.InFlight, 0); - Interlocked.Decrement(ref _inFlight); + try + { + if (succeeded && BreachedBudget(slot.AllocatedBytes)) + Quarantine(key, state, AllocationReason(slot.AllocatedBytes), "allocation"); + SlotReleasingForTest?.Invoke(key); + Volatile.Write(ref state.RunStartedTimestamp, 0); + Interlocked.Exchange(ref state.InFlight, 0); + Interlocked.Decrement(ref _inFlight); + } + finally { physicalLease?.Dispose(); } } }); + transferred = true; _ = runTask.ContinueWith(t => { @@ -320,6 +330,8 @@ public sealed class ScriptRunGuard throw new ScriptQuarantinedException(key, state.QuarantineReason!); } return result; + } + finally { if (!transferred) physicalLease?.Dispose(); } } /// Resolve the key's state, rolling it over when the source identity changed, and refuse a quarantined key. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriver.cs index dbb234d73..b0f85626b 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriver.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging.Abstractions; using Serilog; using ZB.MOM.WW.OtOpcUa.Commons.Engines; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Scripting; namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation; @@ -45,7 +46,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation; /// A historized Bad records BadInternalError. /// /// -public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscribable, IReadable, ISkippedTagReporter, IDisposable +public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjectedDependencyConsumer, ISubscribable, IReadable, ISkippedTagReporter, IDisposable { /// Authored tags this driver could not build into its calc table. A raw tag with /// no scriptId is not a calc tag and computes nothing. @@ -85,6 +86,8 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba // comms-lost input apart from a genuine Good null, and storing values only is what let this driver // compute a Good output from a dead source. private readonly Dictionary _depValues = new(StringComparer.Ordinal); + private readonly Dictionary _projectedProofs = new(StringComparer.Ordinal); + private readonly Dictionary _projectedCacheLeases = new(StringComparer.Ordinal); private readonly HashSet _arrivedDeps = new(StringComparer.Ordinal); private readonly Dictionary _stateByRawPath = new(StringComparer.Ordinal); @@ -105,8 +108,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba // Change-triggered evaluations queued by OnDependencyValue and drained, in arrival order, by a single // pump task. Both fields are guarded by _lock; _pumpScheduled stays true until the pump observes an // empty queue under the lock, so an enqueue can never be lost against a pump that is exiting. - private readonly Queue _pending = new(); + private readonly LinkedList _pending = new(); + private readonly Dictionary> _pendingProjected = new(StringComparer.Ordinal); private bool _pumpScheduled; + private long _projectedQueueVisits; + internal long ProjectedQueueVisitsForTest => Interlocked.Read(ref _projectedQueueVisits); private CalculationTimerScheduler? _timers; private volatile bool _running; @@ -204,6 +210,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba .SelectMany(t => t.DependencyRefs) .Distinct(StringComparer.Ordinal) .ToArray(); + foreach (var path in _projectedProofs.Keys.Except(_dependencyRefs, StringComparer.Ordinal).ToArray()) + { + if (_projectedCacheLeases.Remove(path, out var lease)) lease.Dispose(); + _projectedProofs.Remove(path); + _depValues.Remove(path); + _arrivedDeps.Remove(path); + } } // Reinit config-bind options — mirrors the factory's bind (case-insensitive, enum-string, trailing-comma @@ -261,7 +274,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba // Queued evaluations were prepared against the OUTGOING tag table (old script source, old // dependency set), so they are stale the moment the rebuild lands — drop them rather than // publish one last pre-edit value after the delta was applied. - _pending.Clear(); + ClearPending(); RebuildTagTable(newOptions); } // Drop compiled scripts (IScriptCacheOwner contract — stops collectible ALCs accreting AND forces a @@ -337,7 +350,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba _running = false; StopTimers(); // The pump exits at its next iteration; an evaluation already in flight is bounded by RunTimeout. - lock (_lock) _pending.Clear(); + lock (_lock) ClearPending(); // R07:L2 — nothing in the runtime disposes a driver, and every config change is a respawn, so // the compiled scripts' collectible ALCs survived each generation until GC got round to the whole // driver graph. Drop them here (idempotent; a later InitializeAsync recompiles on first use). An @@ -367,14 +380,38 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba /// public void OnDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc) + => OnDependencyValueCore(rawPath, value, statusCode, timestampUtc, null); + + /// + public void OnProjectedDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc, + IProjectedSamplePublicationProof proof) + => OnDependencyValueCore(rawPath, value, statusCode, timestampUtc, proof); + + private void OnDependencyValueCore(string rawPath, object? value, uint statusCode, DateTime timestampUtc, + IProjectedSamplePublicationProof? proof) { lock (_lock) { + if (_disposed || proof is not null && !_dependencyRefs.Contains(rawPath, StringComparer.Ordinal)) return; + var snapshot = new DataValueSnapshot(value, statusCode, timestampUtc, timestampUtc); + IDisposable? cacheLease = null; + if (proof is not null && (!ProofValid(proof) || + !ProjectedInputBudget.TryRetain([snapshot], out cacheLease) || cacheLease is null)) + { + snapshot = new DataValueSnapshot(null, 0x80310000u, timestampUtc, timestampUtc); + } + if (_projectedCacheLeases.Remove(rawPath, out var oldLease)) oldLease.Dispose(); + _projectedProofs.Remove(rawPath); + if (proof is not null) + { + _projectedProofs[rawPath] = proof; + if (cacheLease is not null) _projectedCacheLeases[rawPath] = cacheLease; + } // Recorded REGARDLESS of _running (R07:H6): the mux adapter registers interest at construction, // so inputs — the mux's retained-value replay in particular — can land before InitializeAsync. // Dropping them left every calc tag waiting for each input to change again; keeping them means // the first trigger after init evaluates from current inputs. Only the EVALUATION is gated. - _depValues[rawPath] = new DataValueSnapshot(value, statusCode, timestampUtc, timestampUtc); + _depValues[rawPath] = snapshot; _arrivedDeps.Add(rawPath); if (!_running) return; if (!_changeDependents.TryGetValue(rawPath, out var dependents) || dependents.Count == 0) return; @@ -387,7 +424,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba foreach (var calcRawPath in dependents) { if (PrepareEvaluation(calcRawPath, timestampUtc) is not { } prepared) continue; - _pending.Enqueue(prepared); + EnqueueEvaluation(prepared); queued = true; } if (queued) SchedulePump(); @@ -459,11 +496,18 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba /// The worst status among /// (). Bad ⇒ the script is HELD and this status is published; /// Good or Uncertain ⇒ the script runs and its result is stamped with it. + /// Captured authority for each projected dependency. + /// Retained ownership of the projected inputs. private sealed record PendingEvaluation( CalculationTagDefinition Definition, IReadOnlyDictionary Dependencies, DateTime TimestampUtc, - uint WorstInputStatus); + uint WorstInputStatus, + IReadOnlyDictionary Proofs, + PhysicalLeaseOwnership? Ownership) : IDisposable + { + public void Dispose() => Ownership?.DisposeIfUntransferred(); + } /// /// Prepare one calc tag's evaluation: resolve the definition, apply the change-gate, and snapshot @@ -502,7 +546,71 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba // Worst-of-input, computed from the SAME snapshot the evaluation will use, so the status // published can never disagree with the values it was derived from. var worst = InputQuality.WorstOf(def.DependencyRefs.Select(r => deps.GetValueOrDefault(r))); - return new PendingEvaluation(def, deps, timestampUtc, worst); + var proofs = new Dictionary(StringComparer.Ordinal); + foreach (var dep in def.DependencyRefs) + if (_projectedProofs.TryGetValue(dep, out var proof)) proofs[dep] = proof; + PhysicalLeaseOwnership? ownership = null; + if (proofs.Count > 0) + { + if (proofs.Values.Any(p => !ProofValid(p)) || + !ProjectedInputBudget.TryRetain(proofs.Keys.Select(key => deps[key]), out var lease) || lease is null) + { + // Do not retain uncharged projected payloads in queued work. + foreach (var key in proofs.Keys) deps[key] = new DataValueSnapshot(null, 0x80310000u, timestampUtc, timestampUtc); + worst = 0x80310000u; + } + else ownership = new PhysicalLeaseOwnership(lease); + } + return new PendingEvaluation(def, deps, timestampUtc, worst, proofs, ownership); + } + + private static bool ProofValid(IProjectedSamplePublicationProof proof) + { + try { return proof.IsValid; } catch (Exception) { return false; } + } + + private bool EvidenceValid(PendingEvaluation pending) + { + foreach (var (path, captured) in pending.Proofs) + { + if (!ProofValid(captured) || !_projectedProofs.TryGetValue(path, out var current)) return false; + try { if (!ReferenceEquals(captured.SourceIdentity, current.SourceIdentity) || !current.IsSourceValid) return false; } + catch (Exception) { return false; } + } + return true; + } + + private void ClearPending() + { + while (_pending.Count != 0) DequeuePending().Dispose(); + } + + private PendingEvaluation DequeuePending() + { + var first = _pending.First!; + _pending.RemoveFirst(); + if (first.Value.Proofs.Count > 0) _pendingProjected.Remove(first.Value.Definition.RawPath); + return first.Value; + } + + private void EnqueueEvaluation(PendingEvaluation pending) + { + // Projected work is latest-wins per tag. Remove its indexed node and append the + // replacement in arrival order, without traversing unrelated projected or local work. + if (pending.Proofs.Count > 0) + { + _projectedQueueVisits++; + if (_pendingProjected.Remove(pending.Definition.RawPath, out var prior)) + { + _projectedQueueVisits++; + _pending.Remove(prior); + prior.Value.Dispose(); + } + var node = _pending.AddLast(pending); + _pendingProjected.Add(pending.Definition.RawPath, node); + _projectedQueueVisits++; + } + else _pending.AddLast(pending); } /// Start the evaluation pump if it is not already running. MUST be called under @@ -535,18 +643,18 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba PendingEvaluation next; lock (_lock) { - if (!_running) _pending.Clear(); + if (!_running) ClearPending(); if (_pending.Count == 0) { _pumpScheduled = false; return; } - next = _pending.Dequeue(); + next = DequeuePending(); } // _evalGate (never _lock) is held across the run, so the pump and the timer ticks still // evaluate one at a time while no host thread can block behind a script. - if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) return; // disposed + if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { next.Dispose(); return; } // disposed try { await RunEvaluationAsync(next).ConfigureAwait(false); @@ -578,7 +686,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba List batch; lock (_lock) { - if (!_running) _pending.Clear(); + if (!_running) ClearPending(); if (_pending.Count == 0) { _pumpScheduled = false; @@ -586,10 +694,10 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba } batch = []; var inBatch = new HashSet(StringComparer.Ordinal); - while (_pending.Count > 0 && inBatch.Add(_pending.Peek().Definition.RawPath)) batch.Add(_pending.Dequeue()); + while (_pending.Count > 0 && inBatch.Add(_pending.First!.Value.Definition.RawPath)) batch.Add(DequeuePending()); } - if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) return; // disposed + if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { foreach (var item in batch) item.Dispose(); return; } // disposed try { await RunEvaluationBatchAsync(batch).ConfigureAwait(false); @@ -610,6 +718,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba /// The prepared evaluations; no calc tag twice. private async Task RunEvaluationBatchAsync(IReadOnlyList batch) { + if (batch.Any(item => item.Proofs.Count > 0 || item.Ownership is not null)) + { + try { foreach (var item in batch) await RunEvaluationAsync(item).ConfigureAwait(false); } + finally { foreach (var item in batch) item.Dispose(); } + return; + } // Hold-on-Bad entries never reach the runner; the rest are submitted together. var requests = new List<(string, string, IReadOnlyDictionary)>(batch.Count); var slot = new int[batch.Count]; @@ -641,7 +755,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba PendingEvaluation? prepared; lock (_lock) prepared = PrepareEvaluation(rawPath, DateTime.UtcNow); if (prepared is null) return; - if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) return; // disposed + if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { prepared.Dispose(); return; } // disposed try { await RunEvaluationAsync(prepared).ConfigureAwait(false); @@ -677,7 +791,16 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba /// The prepared evaluation. private async Task RunEvaluationAsync(PendingEvaluation pending) { + try + { var def = pending.Definition; + lock (_lock) + { + if (!EvidenceValid(pending)) + { + pending = pending with { WorstInputStatus = 0x80310000u }; + } + } // HOLD ON BAD (matching ScriptedAlarmEngine's AreInputsReady): a Bad input is not // usable, so the script does NOT run — which removes the "(double)ctx.GetTag(x).Value threw" @@ -691,9 +814,22 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba // Snapshots, not bare values: the script's ctx.GetTag(path).StatusCode / .SourceTimestampUtc are // then the input's real ones rather than a fabricated Good stamped at evaluation time. - var result = await _evaluator.EvaluateAsync(def.RawPath, def.ScriptSource, pending.Dependencies, _evalCts.Token) + // Pending work remains charged through output acceptance, independently of the + // physical run: either one may outlive the other (a blocked callback or a timeout). + IDisposable? physicalLease = null; + if (pending.Proofs.Count > 0 && + (!ProjectedInputBudget.TryRetain(pending.Proofs.Keys.Select(key => pending.Dependencies[key]), out physicalLease) || + physicalLease is null)) + { + HoldOnBadInput(pending with { WorstInputStatus = 0x80310000u }); + return; + } + var result = await _evaluator.EvaluateAsync(def.RawPath, def.ScriptSource, pending.Dependencies, _evalCts.Token, + physicalLease) .ConfigureAwait(false); ApplyEvaluationResult(pending, result); + } + finally { pending.Dispose(); } } /// A Bad input holds the script: publish the input's own status (once per transition), no script log. @@ -726,8 +862,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba // A ReinitializeAsync can drop the tag while its script is running; its result is then stale // by definition and there is no state left to record it against. if (!_stateByRawPath.TryGetValue(def.RawPath, out var st)) return; - - if (!result.Success) + if (!EvidenceValid(pending)) + { + toPublish = MarkInputsBad(st, 0x80310000u, pending.TimestampUtc); + } + else if (!result.Success) { var reason = result.Reason ?? "evaluator failure"; toPublish = MarkEvaluationFailed(st, pending.TimestampUtc, result.StatusCode ?? StatusBadInternalError); @@ -754,7 +893,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba } if (failureToLog is not null) PublishScriptLog(def, failureToLog); - if (toPublish is { } p) Publish(def.RawPath, p.Value, p.StatusCode, pending.TimestampUtc); + lock (_lock) + { + if (!EvidenceValid(pending) && _stateByRawPath.TryGetValue(def.RawPath, out var current)) + toPublish = MarkInputsBad(current, 0x80310000u, pending.TimestampUtc); + } + if (toPublish is { } p) Publish(def.RawPath, p.Value, p.StatusCode, pending.TimestampUtc, pending); } /// @@ -770,7 +914,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba if (_stateByRawPath.TryGetValue(rawPath, out var st)) st.RecoveryArmed = false; if (!_running || _disposed) return; if (PrepareEvaluation(rawPath, DateTime.UtcNow) is not { } prepared) return; - _pending.Enqueue(prepared); + EnqueueEvaluation(prepared); SchedulePump(); } } @@ -856,13 +1000,31 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba return (st.HasValue ? st.LastValue : null, badStatus); } - private void Publish(string rawPath, object? value, uint statusCode, DateTime timestampUtc) + private void Publish(string rawPath, object? value, uint statusCode, DateTime timestampUtc, + PendingEvaluation? pending = null) { var snapshot = new DataValueSnapshot(value, statusCode, timestampUtc, timestampUtc); - // Fired outside both locks, from the single evaluation worker — so publish order still follows - // evaluation order, and a subscriber can neither deadlock against the state lock nor re-enter the - // driver behind it (DriverInstanceActor marshals the event onto its own thread regardless). - OnDataChange?.Invoke(this, new DataChangeEventArgs(SharedHandle, rawPath, snapshot)); + var handlers = OnDataChange; + if (handlers is null) return; + // Every handler is a distinct acceptance boundary: an earlier callback may block while + // the source is revoked. Local-only publication retains its existing multicast behavior. + if (pending is null || pending.Proofs.Count == 0) + { + handlers.Invoke(this, new DataChangeEventArgs(SharedHandle, rawPath, snapshot)); + return; + } + foreach (EventHandler handler in handlers.GetInvocationList()) + { + lock (_lock) + { + if (!EvidenceValid(pending)) + { + snapshot = new DataValueSnapshot(null, 0x80310000u, timestampUtc, timestampUtc); + if (_stateByRawPath.TryGetValue(rawPath, out var state)) MarkInputsBad(state, 0x80310000u, timestampUtc); + } + } + handler(this, new DataChangeEventArgs(SharedHandle, rawPath, snapshot)); + } } private void PublishScriptLog(CalculationTagDefinition def, string reason) @@ -920,7 +1082,14 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba _disposed = true; _running = false; StopTimers(); - lock (_lock) _pending.Clear(); + lock (_lock) + { + ClearPending(); + foreach (var lease in _projectedCacheLeases.Values) lease.Dispose(); + foreach (var path in _projectedProofs.Keys) _depValues.Remove(path); + _projectedCacheLeases.Clear(); + _projectedProofs.Clear(); + } // Cancel an awaited run first (the guard lets the caller's cancel win over the timeout), then drop // the compiled scripts. try { _evalCts.Cancel(); } catch (ObjectDisposedException) { } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationEvaluator.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationEvaluator.cs index 2b2b7780f..3831ae004 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationEvaluator.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationEvaluator.cs @@ -161,11 +161,17 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO /// The C# script source producing the tag's value. /// Read-only snapshot of dependency values keyed by RawPath. /// Caller cancellation (driver shutdown); wins over the run timeout. + /// Optional projected input ownership transferred to physical execution. /// The evaluation outcome. public async Task EvaluateAsync( string calcTagId, string scriptSource, IReadOnlyDictionary dependencies, - CancellationToken ct = default) + CancellationToken ct = default, IDisposable? physicalLease = null) { + var ownership = new PhysicalLeaseOwnership(physicalLease); + try + { + if (physicalLease is not null && _runner is not null && _runner is not IPhysicalScriptRunner) + return VirtualTagEvalResult.Failure("runner does not support projected input ownership"); if (_disposed) return VirtualTagEvalResult.Failure("evaluator disposed"); if (string.IsNullOrWhiteSpace(scriptSource)) return VirtualTagEvalResult.Failure("empty expression"); @@ -201,21 +207,26 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO // quarantine and the negative compile cache for this seam. Unavailable publishes BadResourceUnavailable. if (_runner is not null) { - var outcome = await _runner.RunAsync(new ScriptInvocation( - calcTagId, ScriptContextKind.Calculation, scriptSource, readCache, _runTimeout, scriptLog), ct).ConfigureAwait(false); + var invocation = new ScriptInvocation(calcTagId, ScriptContextKind.Calculation, scriptSource, readCache, + _runTimeout, scriptLog, physicalLease is null ? null : ownership.Transfer()); + ScriptRunOutcome outcome; + try { outcome = await _runner.RunAsync(invocation, ct).ConfigureAwait(false); } + catch { ownership.Dispose(); throw; } return outcome.ToVirtualTagEvalResult(); } - var result = await RunInProcessAsync(calcTagId, scriptSource, context, ct).ConfigureAwait(false); + var result = await RunInProcessAsync(calcTagId, scriptSource, context, ct, physicalLease is null ? null : ownership).ConfigureAwait(false); // lmxopcua#780 P2 — Shadow: `result` is what gets published; the same evaluation is mirrored to the worker pool // and only compared. Mirror never blocks and nothing it does reaches this result. - if (_shadow is not null && result.ToMirroredOutcome() is { } mirrored) + if (physicalLease is null && _shadow is not null && result.ToMirroredOutcome() is { } mirrored) _shadow.Mirror(new ScriptInvocation(calcTagId, ScriptContextKind.Calculation, scriptSource, readCache, _runTimeout), mirrored); return result; + } + finally { ownership.DisposeIfUntransferred(); } } private async Task RunInProcessAsync( - string calcTagId, string scriptSource, VirtualTagContext context, CancellationToken ct) + string calcTagId, string scriptSource, VirtualTagContext context, CancellationToken ct, PhysicalLeaseOwnership? ownership) { // A source that already failed to compile fails the same way without touching Roslyn (R07:P4). var sourceKey = HashSource(scriptSource); @@ -258,7 +269,7 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO // CancellationToken can't interrupt a CPU-bound/infinite-loop Roslyn script, so the wall-clock // budget is what bounds a runaway script — and the guard is what keeps the next trigger from // stacking another orphan behind it (one per tag, then quarantine). - var raw = await _guard.RunAsync(calcTagId, scriptSource, evaluator, context, _runTimeout, ct) + var raw = await _guard.RunAsync(calcTagId, scriptSource, evaluator, context, _runTimeout, ct, ownership?.Transfer()) .ConfigureAwait(false); return VirtualTagEvalResult.Ok(raw); } @@ -279,7 +290,7 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO { return VirtualTagEvalResult.Failure("evaluation cancelled (driver shutting down)"); } - catch (ObjectDisposedException) when (!_disposed && attempt == 0) + catch (ObjectDisposedException) when (!_disposed && attempt == 0 && ownership is null) { // A concurrent ClearCompiledScripts disposed the evaluator between our GetOrCompile and the // run's disposed-guard. Re-fetch (recompiling the same source into the CURRENT generation) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index 7644c1146..3a9c33fa6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -9,6 +9,7 @@ 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.Host.Grpc; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.Runtime; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; @@ -62,6 +63,67 @@ public static class DataConnectionRegistration () => sp.GetRequiredService().Serving, sp.GetRequiredService().ClusterId)); services.AddSingleton(sp => new DataOperationPolicy(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService())); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => new ProjectedCatalogCache(options.MaxMonitoredItems, options.Hub.MaxTrackedSources, + sp.GetRequiredService(), sp.GetRequiredService(), options.MaxTransportBytes)); + services.AddSingleton(sp => new BrowseContinuationRegistry(options.MaxMonitoredItems, sp.GetRequiredService())); + services.AddSingleton(sp => new RemoteNamespaceResolver(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), 256, options.MaxConcurrentCalls)); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(); + services.AddSingleton(sp => new ProjectedNamespaceApplier(sp.GetRequiredService(), + sp.GetRequiredService(), options.MaxConcurrentCalls)); + services.AddSingleton(sp => new ProjectedBrowseAccess(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), (uri, identifier) => + sp.GetRequiredService().TryGetNodeId(uri, identifier, out var nodeId) ? nodeId : null, + new DataBudget(options.UnaryTimeout, 1000, options.MaxMessageBytes), options.MaxConcurrentCalls)); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => new ActorProjectedValuePublisher( + () => sp.GetService() is { } registry && registry.TryGet(out var host) ? host : null, + route => + { + var catalog = sp.GetRequiredService(); + var mappings = sp.GetRequiredService(); + return catalog.TryResolveProjected(route.Realm, route.LocalIdentifier, out var proof) && proof is not null + && proof.Generation == route.ProjectionGeneration && proof.Lease.IsValid && proof.Lease.Serving == route.Serving + && proof.Metadata.View.MappingId is { } mappingId && mappings.TryGetConnectionId(mappingId, out var connectionId) + && route.DriverInstanceId == "grpc-data:" + connectionId; + }, options.MaxMonitoredItems, options.MaxPendingBytes, sp.GetRequiredService(), options.MaxTransportBytes)); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => new ProjectedDataAccess(sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + mappingId => sp.GetRequiredService().TryGetConnectionId(mappingId, out var connectionId) + ? connectionId : null, + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), + new(options.MaxMonitoredItems, options.MaxConcurrentCalls, options.MaxPendingBytes, options.MaxStreams), + localWriteRole: () => + { + var role = sp.GetRequiredService(); + var state = CaptureRole(role, sp.GetRequiredService()); + var settings = sp.GetService() ?? WarmRedundancySettings.Unset; + var active = sp.GetRequiredService().Current is { IsActive: true }; + return (active && role.ShouldActAsPrimary && state.Role == "Primary" && + (!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation); + })); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddSingleton(sp => new ConfiguredProjectionDiscovery( + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService(), + new DataBudget(options.UnaryTimeout, Math.Min(options.MaxMonitoredItems, 1000), options.MaxMessageBytes), 256)); + services.AddSingleton(sp => new ConfiguredProjectedInterestOwner( + sp.GetRequiredService(), options.MaxMonitoredItems, + options.MaxConcurrentCalls, options.MaxTransportBytes, sp.GetRequiredService())); + services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(sp => { var catalog = sp.GetRequiredService(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynVirtualTagEvaluator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynVirtualTagEvaluator.cs index dc440ce26..8f5313706 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynVirtualTagEvaluator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Engines/RoslynVirtualTagEvaluator.cs @@ -42,7 +42,7 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Engines; /// boundary), never by itself. /// /// -public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCacheOwner, IScriptQuarantineOwner, IDisposable +public sealed class RoslynVirtualTagEvaluator : IProjectedVirtualTagEvaluator, IScriptCacheOwner, IScriptQuarantineOwner, IDisposable { // Purpose-built source-hash-keyed compile cache: Lazy single-compile (no double-compile race) and // Clear()/Dispose() that dispose each evaluator's collectible AssemblyLoadContext. The apply-boundary @@ -135,9 +135,23 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac /// complete synchronously (cheap), a first-use compile is pushed to the pool, and the script run is awaited. /// The outcomes are exactly those of the synchronous overload, which now delegates here. /// - public async Task EvaluateAsync( + public Task EvaluateAsync( string virtualTagId, string expression, IReadOnlyDictionary dependencies) + => EvaluateCoreAsync(virtualTagId, expression, dependencies, null); + + /// + public Task EvaluateProjectedAsync(string virtualTagId, string expression, + IReadOnlyDictionary dependencies, IDisposable physicalLease) + => EvaluateCoreAsync(virtualTagId, expression, dependencies, physicalLease); + + private async Task EvaluateCoreAsync( + string virtualTagId, string expression, IReadOnlyDictionary dependencies, IDisposable? physicalLease) { + var ownership = new PhysicalLeaseOwnership(physicalLease); + try + { + if (physicalLease is not null && _runner is not null && _runner is not IPhysicalScriptRunner) + return VirtualTagEvalResult.Failure("runner does not support projected input ownership"); if (_disposed) return VirtualTagEvalResult.Failure("evaluator disposed"); if (string.IsNullOrWhiteSpace(expression)) return VirtualTagEvalResult.Failure("empty expression"); @@ -176,20 +190,30 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac // coalescer submits those as one batch (design §4.5) and an evaluation on an idle seam at once. if (_batches is not null) { - var outcome = await _batches.RunAsync(new ScriptInvocation( - virtualTagId, ScriptContextKind.VirtualTag, expression, readCache, _runTimeout, scriptLog)).ConfigureAwait(false); + var invocation = new ScriptInvocation(virtualTagId, ScriptContextKind.VirtualTag, expression, + readCache, _runTimeout, scriptLog, physicalLease is null ? null : ownership.Transfer()); + ScriptRunOutcome outcome; + if (physicalLease is null) outcome = await _batches.RunAsync(invocation).ConfigureAwait(false); + else + { + try { outcome = await _runner!.RunAsync(invocation).ConfigureAwait(false); } + catch { ownership.Dispose(); throw; } + } return outcome.ToVirtualTagEvalResult(); } - var result = await RunInProcessAsync(virtualTagId, expression, context).ConfigureAwait(false); + var result = await RunInProcessAsync(virtualTagId, expression, context, physicalLease is null ? null : ownership).ConfigureAwait(false); // lmxopcua#780 P2 — Shadow: `result` is what gets published; the same evaluation is mirrored to the worker pool // and only compared. Mirror never blocks and nothing it does reaches this result. - if (_shadow is not null && result.ToMirroredOutcome() is { } mirrored) + if (physicalLease is null && _shadow is not null && result.ToMirroredOutcome() is { } mirrored) _shadow.Mirror(new ScriptInvocation(virtualTagId, ScriptContextKind.VirtualTag, expression, readCache, _runTimeout), mirrored); return result; + } + finally { ownership.DisposeIfUntransferred(); } } - private async Task RunInProcessAsync(string virtualTagId, string expression, VirtualTagContext context) + private async Task RunInProcessAsync(string virtualTagId, string expression, VirtualTagContext context, + PhysicalLeaseOwnership? ownership) { // 02/S12: fetch + run inside a bounded loop so an ObjectDisposedException caused by a concurrent // apply-boundary ClearCompiledScripts (which disposed the evaluator between GetOrCompile and the @@ -235,7 +259,7 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac // it), so the wall-clock budget is what returns control — and the guard is what stops the // abandoned run from being joined by another on the next trigger (one orphan per tag, then // quarantine), which is the leak the old per-evaluation TimedScriptEvaluator allowed. - var raw = await _guard.RunAsync(virtualTagId, expression, evaluator, context, _runTimeout) + var raw = await _guard.RunAsync(virtualTagId, expression, evaluator, context, _runTimeout, physicalLease: ownership?.Transfer()) .ConfigureAwait(false); return VirtualTagEvalResult.Ok(raw); } @@ -252,7 +276,7 @@ public sealed class RoslynVirtualTagEvaluator : IVirtualTagEvaluator, IScriptCac { return VirtualTagEvalResult.Failure(ex.Message); } - catch (ObjectDisposedException) when (!_disposed && attempt == 0) + catch (ObjectDisposedException) when (!_disposed && attempt == 0 && ownership is null) { // S12: the apply-boundary ClearCompiledScripts disposed the evaluator between our // GetOrCompile and the run's disposed-guard. Re-fetch — GetOrCompile recompiles the same diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index ce88e0bb2..333881835 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -22,7 +22,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO var budget = new DataBudget(_options.UnaryTimeout, 1, _options.MaxMessageBytes); var capabilities = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false); var response = DataProtoMapper.EncodeCapabilities(capabilities with - { ProtocolMinor = Math.Max(2, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true }); + { ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true }); CheckSize(response); var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false); if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index 1aacbbd3c..1d04c3314 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -7,12 +7,15 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ZB.MOM.WW.OtOpcUa.Cluster; +using ZB.MOM.WW.OtOpcUa.Host.Configuration; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; using ZB.MOM.WW.OtOpcUa.Runtime; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.Historian; using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; @@ -55,6 +58,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl private readonly OpcUaEndpointState _endpointState; private readonly bool _rethrowStartFailure; private readonly DriverWriteBounds _writeBounds; + private readonly IProjectedBrowseAccess? _projectedBrowseAccess; + private readonly IProjectedDataAccess? _projectedDataAccess; + private readonly IFederatedProjectionCatalog? _projectedCatalog; + private readonly DataConnectionOptions _dataConnectionOptions; private OpcUaApplicationHost? _appHost; @@ -130,6 +137,9 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl /// . /// The late-bound Warm standby projection (Gitea #717) OpcUaPublishActor drives; /// bound here once the SDK has started. Optional: null (and a non-Warm server) binds nothing. + /// Optional caller-bound mapped browse scheduler. + /// Optional bounded mapped read, write and subscription gateway. + /// Optional live projection catalog used for mapped authorization. public OtOpcUaServerHostedService( IOptions options, DeferredAddressSpaceSink deferredSink, @@ -151,8 +161,15 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl EffectiveRoles? roles = null, NativeAlarmAckPreflightView? ackPreflightView = null, DriverWriteBounds? writeBounds = null, - DeferredStandbyProjection? deferredStandby = null) + DeferredStandbyProjection? deferredStandby = null, + IProjectedBrowseAccess? projectedBrowseAccess = null, + IProjectedDataAccess? projectedDataAccess = null, + IFederatedProjectionCatalog? projectedCatalog = null) { + _dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get() ?? new(); + _projectedBrowseAccess = projectedBrowseAccess; + _projectedDataAccess = projectedDataAccess; + _projectedCatalog = projectedCatalog; _deferredStandby = deferredStandby; ArgumentNullException.ThrowIfNull(aclOptions); ArgumentNullException.ThrowIfNull(time); @@ -239,7 +256,22 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl // first guarantees every node sees it (nodes are never retro-updated). _server.SetHistorianDataUpdater(_historianUpdater.Updater); + if (_dataConnectionOptions.Enabled) + { + _server.SetProjectedBrowseLimits(_dataConnectionOptions.MaxMonitoredItems, _dataConnectionOptions.MaxTransportBytes); + _server.NodeManager.ConfigureProjectedNodeLimits(_dataConnectionOptions.MaxMonitoredItems, _dataConnectionOptions.MaxTransportBytes); + } + _server.NodeManager.ProjectedBrowseAccess = _projectedBrowseAccess; + _server.NodeManager.ProjectedBrowseClock = _time; + _server.NodeManager.ProjectedDataAccess = _projectedDataAccess; + if (_projectedCatalog is { } projectedCatalog) + _server.NodeManager.MappedSubjectResolver = (realm, identifier) => + projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns, + identifier, out var proof) && proof is not null + ? MappedNodeResolution.Mapped(proof.Metadata.View, proof.Subject, proof.Resolver, proof.Lease) + : MappedNodeResolution.Deny; _deferredSink.SetSink(new SdkAddressSpaceSink(_server.NodeManager)); + (_projectedBrowseAccess as ProjectedBrowseAccess)?.RefreshAnchors(); // Wire the reverse-path inbound-alarm-command router: a client Acknowledge/Confirm/Shelve that // passes the node manager's AlarmAck gate publishes the mapped AlarmCommand onto the cluster diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs new file mode 100644 index 000000000..b326e5dbe --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNamespacePageSink.cs @@ -0,0 +1,17 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Resolves the currently bound SDK page sink without retaining a retired node manager. +public sealed class DeferredProjectedNamespacePageSink(DeferredAddressSpaceSink deferred) : IProjectedNamespacePageSink +{ + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => + deferred.GetCapability()?.TryApply(parent, nodes, commit) ?? false; + + public bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func commit) => + deferred.GetCapability()?.TryApplyRootLeaf(anchorId, rootDefinition, commit) ?? false; + + public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => + deferred.GetCapability()?.TryRemove(nodeId, expected) ?? false; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs new file mode 100644 index 000000000..2e70f49c2 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/DeferredProjectedNodeAccess.cs @@ -0,0 +1,26 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Resolves projected node capabilities from the currently bound SDK sink. +public sealed class DeferredProjectedNodeAccess(DeferredAddressSpaceSink deferred) : IProjectedNodeLookup, IProjectedAnchorSink +{ + public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) + { + definition = null; + return deferred.GetCapability()?.TryResolve(nodeId, out definition) == true; + } + public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) + { + nodeId = null; + return deferred.GetCapability()?.TryGetNodeId(namespaceUri, identifier, out nodeId) == true; + } + public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId) + { + nodeId = null; + return deferred.GetCapability()?.TryEnsureProjectedAnchor(definition, out nodeId) == true; + } + public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected) => + deferred.GetCapability()?.TryRemoveProjectedAnchor(nodeId, expected) == true; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedBrowseAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedBrowseAccess.cs new file mode 100644 index 000000000..f2a219085 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedBrowseAccess.cs @@ -0,0 +1,28 @@ +using Opc.Ua; +using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Borrowed SDK browse state; implementations must not retain or mutate the continuation object. +public sealed record ProjectedBrowseContext(NodeId Parent, RoleCarryingUserIdentity? Caller, + ContinuationPoint Continuation, long RequestStartedTimestamp); + +/// A copied, caller-bound request for one projected page. +public sealed record ProjectedBrowsePageRequest(NodeId Parent, RoleCarryingUserIdentity Caller, string? Cursor, + uint MaximumResults, long RequestStartedTimestamp); + +/// An immutable page snapshot; authority must remain live through emission. +public sealed record ProjectedBrowsePage(ProjectedBrowseReadiness Status, IReadOnlyList Children, + string? NextCursor, bool Complete, Func IsCurrent, long RetainedBytes = 0); + +/// Per-caller synchronous lookup and bounded scheduling, never network I/O. +public interface IProjectedBrowseAccess +{ + ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context); + ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest request) => + new(ProjectedBrowseReadiness.Unavailable, [], null, false, static () => false); + /// Waits for a bounded coalesced page preparation without occupying an SDK lock. + Task WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken) => + Task.FromResult(GetOrSchedulePage(request)); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs new file mode 100644 index 000000000..ca5b55177 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedDataAccess.cs @@ -0,0 +1,35 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// A caller- and item-scoped projection demand, bound to its original local and remote authority. +public interface IProjectedDemandLease : IDisposable +{ + DataView OriginView { get; } + DataRealm Realm { get; } + string LocalIdentifier { get; } + long ProjectionGeneration { get; } + /// Maximum allowed origin-cache age; zero denies sample delivery. + TimeSpan MaximumSampleAge => TimeSpan.Zero; + ServingIdentity Serving { get; } + CancellationToken CancellationToken { get; } + bool IsValid { get; } +} + +/// Nonblocking local admission and bounded scheduling for projected data. +public interface IProjectedDataAccess +{ + TimeProvider Clock { get; } + bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand); + /// On success owns the demand through physical completion; otherwise the caller retains it. + bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp); + Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, + long requestStartedTimestamp, CancellationToken cancellationToken); + bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval); + /// Requests a coalesced fresh authenticated snapshot without changing caller ownership. + bool RequestFreshSnapshot(IProjectedDemandLease demand) => false; + /// True while a demand or physically retained operation still owns this projection. + bool HasLiveDemand(DataRealm realm, string localIdentifier) => true; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs new file mode 100644 index 000000000..c5a2c6e0b --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNamespacePageSink.cs @@ -0,0 +1,12 @@ +using Opc.Ua; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Applies a prepared page atomically with its cursor commit. +public interface IProjectedNamespacePageSink +{ + bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit); + bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected); + /// Atomically promotes an owned mapping anchor to its verified leaf value. + bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func commit) => false; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs new file mode 100644 index 000000000..844a59658 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/IProjectedNodeLookup.cs @@ -0,0 +1,23 @@ +using Opc.Ua; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Reports bytes retained by a projected node's detached authority guard. +public interface IProjectedRetainedAuthority +{ + long RetainedBytes { get; } +} + +/// Resolves against the currently live SDK node manager, without conferring authority. +public interface IProjectedNodeLookup +{ + bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition); + bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId); +} + +/// Installs and retires locally authorized mapping anchors. +public interface IProjectedAnchorSink +{ + bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId); + bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index eaaaa7a18..669bfe85b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -8,6 +8,15 @@ using Opc.Ua.Server; using ZB.MOM.WW.OtOpcUa.Commons.Observability; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using DataRealm = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataRealm; +using DataBudget = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataBudget; +using DataOperations = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations; +using DataMetadata = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataMetadata; +using DataValueKind = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValueKind; +using ProjectedDataIds = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedDataIds; +using IProjectedValueSink = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedValueSink; +using IProjectedSamplePublicationProof = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof; +using ProjectedValueWrite = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedValueWrite; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; // The SDK's HistoryRead service result (the value the override fills + hands back) and the historian @@ -20,6 +29,25 @@ using DataWriteState = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataW namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; +/// Current page readiness for a projected browse parent. +public enum ProjectedBrowseReadiness { Ready, Pending, Unavailable, InvalidContinuation } + +/// A checked local placement for a remotely derived variable. +public sealed record ProjectedVariableDefinition(DataRealm Realm, string LocalIdentifier, NodeId Parent, + DataMetadata Metadata, long ProjectionGeneration, Func AuthorityIsCurrent) +{ + /// Stable across same-node metadata renewal, replaced on node retirement. + public ProjectedNodeLifetime Lifetime { get; init; } = new(); +} + +/// Locally authorized placement for a configured mapping anchor. +public sealed record ProjectedAnchorDefinition(DataRealm Realm, string LocalIdentifier, NodeId Parent, + string BrowseName, string LocalSubject, string MappingId, long MappingRevision, Func AuthorityIsCurrent) +{ + /// Stable for one installed mapping anchor incarnation. + public ProjectedNodeLifetime Lifetime { get; init; } = new(); +} + /// /// Custom OPC UA that owns the writable address space for /// the OtOpcUa server. Variable nodes are declared by (the applier's @@ -48,15 +76,37 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; // re-implementing the interface is the only way to put an ACL decision on that path. Since #855 condition events no // longer take it, and since #878 the decision there is a flat deny under enforcement (the SDK memoizes it, so it must // not depend on grants). Every other member maps to the inherited implementation exactly as before. -public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 +public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink { + /// Nonblocking lookup of the current projected parent readiness. + public Func? ProjectedBrowseReadiness { get; set; } + /// Caller-aware, nonblocking projected browse scheduler. + public IProjectedBrowseAccess? ProjectedBrowseAccess { get; set; } + /// Current caller-scoped projected data demand provider. + private IProjectedDataAccess? _projectedDataAccess; + public IProjectedDataAccess? ProjectedDataAccess + { + get => _projectedDataAccess; + set + { + _projectedDataAccess = value; + if (_authorizer is { } authorizer) authorizer.MappedNamespacePredicate = value is null ? null : IsProjectedDescendant; + } + } + + private bool IsProjectedDescendant(NodeId nodeId) => + (nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3]) && (!_projectedAnchors.ContainsKey(nodeId) || _projectedRootLeaves.ContainsKey(nodeId)); + /// Clock shared with the projected browse scheduler. + public TimeProvider ProjectedBrowseClock { get; set; } = TimeProvider.System; + /// v3 dual-namespace: both the Raw (device tree) and UNS (equipment tree) namespaces are /// registered with the SDK so nodes can be minted in either. is /// registered FIRST (namespace index [0]) and /// SECOND ([1]); maps a realm /// to its index. Which realm a node belongs to travels with each sink call as an /// — the namespace is never parsed back out of the id string. - private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri }; + private static readonly string[] RegisteredNamespaceUris = { V3NodeIds.RawNamespaceUri, V3NodeIds.UnsNamespaceUri, + ProjectedDataIds.RawNamespaceUri, ProjectedDataIds.UnsNamespaceUri }; /// Transitional alias kept so the pre-v3 single-namespace integration tests /// (SubscriptionSurvivalTests) still resolve a namespace index. It points at @@ -176,13 +226,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 : this(server, configuration, logger) { _standby = standby ?? WarmStandbyState.Off; - if (_standby.WarmMode) - { - // Spec §4.6 item 1: ordinary-tag Value items are built by OrdinaryTagMonitoredItem, which marks each - // notification. Warm only — Unset/None keep the SDK's own manager. - m_monitoredItemManager.Dispose(); - m_monitoredItemManager = new OrdinaryTagItemManager(this.ToAsyncNodeManager(), server); - } + // The wrapper retains the SDK's normal behavior for ordinary non-Warm items, and installs + // item-bound publication proofs for mapped data in every redundancy mode. + m_monitoredItemManager.Dispose(); + m_monitoredItemManager = new OrdinaryTagItemManager(this.ToAsyncNodeManager(), server, this, _standby.WarmMode); } /// The Warm standby flags (Gitea #717). unless the server is Warm. @@ -225,7 +272,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 /// The resolved SDK node id. /// The realm the node belongs to. private AddressSpaceRealm RealmOf(NodeId nodeId) => - nodeId.NamespaceIndex == NamespaceIndexes[0] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns; + nodeId.NamespaceIndex == NamespaceIndexes[0] || nodeId.NamespaceIndex == NamespaceIndexes[2] ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns; /// Zero-allocation realm-qualified map key. Replaces the formatted "ns=N;s=id" string key — /// the (realm, id) pair is the same identity without the per-write NodeId + string allocations @@ -703,7 +750,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 { // #854 review: refuse new Server-object refreshes and let the ones in flight finish (the base's private // NodeManagerOperation guard does this for its own paths). - _disposing = true; + lock (Lock) _disposing = true; Interlocked.MemoryBarrier(); // the flag write must not be reordered after the in-flight read (#854 re-review) if (!SpinWait.SpinUntil(() => Volatile.Read(ref _refreshesInFlight) == 0, TimeSpan.FromSeconds(10))) _logger.LogWarning("Node manager disposed with {Count} Server-object ConditionRefresh call(s) still in flight after 10 s", @@ -746,6 +793,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 { value.UnsSubjectResolver = ResolveUnsAclSubject; value.MappedSubjectResolver = _mappedSubjectResolver; + value.MappedNamespacePredicate = _projectedDataAccess is null ? null : IsProjectedDescendant; } _authorizer = value; } @@ -765,7 +813,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 } } - private bool SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null; + private bool SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null || NamespaceIndexes.Count >= 4; /// /// True when a wired authorizer is switched on — i.e. when ACL grants, rather than the server-wide @@ -4135,6 +4183,640 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 } } + private readonly ConcurrentDictionary _projectedAnchors = new(); + private readonly ConcurrentDictionary _projectedRootLeaves = new(); + + /// Installs an anchor only beneath its exact live local parent, without remote authority. + public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId) + { + nodeId = null; + if (definition is null || definition.Realm is not (DataRealm.Raw or DataRealm.Uns) || + string.IsNullOrWhiteSpace(definition.LocalIdentifier) || string.IsNullOrWhiteSpace(definition.BrowseName) || + string.IsNullOrWhiteSpace(definition.MappingId) || string.IsNullOrWhiteSpace(definition.LocalSubject) || + !ProjectedDataIds.TryDecodeIdentifier(definition.LocalIdentifier, out var mappingId, out _) || mappingId != definition.MappingId || + definition.MappingRevision <= 0 || !definition.Lifetime.IsActive || definition.AuthorityIsCurrent is null) + return false; + lock (Lock) + { + if (_disposing || !definition.AuthorityIsCurrent() || + GetManagerHandle(definition.Parent) is not NodeHandle { Node: FolderState parent } || parent.NodeId != definition.Parent) + return false; + var id = new NodeId(definition.LocalIdentifier, definition.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]); + if (_projectedAnchors.TryGetValue(id, out var old)) + { + if (old.Definition.Parent != definition.Parent || old.Definition.MappingId != definition.MappingId || + old.Definition.MappingRevision != definition.MappingRevision || old.Definition.LocalSubject != definition.LocalSubject || + !old.Definition.AuthorityIsCurrent()) return false; + nodeId = id; return true; + } + if (GetManagerHandle(id) is not null) return false; + var charge = ProjectedAnchorCharge(definition); + if (!ReserveProjectedNode(charge)) return false; + var folder = new FolderState(parent) + { + NodeId = id, BrowseName = new QualifiedName(definition.LocalIdentifier, id.NamespaceIndex), + DisplayName = new LocalizedText(definition.BrowseName), EventNotifier = EventNotifiers.None, + TypeDefinitionId = ObjectTypeIds.FolderType, ReferenceTypeId = ReferenceTypeIds.Organizes + }; + if (!definition.AuthorityIsCurrent()) return false; + parent.AddChild(folder); AddPredefinedNode(SystemContext, folder); + _projectedAnchors[id] = (definition, folder); + _projectedNodeCharges.Add(id, charge); _projectedNodeBytes += charge; + nodeId = id; return true; + } + } + + private static long ProjectedAnchorCharge(ProjectedAnchorDefinition definition) => + checked(1024L + 2L * (definition.LocalIdentifier.Length + definition.BrowseName.Length + definition.LocalSubject.Length + definition.MappingId.Length)); + + /// + public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected) + { + lock (Lock) + { + if (_disposing || !_projectedAnchors.TryGetValue(nodeId, out var anchor) || + !ReferenceEquals(anchor.Definition, expected)) return false; + var mappingId = anchor.Definition.MappingId; + foreach (var id in _projectedVariables.Keys.Where(id => + ProjectedDataIds.TryDecodeIdentifier(id.IdentifierAsString, out var mapping, out _) && mapping == mappingId).ToArray()) + { + if (_projectedVariables.Remove(id, out var child)) + { + if (_projectedDefinitions.Remove(id, out var definition)) RetireProjectedCharge(id, definition.Lifetime); + RemoveProjectedSample(id); + TombstoneMonitoredNode(id, UtcNow); + child.Node.Parent?.RemoveChild(child.Node); PredefinedNodes?.Remove(id); + } + } + _projectedAnchors.TryRemove(nodeId, out _); + _projectedRootLeaves.TryRemove(nodeId, out _); + RetireProjectedCharge(nodeId, anchor.Definition.Lifetime); + anchor.Node.Parent?.RemoveChild(anchor.Node); PredefinedNodes?.Remove(nodeId); + return true; + } + } + + /// + public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) + { + nodeId = null; + if (string.IsNullOrEmpty(identifier)) return false; + lock (Lock) + { + if (_disposing) return false; + var index = Array.IndexOf(RegisteredNamespaceUris, namespaceUri); + if (index < 0) return false; + nodeId = new NodeId(identifier, NamespaceIndexes[index]); + return true; + } + } + + /// + public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) + { + lock (Lock) + { + if (!_disposing && _projectedDefinitions.TryGetValue(nodeId, out definition) && definition.Lifetime.IsActive && definition.AuthorityIsCurrent()) return true; + definition = null; return false; + } + } + + private int _maxProjectedNodes = 4096; + private long _maxProjectedNodeBytes = 16 * 1024 * 1024; + private long _projectedNodeBytes; + private readonly Dictionary _projectedNodeCharges = new(); + /// Configures bounded retained projected nodes before any are installed. + public void ConfigureProjectedNodeLimits(int maxNodes, long maxBytes) + { + if (maxNodes <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxNodes)); + lock (Lock) + { + if (_projectedVariables.Count != 0 || !_projectedAnchors.IsEmpty) throw new InvalidOperationException("Projected nodes are already active."); + _maxProjectedNodes = maxNodes; _maxProjectedNodeBytes = maxBytes; + } + } + private static long ProjectedNodeCharge(ProjectedVariableDefinition definition) + { + var authorityBytes = (definition.AuthorityIsCurrent.Target as IProjectedRetainedAuthority)?.RetainedBytes ?? 0; + if (authorityBytes < 0) throw new ArgumentOutOfRangeException(nameof(definition)); + var metadata = definition.Metadata; + return checked(1024L + authorityBytes + 2L * (definition.LocalIdentifier.Length + metadata.BrowseName.Length + + metadata.NodeKind.Length + metadata.View.Subject.Length + metadata.View.Address.Identifier.Length + + metadata.View.Address.NamespaceUri.Length + metadata.View.Address.OriginClusterId.Length + metadata.View.Address.IdentifierKind.Length + + (metadata.View.MappingId?.Length ?? 0) + (metadata.StableSourceId?.Length ?? 0) + (metadata.EngineeringUnits?.Length ?? 0)) + + 4L * metadata.Dimensions.Count); + } + private int _retiredProjectedNodes; + private long _retiredProjectedBytes; + private void RetireProjectedCharge(NodeId id, ProjectedNodeLifetime lifetime) + { + if (!_projectedNodeCharges.Remove(id, out var charge)) { lifetime.ForceRetire(); return; } + _projectedNodeBytes -= charge; + Interlocked.Add(ref _retiredProjectedBytes, charge); + Interlocked.Increment(ref _retiredProjectedNodes); + lifetime.ForceRetire(() => + { + Interlocked.Add(ref _retiredProjectedBytes, -charge); + Interlocked.Decrement(ref _retiredProjectedNodes); + }); + } + private bool ReserveProjectedNode(long bytes) + { + if (bytes <= 0 || bytes > _maxProjectedNodeBytes) return false; + if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true; + foreach (var pair in _projectedDefinitions.ToArray()) + { + if (_projectedRootLeaves.ContainsKey(pair.Key) || pair.Value.AuthorityIsCurrent() || + _projectedVariables.Values.Any(child => child.Parent == pair.Key) || !pair.Value.Lifetime.TryRetire()) continue; + if (!_projectedVariables.Remove(pair.Key, out var entry)) continue; + _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); + if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes; + entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(pair.Key); + if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true; + } + foreach (var pair in _projectedAnchors.ToArray()) + { + if (pair.Value.Definition.AuthorityIsCurrent() || + _projectedVariables.Values.Any(node => node.Parent == pair.Key) || !pair.Value.Definition.Lifetime.TryRetire()) continue; + if (!_projectedAnchors.TryRemove(pair.Key, out var anchor)) continue; + if (_projectedRootLeaves.TryRemove(pair.Key, out _)) + { _projectedVariables.Remove(pair.Key); _projectedDefinitions.Remove(pair.Key); RemoveProjectedSample(pair.Key); } + if (_projectedNodeCharges.Remove(pair.Key, out var oldBytes)) _projectedNodeBytes -= oldBytes; + anchor.Node.Parent?.RemoveChild(anchor.Node); PredefinedNodes?.Remove(pair.Key); + if (_projectedVariables.Count + _projectedAnchors.Count - _projectedRootLeaves.Count + Volatile.Read(ref _retiredProjectedNodes) < _maxProjectedNodes && bytes <= _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return true; + } + return false; + } + private readonly Dictionary _projectedDefinitions = new(); + private readonly ProjectedCandidateBudget _projectedCandidateBudget = new(65_536, 16 * 1024 * 1024); + internal ProjectedCandidateBudget ProjectedCandidateBudget => _projectedCandidateBudget; + internal bool IsProjectedItem(NodeId nodeId) => IsProjectedDescendant(nodeId); + internal bool CanDispatchProjectedWrite() + { + try { return !_disposing && !_standby.RefusesMutations && (NativeAlarmAckPrimaryGate?.Invoke() ?? true); } + catch (Exception) { return false; } + } + internal bool IsProjectedBrowseNode(NodeId nodeId) => + nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3]; + internal bool CanBrowseProjectedParent(NodeId nodeId, RoleCarryingUserIdentity caller) + { + if (_projectedAnchors.ContainsKey(nodeId)) return Permits(caller, OpcUaOperation.Browse, nodeId); + var access = ProjectedDataAccess; + IProjectedDemandLease? demand = null; + try { return access is not null && access.TryAcquire(nodeId, caller, DataOperations.Browse, out demand) && demand is { IsValid: true }; } + catch (Exception) { return false; } + finally { demand?.Dispose(); } + } + internal ServiceResult? ValidateProjectedView(OperationContext context, ViewDescription? view) + { + if (view is null || ViewDescription.IsDefault(view)) return null; + try { ValidateViewDescription(SystemContext.Copy(context), view); return null; } + catch (ServiceResultException ex) { return ex.StatusCode; } + } + internal bool TryDescribeProjectedParent(NodeId nodeId, RoleCarryingUserIdentity caller, out ReferenceDescription? reference) + { + reference = null; + NodeId parent; + lock (Lock) + { + if (_projectedAnchors.TryGetValue(nodeId, out var anchor)) parent = anchor.Definition.Parent; + else if (_projectedVariables.TryGetValue(nodeId, out var entry)) parent = entry.Parent; + else return false; + } + if (IsProjectedBrowseNode(parent)) + { + if (!CanBrowseProjectedParent(parent, caller)) return false; + } + else if (!Permits(caller, OpcUaOperation.Browse, parent)) return false; + lock (Lock) + { + if (_disposing || GetManagerHandle(parent) is not NodeHandle { Node: BaseInstanceState node }) return false; + reference = new ReferenceDescription { NodeId = new ExpandedNodeId(parent), BrowseName = node.BrowseName, + DisplayName = node.DisplayName, NodeClass = node.NodeClass, ReferenceTypeId = ReferenceTypeIds.Organizes, + IsForward = false, TypeDefinition = new ExpandedNodeId(node.TypeDefinitionId) }; + return true; + } + } + internal bool TryDescribeProjectedChild(NodeId nodeId, RoleCarryingUserIdentity caller, out ReferenceDescription? reference) + { + reference = null; + var access = ProjectedDataAccess; + IProjectedDemandLease? demand = null; + try + { + if (access is null || !access.TryAcquire(nodeId, caller, DataOperations.Browse, out demand) || demand is null || !demand.IsValid) return false; + lock (Lock) + { + if (_disposing || !_projectedVariables.TryGetValue(nodeId, out var entry) || !entry.Guard() || !demand.IsValid) return false; + reference = new ReferenceDescription + { + NodeId = new ExpandedNodeId(nodeId), BrowseName = entry.Node.BrowseName, DisplayName = entry.Node.DisplayName, + NodeClass = entry.Node.NodeClass, ReferenceTypeId = ReferenceTypeIds.Organizes, IsForward = true, + TypeDefinition = new ExpandedNodeId(entry.Node.TypeDefinitionId) + }; + } + return demand.IsValid; + } + catch (Exception) { reference = null; return false; } + finally { demand?.Dispose(); } + } + internal bool RequestProjectedSnapshot(IProjectedDemandLease demand) => ProjectedDataAccess?.RequestFreshSnapshot(demand) == true; + internal void ObserveCurrentProjectedSource(ProjectedMonitoredItem item) + { + lock (Lock) + if (_projectedSamples.TryGetValue(item.ProjectedNodeId, out var sample)) item.ObserveSample(sample); + } + internal bool IsProjectedDefinitionCurrent(NodeId nodeId, ProjectedVariableDefinition definition) + { + lock (Lock) return !_disposing && _projectedDefinitions.TryGetValue(nodeId, out var current) && + ReferenceEquals(current.Lifetime, definition.Lifetime) && current.Lifetime.IsActive && current.AuthorityIsCurrent(); + } + internal bool TryAcquireProjectedItem(ServerSystemContext context, NodeId nodeId, double publishingInterval, + out IProjectedDemandLease? demand, out ProjectedValueWrite? sample, out ProjectedVariableDefinition? definition) + { + demand = null; sample = null; definition = null; + var identity = IdentityOf(context); + var access = ProjectedDataAccess; + var accepted = false; + try + { + if (identity is null || access is null || !TryResolve(nodeId, out definition) || definition is null || + !access.TryAcquire(nodeId, identity, DataOperations.Subscribe, out demand) || demand is null || !demand.IsValid || + !access.StartSubscription(demand, TimeSpan.FromMilliseconds(Math.Max(0, publishingInterval)))) return false; + lock (Lock) _projectedSamples.TryGetValue(nodeId, out sample); + if (!demand.IsValid || !IsProjectedDefinitionCurrent(nodeId, definition)) return false; + accepted = true; + return true; + } + finally + { + if (!accepted) { demand?.Dispose(); demand = null; } + } + } + + private readonly Dictionary _projectedSamples = new(); + private readonly Dictionary _projectedSampleCharges = new(); + private long _projectedSampleBytes; + private void RemoveProjectedSample(NodeId id) + { + _projectedSamples.Remove(id); + if (_projectedSampleCharges.Remove(id, out var bytes)) _projectedSampleBytes -= bytes; + } + private static long EstimateProjectedSample(object? value) + { + checked + { + long bytes = 256; + if (value is string text) bytes += 2L * text.Length; + else if (value is Array array) + { + if (array.Rank != 1 || array.Length > 65_536) throw new ArgumentException("Unsupported projected array."); + bytes += 64L * array.Length; + if (array is string[] strings) foreach (var item in strings) bytes += 2L * (item?.Length ?? 0); + } + return bytes; + } + } + + bool IProjectedValueSink.TryPublish(IReadOnlyList values) + { + ArgumentNullException.ThrowIfNull(values); + if (values.Count == 0) return false; + var valid = true; + long sampleDelta = 0; + var snapshotRequests = new List(); + lock (Lock) + { + if (_disposing) return false; + var targets = new List<(NodeId Id, BaseDataVariableState Node, ProjectedValueWrite Value, DataMetadata Metadata, long Charge)>(values.Count); + var seen = new HashSet(); + foreach (var value in values) + { + if (value is null || value.Proof is null || value.Realm is not (DataRealm.Raw or DataRealm.Uns)) { valid = false; continue; } + var id = new NodeId(value.LocalIdentifier, value.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]); + if (!seen.Add(id) || !_projectedVariables.TryGetValue(id, out var target) || target.Generation != value.ProjectionGeneration || + !value.Proof.IsValid || !target.Guard() || target.Node is not BaseDataVariableState || value.Serving.ServingGeneration <= 0 || + (target.Metadata.Serving is { } expected && expected != value.Serving) || !ProjectedValueMatches(target.Metadata, value.Snapshot.Value)) + { valid = false; continue; } + try + { + value.OriginAgeBounds.Advance(value.Proof.Clock.GetElapsedTime(value.ReceivedTimestamp, value.Proof.Clock.GetTimestamp())); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { valid = false; continue; } + try + { + var charge = EstimateProjectedSample(value.Snapshot.Value); + sampleDelta = checked(sampleDelta + charge - _projectedSampleCharges.GetValueOrDefault(id)); + targets.Add((id, (BaseDataVariableState)target.Node, value, target.Metadata, charge)); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { valid = false; } + } + if (sampleDelta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) valid = false; + if (valid && targets.Any(target => !target.Value.Proof.IsValid)) valid = false; + if (!valid || targets.Count != values.Count) + { + // Retire only matching generations: a late old owner cannot invalidate a new projection. + foreach (var value in values) + { + if (value is null || value.Realm is not (DataRealm.Raw or DataRealm.Uns)) continue; + var id = new NodeId(value.LocalIdentifier, value.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]); + if (_projectedVariables.TryGetValue(id, out var target) && target.Generation == value.ProjectionGeneration && target.Node is BaseDataVariableState variable) + { + RemoveProjectedSample(id); + variable.Value = Variant.Null; + variable.StatusCode = StatusCodes.BadWaitingForInitialData; + variable.ClearChangeMasks(SystemContext, false); + } + } + } + else + { + foreach (var target in targets) + { + var source = target.Value.Snapshot.Value; + var detached = target.Value with { Snapshot = target.Value.Snapshot with { Value = source is Array array ? array.Clone() : source } }; + foreach (var item in _liveItems.Keys.OfType()) + if (item.ProjectedNodeId == target.Id && item.ObserveSample(detached)) snapshotRequests.Add(item); + target.Node.Value = SdkValueBoundary.FromClr(detached.Snapshot.Value, + target.Metadata.ValueKind == DataValueKind.Array && target.Metadata.ArrayElementKind == DataValueKind.UInt8); + target.Node.StatusCode = detached.Snapshot.StatusCode; + target.Node.Timestamp = detached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue; + RemoveProjectedSample(target.Id); + _projectedSamples[target.Id] = detached; _projectedSampleCharges[target.Id] = target.Charge; _projectedSampleBytes += target.Charge; + target.Node.ClearChangeMasks(SystemContext, false); + } + } + } + if (!valid) foreach (var value in values) value?.Proof?.Invalidate(); + foreach (var item in snapshotRequests.Distinct()) item.RequestBaseline(); + return valid; + } + + private static bool ProjectedValueMatches(DataMetadata metadata, object? value) + { + if (value is null) return true; + var kind = metadata.ValueKind; + if (kind == DataValueKind.Array) + { + if (value is not Array array || array.Rank != 1 || metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || + (metadata.Dimensions[0] != 0 && array.Length != metadata.Dimensions[0])) return false; + kind = metadata.ArrayElementKind ?? DataValueKind.Unspecified; + var elementType = array.GetType().GetElementType(); + var expectedType = kind switch + { + DataValueKind.Boolean => typeof(bool), DataValueKind.Int8 => typeof(sbyte), DataValueKind.UInt8 => typeof(byte), + DataValueKind.Int16 => typeof(short), DataValueKind.UInt16 => typeof(ushort), DataValueKind.Int32 => typeof(int), + DataValueKind.UInt32 => typeof(uint), DataValueKind.Int64 => typeof(long), DataValueKind.UInt64 => typeof(ulong), + DataValueKind.Float => typeof(float), DataValueKind.Double => typeof(double), DataValueKind.String => typeof(string), + DataValueKind.Timestamp => typeof(DateTime), _ => null + }; + if (elementType != expectedType) return false; + foreach (var element in array) if (!ProjectedScalarMatches(kind, element)) return false; + return true; + } + return ProjectedScalarMatches(kind, value); + } + private static bool ProjectedScalarMatches(DataValueKind kind, object? value) => value is not null && kind switch + { + DataValueKind.Boolean => value is bool, DataValueKind.Int8 => value is sbyte, DataValueKind.UInt8 => value is byte, + DataValueKind.Int16 => value is short, DataValueKind.UInt16 => value is ushort, DataValueKind.Int32 => value is int, + DataValueKind.UInt32 => value is uint, DataValueKind.Int64 => value is long, DataValueKind.UInt64 => value is ulong, + DataValueKind.Float => value is float, DataValueKind.Double => value is double, DataValueKind.String => value is string, + DataValueKind.Timestamp => value is DateTime or DateTimeOffset, _ => false + }; + + private readonly Dictionary Guard)> _projectedVariables = new(); + + bool IProjectedNamespacePageSink.TryApply(NodeId parent, IReadOnlyList nodes, Func commit) + { + ArgumentNullException.ThrowIfNull(nodes); + ArgumentNullException.ThrowIfNull(commit); + if (nodes.Count > 4096) return false; + lock (Lock) + { + if (_disposing) return false; + var added = new List(); + var renewals = new List<(NodeId Id, ProjectedVariableDefinition Definition, long Charge)>(); + var seen = new HashSet(); + var applied = false; + try + { + foreach (var definition in nodes) + { + if (definition is null || definition.Parent != parent || definition.Realm is not (DataRealm.Raw or DataRealm.Uns)) return false; + var id = new NodeId(definition.LocalIdentifier, definition.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]); + if (!seen.Add(id)) return false; + if (_projectedVariables.TryGetValue(id, out var existing)) + { + if (!_projectedDefinitions.TryGetValue(id, out var old) || existing.Parent != parent || + existing.Generation != definition.ProjectionGeneration || !definition.AuthorityIsCurrent() || + old.Metadata.View != definition.Metadata.View || old.Metadata.BrowseName != definition.Metadata.BrowseName || + old.Metadata.NodeKind != definition.Metadata.NodeKind || old.Metadata.ValueKind != definition.Metadata.ValueKind || + old.Metadata.ValueRank != definition.Metadata.ValueRank || old.Metadata.ArrayElementKind != definition.Metadata.ArrayElementKind || + !old.Metadata.Dimensions.SequenceEqual(definition.Metadata.Dimensions)) return false; + var renewed = ReferenceEquals(definition.Lifetime, old.Lifetime) ? definition : definition with { Lifetime = old.Lifetime }; + renewals.Add((id, renewed, checked(ProjectedNodeCharge(renewed) + + (_projectedRootLeaves.ContainsKey(id) ? ProjectedAnchorCharge(_projectedAnchors[id].Definition) : 0)))); + continue; + } + if (!TryEnsureProjectedVariable(definition, out var created) || created != id) return false; + added.Add(id); + } + long renewalDelta = 0; + foreach (var renewal in renewals) renewalDelta = checked(renewalDelta + renewal.Charge - _projectedNodeCharges[renewal.Id]); + if (renewalDelta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes || + nodes.Any(node => !node.AuthorityIsCurrent()) || !commit() || nodes.Any(node => !node.AuthorityIsCurrent())) return false; + foreach (var renewal in renewals) + { + var previous = _projectedVariables[renewal.Id]; + _projectedVariables[renewal.Id] = (previous.Parent, previous.Generation, renewal.Definition.Metadata, + previous.Node, renewal.Definition.AuthorityIsCurrent); + _projectedDefinitions[renewal.Id] = renewal.Definition; + _projectedNodeBytes += renewal.Charge - _projectedNodeCharges[renewal.Id]; + _projectedNodeCharges[renewal.Id] = renewal.Charge; + } + applied = true; + return true; + } + finally + { + if (!applied) + foreach (var id in added) + { + if (!_projectedVariables.Remove(id, out var entry)) continue; + RemoveProjectedSample(id); + _projectedDefinitions.Remove(id); + if (_projectedNodeCharges.Remove(id, out var charge)) _projectedNodeBytes -= charge; + entry.Node.Parent?.RemoveChild(entry.Node); + PredefinedNodes?.Remove(id); + } + } + } + } + + + bool IProjectedNamespacePageSink.TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func commit) + { + ArgumentNullException.ThrowIfNull(rootDefinition); ArgumentNullException.ThrowIfNull(commit); + lock (Lock) + { + if (_disposing || !_projectedAnchors.TryGetValue(anchorId, out var anchor) || + (rootDefinition.Parent != anchor.Definition.Parent && rootDefinition.Parent != anchorId) || rootDefinition.LocalIdentifier != anchor.Definition.LocalIdentifier || + rootDefinition.Realm != anchor.Definition.Realm || rootDefinition.ProjectionGeneration <= 0 || + !ProjectedDataIds.TryDecodeIdentifier(rootDefinition.LocalIdentifier, out var mapping, out var origin) || + mapping != anchor.Definition.MappingId || rootDefinition.Metadata.View.MappingId != mapping || + rootDefinition.Metadata.View.Address != origin || rootDefinition.Metadata.View.Realm != rootDefinition.Realm || + rootDefinition.Metadata.NodeKind is not ("Variable" or "Tag") || + !anchor.Definition.AuthorityIsCurrent() || !rootDefinition.AuthorityIsCurrent() || + !_projectedNodeCharges.TryGetValue(anchorId, out var anchorCharge) || + GetManagerHandle(anchor.Definition.Parent) is not NodeHandle { Node: FolderState parent }) return false; + var installed = rootDefinition with { Parent = anchor.Definition.Parent, Lifetime = anchor.Definition.Lifetime }; + if (anchor.Node is BaseDataVariableState existingNode) + { + if (!_projectedRootLeaves.ContainsKey(anchorId) || !_projectedDefinitions.TryGetValue(anchorId, out var old) || + !_projectedVariables.TryGetValue(anchorId, out var existing) || existing.Generation != installed.ProjectionGeneration || + old.Metadata.View != installed.Metadata.View || old.Metadata.BrowseName != installed.Metadata.BrowseName || + old.Metadata.NodeKind != installed.Metadata.NodeKind || old.Metadata.ValueKind != installed.Metadata.ValueKind || + old.Metadata.ValueRank != installed.Metadata.ValueRank || old.Metadata.ArrayElementKind != installed.Metadata.ArrayElementKind || + !old.Metadata.Dimensions.SequenceEqual(installed.Metadata.Dimensions)) return false; + var renewedCharge = checked(ProjectedAnchorCharge(anchor.Definition) + ProjectedNodeCharge(installed)); + var delta = renewedCharge - anchorCharge; + if (delta > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes || + !installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false; + _projectedVariables[anchorId] = (existing.Parent, existing.Generation, installed.Metadata, existingNode, installed.AuthorityIsCurrent); + _projectedDefinitions[anchorId] = installed; + _projectedNodeCharges[anchorId] = renewedCharge; + _projectedNodeBytes += delta; + return true; + } + if (anchor.Node is not FolderState folder) return false; + var children = new List(); folder.GetChildren(SystemContext, children); + if (children.Count != 0) return false; + var isArray = rootDefinition.Metadata.ValueKind == DataValueKind.Array; + if (isArray ? rootDefinition.Metadata.ValueRank != 1 || rootDefinition.Metadata.Dimensions.Count != 1 || rootDefinition.Metadata.Dimensions[0] < 0 : + rootDefinition.Metadata.ValueRank != -1 || rootDefinition.Metadata.Dimensions.Count != 0) return false; + var kind = isArray ? rootDefinition.Metadata.ArrayElementKind ?? DataValueKind.Unspecified : rootDefinition.Metadata.ValueKind; + var typeName = kind switch + { + DataValueKind.Boolean => "Boolean", DataValueKind.Int8 => "SByte", DataValueKind.UInt8 => "Byte", + DataValueKind.Int16 => "Int16", DataValueKind.UInt16 => "UInt16", DataValueKind.Int32 => "Int32", + DataValueKind.UInt32 => "UInt32", DataValueKind.Int64 => "Int64", DataValueKind.UInt64 => "UInt64", + DataValueKind.Float => "Float", DataValueKind.Double => "Double", DataValueKind.String => "String", + DataValueKind.Timestamp => "DateTime", _ => null + }; + if (typeName is null) return false; + var charge = ProjectedNodeCharge(rootDefinition); + if (charge > _maxProjectedNodeBytes - _projectedNodeBytes - Volatile.Read(ref _retiredProjectedBytes) - _projectedSampleBytes) return false; + var variable = new BaseDataVariableState(parent) + { + NodeId = anchorId, BrowseName = new QualifiedName(anchor.Definition.BrowseName, anchorId.NamespaceIndex), + DisplayName = new LocalizedText(anchor.Definition.BrowseName), TypeDefinitionId = VariableTypeIds.BaseDataVariableType, + ReferenceTypeId = ReferenceTypeIds.Organizes, DataType = ResolveBuiltInDataType(typeName), + ValueRank = isArray ? ValueRanks.OneDimension : ValueRanks.Scalar, + ArrayDimensions = isArray ? (ArrayOf)[checked((uint)rootDefinition.Metadata.Dimensions[0])] : default, + AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead, + Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue + }; + var accepted = false; + var charged = false; + try + { + parent.RemoveChild(folder); PredefinedNodes?.Remove(anchorId); + parent.AddChild(variable); AddPredefinedNode(SystemContext, variable); + _projectedAnchors[anchorId] = (anchor.Definition, variable); + _projectedRootLeaves[anchorId] = 0; + _projectedVariables.Add(anchorId, (anchor.Definition.Parent, installed.ProjectionGeneration, installed.Metadata, variable, installed.AuthorityIsCurrent)); + _projectedDefinitions.Add(anchorId, installed); + _projectedNodeCharges[anchorId] = anchorCharge + charge; _projectedNodeBytes += charge; charged = true; + if (!installed.AuthorityIsCurrent() || !commit() || !installed.AuthorityIsCurrent()) return false; + accepted = true; return true; + } + finally + { + if (!accepted) + { + _projectedVariables.Remove(anchorId); _projectedDefinitions.Remove(anchorId); _projectedRootLeaves.TryRemove(anchorId, out _); + _projectedNodeCharges[anchorId] = anchorCharge; + if (charged) _projectedNodeBytes -= charge; + variable.Parent?.RemoveChild(variable); PredefinedNodes?.Remove(anchorId); + parent.AddChild(folder); AddPredefinedNode(SystemContext, folder); _projectedAnchors[anchorId] = anchor; + } + } + } + } + + bool IProjectedNamespacePageSink.TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) + { + lock (Lock) + { + if (_disposing || _projectedRootLeaves.ContainsKey(nodeId) || !_projectedDefinitions.TryGetValue(nodeId, out var current) || !ReferenceEquals(current, expected) || + _projectedVariables.Values.Any(child => child.Parent == nodeId) || !_projectedVariables.Remove(nodeId, out var entry)) return false; + _projectedDefinitions.Remove(nodeId); RemoveProjectedSample(nodeId); RetireProjectedCharge(nodeId, current.Lifetime); + TombstoneMonitoredNode(nodeId, UtcNow); + entry.Node.Parent?.RemoveChild(entry.Node); PredefinedNodes?.Remove(nodeId); + return true; + } + } + + /// Materializes one checked scalar under its exact existing parent. Access stays denied until its live proof is wired. + internal bool TryEnsureProjectedVariable(ProjectedVariableDefinition definition, out NodeId? nodeId) + { + nodeId = null; + if (definition is null || definition.Metadata is null || definition.AuthorityIsCurrent is null || + definition.ProjectionGeneration <= 0 || !definition.Lifetime.IsActive || + !ProjectedDataIds.TryDecodeIdentifier(definition.LocalIdentifier, out var mapping, out var origin) || + definition.Metadata.View.MappingId != mapping || definition.Metadata.View.Address != origin || + definition.Metadata.View.Realm != definition.Realm) return false; + var isFolder = definition.Metadata.NodeKind == "Folder"; + var isArray = definition.Metadata.ValueKind == DataValueKind.Array; + if (isFolder && (definition.Metadata.ValueKind != DataValueKind.Null || definition.Metadata.ValueRank != -1 || definition.Metadata.Dimensions.Count != 0)) return false; + if (!isFolder && definition.Metadata.NodeKind is not ("Variable" or "Tag")) return false; + if (!isFolder && (isArray ? definition.Metadata.ValueRank != 1 || definition.Metadata.Dimensions.Count != 1 || definition.Metadata.Dimensions[0] < 0 : + definition.Metadata.ValueRank != -1 || definition.Metadata.Dimensions.Count != 0)) return false; + var valueKind = isArray ? definition.Metadata.ArrayElementKind ?? DataValueKind.Unspecified : definition.Metadata.ValueKind; + var typeName = valueKind switch + { + DataValueKind.Boolean => "Boolean", DataValueKind.Int8 => "SByte", DataValueKind.UInt8 => "Byte", + DataValueKind.Int16 => "Int16", DataValueKind.UInt16 => "UInt16", DataValueKind.Int32 => "Int32", + DataValueKind.UInt32 => "UInt32", DataValueKind.Int64 => "Int64", DataValueKind.UInt64 => "UInt64", + DataValueKind.Float => "Float", DataValueKind.Double => "Double", DataValueKind.String => "String", + DataValueKind.Timestamp => "DateTime", _ => null + }; + if ((!isFolder && typeName is null) || definition.Realm is not (DataRealm.Raw or DataRealm.Uns)) return false; + lock (Lock) + { + if (_disposing || !definition.AuthorityIsCurrent()) return false; + if (GetManagerHandle(definition.Parent) is not NodeHandle { Node: FolderState parent } || parent.NodeId != definition.Parent) return false; + var index = definition.Realm == DataRealm.Raw ? NamespaceIndexes[2] : NamespaceIndexes[3]; + var candidate = new NodeId(definition.LocalIdentifier, index); + if (_projectedVariables.TryGetValue(candidate, out var existing)) + { + if (existing.Parent != definition.Parent || existing.Generation != definition.ProjectionGeneration || existing.Metadata != definition.Metadata) return false; + nodeId = candidate; return true; + } + if (GetManagerHandle(candidate) is not null) return false; + var charge = ProjectedNodeCharge(definition); + if (!ReserveProjectedNode(charge)) return false; + BaseInstanceState node = isFolder + ? new FolderState(parent) { NodeId = candidate, BrowseName = new QualifiedName(definition.Metadata.BrowseName, index), + DisplayName = new LocalizedText(definition.Metadata.BrowseName), TypeDefinitionId = ObjectTypeIds.FolderType, + ReferenceTypeId = ReferenceTypeIds.Organizes, EventNotifier = EventNotifiers.None } + : new BaseDataVariableState(parent) { NodeId = candidate, BrowseName = new QualifiedName(definition.Metadata.BrowseName, index), + DisplayName = new LocalizedText(definition.Metadata.BrowseName), TypeDefinitionId = VariableTypeIds.BaseDataVariableType, + ReferenceTypeId = ReferenceTypeIds.Organizes, DataType = ResolveBuiltInDataType(typeName!), + ValueRank = isArray ? ValueRanks.OneDimension : ValueRanks.Scalar, + ArrayDimensions = isArray ? (ArrayOf)[checked((uint)definition.Metadata.Dimensions[0])] : default, + AccessLevel = AccessLevels.CurrentRead, UserAccessLevel = AccessLevels.CurrentRead, + Value = Variant.Null, StatusCode = StatusCodes.BadWaitingForInitialData, Timestamp = DateTime.MinValue }; + if (!definition.AuthorityIsCurrent()) return false; + parent.AddChild(node); AddPredefinedNode(SystemContext, node); + _projectedVariables.Add(candidate, (definition.Parent, definition.ProjectionGeneration, definition.Metadata, node, definition.AuthorityIsCurrent)); + _projectedDefinitions.Add(candidate, definition); + _projectedNodeCharges.Add(candidate, charge); _projectedNodeBytes += charge; + nodeId = candidate; return true; + } + } + /// Records under in the P2 subtree index. MUST be /// called under Lock. Idempotent for the same pair; a child re-indexed under another parent moves. private void IndexChild(RealmKey parent, RealmKey child) @@ -4738,8 +5420,17 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 /// EnsureFolder + WriteValue on the next pass. public void RebuildAddressSpace() { + IProjectedSamplePublicationProof[] retiredProofs; lock (Lock) { + retiredProofs = _projectedSamples.Values.Select(sample => sample.Proof).Distinct().ToArray(); + foreach (var item in _liveItems.Keys.OfType()) item.Retire(); + foreach (var id in _projectedVariables.Keys) PredefinedNodes?.Remove(id); + foreach (var id in _projectedAnchors.Keys) PredefinedNodes?.Remove(id); + foreach (var (id, definition) in _projectedDefinitions) RetireProjectedCharge(id, definition.Lifetime); + foreach (var (id, anchor) in _projectedAnchors) RetireProjectedCharge(id, anchor.Definition.Lifetime); + _projectedVariables.Clear(); _projectedDefinitions.Clear(); _projectedSamples.Clear(); _projectedAnchors.Clear(); _projectedRootLeaves.Clear(); + _projectedNodeCharges.Clear(); _projectedSampleCharges.Clear(); _projectedSampleBytes = 0; Interlocked.Increment(ref _historyContinuationEpoch); // Review 01 L2 — every monitored item on a node this rebuild discards is told and forgotten BEFORE // the nodes go, so a later create on the same NodeId binds to the re-created node (see @@ -4819,6 +5510,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 _eventNotifierSources.Clear(); ReconcileAllEventsMonitoring(); } + foreach (var proof in retiredProofs) proof.Invalidate(); } // Reports ONE condition event for each native condition whose off-normal state the rebuild @@ -5121,7 +5813,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 /// when this manager owns the node's namespace. private bool OwnsNamespace(NodeId? nodeId) => nodeId is { } id - && (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1]); + && (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1] || + id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3]); /// Pulls the ACL identity off an SDK operation context. /// The SDK context carrying the session identity. @@ -5141,10 +5834,22 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 /// The operation being attempted. /// The target node. /// when permitted, or when the node is not ours to gate. - private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) => - !OwnsNamespace(nodeId) - || _authorizer?.AuthorizeIfRequired(identity, operation, nodeId, RealmOf(nodeId)) is null - && (_authorizer is not null || _mappedSubjectResolver is null); + private bool Permits(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId) + { + if (!OwnsNamespace(nodeId)) return true; + var realm = RealmOf(nodeId); + if (_projectedAnchors.TryGetValue(nodeId, out var anchor) && operation == OpcUaOperation.Browse) + { + if (!anchor.Definition.AuthorityIsCurrent()) return false; + var localId = new NodeId(anchor.Definition.LocalSubject, NamespaceIndexForRealm(realm)); + return _authorizer?.AuthorizeIfRequired(identity, operation, localId, realm) is null && + (_authorizer is not null || _mappedSubjectResolver is null); + } + if (nodeId.NamespaceIndex == NamespaceIndexes[2] || nodeId.NamespaceIndex == NamespaceIndexes[3]) + return _authorizer is { } mappedAuthorizer && mappedAuthorizer.TryAuthorizeMapped(identity, operation, nodeId, realm, out var veto) && veto is null; + return _authorizer?.AuthorizeIfRequired(identity, operation, nodeId, realm) is null && + (_authorizer is not null || _mappedSubjectResolver is null); + } /// Guard against a corrupt (cyclic) parent chain in . private const int MaxUnsAncestry = 64; @@ -5329,6 +6034,53 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 var identity = IdentityOf(context); var denied = 0; + for (var ii = 0; ii < nodesToRead.Count; ii++) + { + var projected = nodesToRead[ii]; + if (projected.Processed || projected.AttributeId != Attributes.Value || !IsProjectedDescendant(projected.NodeId)) continue; + projected.Processed = true; + var access = ProjectedDataAccess; + IProjectedDemandLease? demand = null; + try + { + if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) || + demand is null || !demand.IsValid) + { + errors[ii] = StatusCodes.BadUserAccessDenied; + values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); + continue; + } + ProjectedValueWrite? cached; + var byteArray = false; + lock (Lock) + { + _projectedSamples.TryGetValue(projected.NodeId, out cached); + if (_projectedVariables.TryGetValue(projected.NodeId, out var mapped)) + byteArray = mapped.Metadata.ValueKind == DataValueKind.Array && mapped.Metadata.ArrayElementKind == DataValueKind.UInt8; + } + if (cached is not null && cached.Proof.IsValid && demand.IsValid && cached.Serving == demand.Serving && + cached.ProjectionGeneration == demand.ProjectionGeneration && maxAge > 0 && + cached.OriginAgeBounds.Advance(cached.Proof.Clock.GetElapsedTime(cached.ReceivedTimestamp, + cached.Proof.Clock.GetTimestamp())).IsFresh(TimeSpan.FromMilliseconds(Math.Min(maxAge, TimeSpan.MaxValue.TotalMilliseconds)))) + { + var value = new DataValue(SdkValueBoundary.FromClr(cached.Snapshot.Value, byteArray), cached.Snapshot.StatusCode, + (DateTimeUtc)(cached.Snapshot.SourceTimestampUtc ?? DateTime.MinValue), + (DateTimeUtc)(cached.Snapshot.ServerTimestampUtc ?? DateTime.MinValue)); + if (cached.Proof.IsValid && demand.IsValid) { values[ii] = value; continue; } + } + var started = access.Clock.GetTimestamp(); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + if (access.ScheduleRead(demand, budget, started)) demand = null; // ownership transfers only on admission + values[ii] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData); + } + catch (Exception) + { + errors[ii] = StatusCodes.BadUserAccessDenied; + values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); + } + finally { demand?.Dispose(); } + } + for (var ii = 0; ii < nodesToRead.Count; ii++) { var nodeToRead = nodesToRead[ii]; @@ -5368,6 +6120,33 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 ref ContinuationPoint continuationPoint, IList references) { + // A local mapping anchor remains visible in its parent; only browsing its remote + // children consults this nonblocking readiness snapshot. + var projectedParent = (continuationPoint?.NodeToBrowse as NodeHandle)?.NodeId; + if (projectedParent is not null && continuationPoint is not null && ProjectedBrowseAccess is { } browseAccess) + { + if (SecurityFilteringActive && !Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value)) + throw new ServiceResultException(StatusCodes.BadUserAccessDenied); + var result = browseAccess.GetOrSchedule(new(projectedParent.Value, IdentityOf(context), continuationPoint, ProjectedBrowseClock.GetTimestamp())); + if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Pending) + throw new ServiceResultException(StatusCodes.BadWaitingForInitialData); + if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Unavailable) + throw new ServiceResultException(StatusCodes.BadNoCommunication); + if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.InvalidContinuation) + throw new ServiceResultException(StatusCodes.BadContinuationPointInvalid); + } + if (projectedParent is not null && ProjectedBrowseReadiness is { } readiness) + { + if (SecurityFilteringActive && !Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value)) + throw new ServiceResultException(StatusCodes.BadUserAccessDenied); + var status = readiness(projectedParent.Value); + if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Pending) + throw new ServiceResultException(StatusCodes.BadWaitingForInitialData); + if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Unavailable) + throw new ServiceResultException(StatusCodes.BadNoCommunication); + if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.InvalidContinuation) + throw new ServiceResultException(StatusCodes.BadContinuationPointInvalid); + } if (!SecurityFilteringActive) { base.Browse(context, ref continuationPoint!, references); @@ -5498,6 +6277,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 var item = itemsToCreate[ii]; var target = item.ItemToMonitor?.NodeId; if (item.Processed || !OwnsNamespace(target)) continue; + if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is not null && + item.ItemToMonitor?.AttributeId == Attributes.Value) continue; if (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue; item.Processed = true; @@ -5614,6 +6395,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 NodeHandle handle) { if (SecurityFilteringActive && monitoringMode != MonitoringMode.Disabled + && !(monitoredItem is ProjectedMonitoredItem projected && projected.IsCurrent) && !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, handle.NodeId)) { return StatusCodes.BadUserAccessDenied; @@ -5646,6 +6428,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 protected override void OnMonitoredItemDeleted( ServerSystemContext context, NodeHandle handle, ISampledDataChangeMonitoredItem monitoredItem) { + if (monitoredItem is ProjectedMonitoredItem projected) projected.Retire(); if (_liveItems.TryRemove(monitoredItem, out var tracked) && tracked.Suppressed) Interlocked.Decrement(ref _suppressedItems); base.OnMonitoredItemDeleted(context, handle, monitoredItem); } @@ -5730,6 +6513,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 { foreach (var item in dataItems.Values.ToArray()) { + if (item is ProjectedMonitoredItem projected) projected.Retire(); TellNodeRemoved(item, now); if (item is ISampledDataChangeMonitoredItem sampled) _liveItems.TryRemove(sampled, out _); ReleaseComponentCacheReference(item); @@ -7456,8 +8240,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 if (item is not IMonitoredItem live) continue; var nodeId = tracked.Handle.NodeId; - var permitted = IsSubscriptionStillPermitted( - live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts); + var permitted = item is ProjectedMonitoredItem projectedItem + ? projectedItem.HasCurrentDemand + : IsSubscriptionStillPermitted(live.EffectiveIdentity as RoleCarryingUserIdentity, nodeId, verdicts); if (permitted) { @@ -7470,7 +8255,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 bool reattached; lock (Lock) { - reattached = ResolveNodeState(MapKey(nodeId)) is { } liveNode + reattached = (item is ProjectedMonitoredItem + ? (GetManagerHandle(nodeId) as NodeHandle)?.Node + : ResolveNodeState(MapKey(nodeId))) is { } liveNode && ReferenceEquals(liveNode, tracked.Handle.Node); if (reattached) tracked.Handle.MonitoredNode?.Add(item); else _liveItems.TryRemove(item, out _); @@ -7479,6 +8266,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3 Interlocked.Decrement(ref _suppressedItems); if (!reattached) { + if (item is ProjectedMonitoredItem projected) projected.Retire(); TellNodeRemoved(item, now); continue; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs index 86bd5837f..4bdd72be5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaSdkServer.cs @@ -6,6 +6,9 @@ using Opc.Ua.Server.Hosting; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using DataBudget = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataBudget; +using DataOperations = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations; +using DataWriteState = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataWriteState; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; @@ -373,6 +376,363 @@ public sealed class OtOpcUaSdkServer : StandardServer return ids; } + /// Dispatch mapped writes asynchronously without mutating the SDK value optimistically. + public override async ValueTask WriteAsync(SecureChannelContext secureChannelContext, RequestHeader? requestHeader, + ArrayOf nodesToWrite, RequestLifetime requestLifetime) + { + var manager = _otOpcUaNodeManager; + var containsProjected = false; + if (manager is not null) + for (var i = 0; i < nodesToWrite.Count; i++) + if (manager.IsProjectedItem(nodesToWrite[i].NodeId)) { containsProjected = true; break; } + if (manager is null || !containsProjected) + return await base.WriteAsync(secureChannelContext, requestHeader, nodesToWrite, requestLifetime).ConfigureAwait(false); + var access = manager.ProjectedDataAccess; + var started = access?.Clock.GetTimestamp() ?? 0; + using var context = await ValidateRequestAsync(secureChannelContext, requestHeader, RequestType.Write, requestLifetime).ConfigureAwait(false); + try + { + ValidateOperationLimits(nodesToWrite, ServerInternal.ServerObject?.ServerCapabilities?.OperationLimits?.MaxNodesPerWrite); + var result = new StatusCode[nodesToWrite.Count]; + var legacy = new List(); + var legacyIndexes = new List(); + var caller = context.UserIdentity as RoleCarryingUserIdentity; + for (var i = 0; i < nodesToWrite.Count; i++) + { + var item = nodesToWrite[i]; + if (!manager.IsProjectedItem(item.NodeId)) { legacy.Add(item); legacyIndexes.Add(i); continue; } + if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; } + if (item.AttributeId != Attributes.Value || !string.IsNullOrEmpty(item.IndexRange) || + item.Value.StatusCode.Code != StatusCodes.Good.Code || item.Value.SourceTimestamp != DateTimeUtc.MinValue || + item.Value.ServerTimestamp != DateTimeUtc.MinValue) + { result[i] = StatusCodes.BadWriteNotSupported; continue; } + IProjectedDemandLease? demand = null; + try + { + if (caller is null || access is null || !access.TryAcquire(item.NodeId, caller, DataOperations.Write, out demand) || + demand is null || !demand.IsValid) + { result[i] = StatusCodes.BadUserAccessDenied; continue; } + if (!manager.CanDispatchProjectedWrite()) { result[i] = StatusCodes.BadInvalidState; continue; } + var milliseconds = requestHeader is { TimeoutHint: > 0 } ? Math.Min(requestHeader.TimeoutHint, 5000u) : 5000u; + var budget = new DataBudget(TimeSpan.FromMilliseconds(milliseconds), 1, 4 * 1024 * 1024); + var outcome = await access.WriteAsync(demand, SdkValueBoundary.ToClr(item.Value.WrappedValue), budget, started, + requestLifetime.CancellationToken).ConfigureAwait(false); + result[i] = outcome.State switch + { + DataWriteState.DriverConfirmedSuccess when demand.IsValid => StatusCodes.Good, + DataWriteState.AcceptedUnconfirmed or DataWriteState.OutcomeUnknown or DataWriteState.DriverConfirmedSuccess => StatusCodes.UncertainLastUsableValue, + _ => StatusCode.IsBad(outcome.StatusCode) ? outcome.StatusCode : StatusCodes.BadNotWritable + }; + } + catch (OperationCanceledException) { result[i] = StatusCodes.UncertainLastUsableValue; } + catch (Exception) { result[i] = StatusCodes.UncertainLastUsableValue; } + finally { demand?.Dispose(); } + } + if (legacy.Count > 0) + { + var (statuses, _) = await ServerInternal.NodeManager.WriteAsync(context, legacy.ToArray(), requestLifetime.CancellationToken).ConfigureAwait(false); + for (var i = 0; i < legacyIndexes.Count; i++) result[legacyIndexes[i]] = statuses[i]; + } + return new WriteResponse { Results = result, ResponseHeader = CreateResponse(requestHeader, context.StringTable) }; + } + finally { OnRequestComplete(context); } + } + + private static readonly byte[] ProjectedCursorPrefix = [0x4f, 0x54, 0x50, 0x43, 0x55, 0x41, 0x50, 0x31]; + private readonly object _projectedBrowseLock = new(); + private readonly Dictionary _projectedBrowseCursors = new(); + private int _maxProjectedBrowseCursors = 256; + private long _maxProjectedBrowseBytes = 16 * 1024 * 1024; + private int _projectedBrowseRetained; + private long _projectedBrowseRetainedBytes; + /// Sets aggregate cursor count and retained-byte limits before cursors are created. + public void SetProjectedBrowseLimits(int maxCursors, long maxBytes) + { + if (maxCursors <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxCursors)); + lock (_projectedBrowseLock) + { + if (_projectedBrowseRetained != 0) throw new InvalidOperationException("Projected browse cursors are active."); + _maxProjectedBrowseCursors = maxCursors; _maxProjectedBrowseBytes = maxBytes; + } + } + private const int MaxProjectedBrowseChildren = 4096; + + private sealed record ProjectedBrowseFilter(BrowseDirection Direction, NodeId ReferenceType, bool IncludeSubtypes, + uint NodeClassMask, uint ResultMask, ViewDescription? View); + private sealed class ProjectedBrowseCursor(NodeId parent, NodeId session, DataCallerIdentity caller, + ProjectedBrowsePage page, int index, uint maximum, long expires, ProjectedBrowseFilter filter) + { + public NodeId Parent = parent; + public NodeId Session = session; + public DataCallerIdentity Caller = caller; + public ProjectedBrowsePage Page = page; + public int Index = index; + public uint Maximum = maximum; + public long Expires = expires; + public ProjectedBrowseFilter Filter = filter; + public long Charge; + public bool Transferred; + public bool Released; + } + + private static bool TryProjectedCursor(ByteString token, out Guid id) + { + id = default; + var bytes = token.ToArray(); + if (bytes is null || bytes.Length != 24 || !bytes.AsSpan(0, 8).SequenceEqual(ProjectedCursorPrefix)) return false; + id = new Guid(bytes.AsSpan(8, 16)); + return true; + } + private static ByteString EncodeProjectedCursor(Guid id) + { + var bytes = new byte[24]; + ProjectedCursorPrefix.CopyTo(bytes, 0); + id.TryWriteBytes(bytes.AsSpan(8)); + return ByteString.From(bytes); + } + private void ReleaseProjectedCursor(ProjectedBrowseCursor cursor) + { + lock (_projectedBrowseLock) + { + if (cursor.Released || cursor.Transferred) return; + cursor.Released = true; + _projectedBrowseRetained--; _projectedBrowseRetainedBytes -= cursor.Charge; + } + } + private ByteString SaveProjectedCursor(ProjectedBrowseCursor cursor, TimeProvider clock, ProjectedBrowseCursor? replacing) + { + long charge; + try + { + charge = checked(4096L + Math.Max(0, cursor.Page.RetainedBytes) + 2L * (cursor.Page.NextCursor?.Length ?? 0) + + cursor.Page.Children.Sum(child => 128L + 2L * child.IdentifierAsString.Length)); + } + catch (OverflowException) { return default; } + lock (_projectedBrowseLock) + { + var now = clock.GetTimestamp(); + foreach (var expired in _projectedBrowseCursors.Where(pair => pair.Value.Expires <= now).Select(pair => pair.Key).ToArray()) + if (_projectedBrowseCursors.Remove(expired, out var removed)) ReleaseProjectedCursor(removed); + var oldCharge = replacing is { Released: false, Transferred: false } ? replacing.Charge : 0; + if ((oldCharge == 0 && _projectedBrowseRetained >= _maxProjectedBrowseCursors) || + charge > _maxProjectedBrowseBytes - _projectedBrowseRetainedBytes + oldCharge) return default; + var id = Guid.NewGuid(); + cursor.Charge = charge; + _projectedBrowseCursors.Add(id, cursor); + if (oldCharge == 0) _projectedBrowseRetained++; + else replacing!.Transferred = true; + _projectedBrowseRetainedBytes += charge - oldCharge; + return EncodeProjectedCursor(id); + } + } + private void UndoProjectedCursor(Guid id, ProjectedBrowseCursor? replacing) + { + lock (_projectedBrowseLock) + { + if (!_projectedBrowseCursors.Remove(id, out var created)) return; + if (replacing is { Transferred: true, Released: false }) + { + replacing.Transferred = false; + created.Released = true; + _projectedBrowseRetainedBytes += replacing.Charge - created.Charge; + } + else ReleaseProjectedCursor(created); + } + } + private static bool ProjectedPageCurrent(ProjectedBrowsePage page) + { try { return page.IsCurrent(); } catch (Exception) { return false; } } + private static DataCallerIdentity BrowseCaller(RoleCarryingUserIdentity caller) => + new(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + private static long BrowseExpiry(TimeProvider clock) + { + var now = clock.GetTimestamp(); + var frequency = clock.TimestampFrequency; + var duration = frequency > long.MaxValue / 60 ? long.MaxValue : frequency * 60; + return now > long.MaxValue - duration ? long.MaxValue : now + duration; + } + + private static bool MatchesProjectedClass(ReferenceDescription reference, uint mask) => mask == 0 || (mask & (uint)reference.NodeClass) != 0; + private static ReferenceDescription MaskProjectedReference(ReferenceDescription reference, uint mask) + { + if ((mask & (uint)BrowseResultMask.ReferenceTypeId) == 0) reference.ReferenceTypeId = default; + if ((mask & (uint)BrowseResultMask.IsForward) == 0) reference.IsForward = false; + if ((mask & (uint)BrowseResultMask.NodeClass) == 0) reference.NodeClass = NodeClass.Unspecified; + if ((mask & (uint)BrowseResultMask.BrowseName) == 0) reference.BrowseName = default; + if ((mask & (uint)BrowseResultMask.DisplayName) == 0) reference.DisplayName = default; + if ((mask & (uint)BrowseResultMask.TypeDefinition) == 0) reference.TypeDefinition = default; + return reference; + } + + private async Task ReadProjectedPageAsync(OtOpcUaNodeManager manager, RoleCarryingUserIdentity caller, + NodeId session, ProjectedBrowseCursor? cursor, NodeId parent, uint maximum, ProjectedBrowseFilter filter, + long started, CancellationToken cancellationToken) + { + var access = manager.ProjectedBrowseAccess; + if (access is null) return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication }; + if (!manager.CanBrowseProjectedParent(parent, caller)) return new BrowseResult { StatusCode = StatusCodes.BadUserAccessDenied }; + var limit = maximum == 0 ? MaxProjectedBrowseChildren : (int)Math.Min(maximum, MaxProjectedBrowseChildren); + var references = new List(); + if (cursor is null && (filter.Direction is BrowseDirection.Inverse or BrowseDirection.Both) && + manager.TryDescribeProjectedParent(parent, caller, out var inverse) && inverse is not null && MatchesProjectedClass(inverse, filter.NodeClassMask)) + references.Add(MaskProjectedReference(inverse, filter.ResultMask)); + if (filter.Direction == BrowseDirection.Inverse) + return manager.CanBrowseProjectedParent(parent, caller) + ? new BrowseResult { StatusCode = StatusCodes.Good, References = references.ToArray() } + : new BrowseResult { StatusCode = StatusCodes.BadUserAccessDenied }; + var page = cursor?.Page; + var index = cursor?.Index ?? 0; + if (page is null || (index >= page.Children.Count && !page.Complete)) + { + var next = page?.NextCursor; + if (page is not null && string.IsNullOrEmpty(next)) return new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; + page = await access.WaitForPageAsync(new(parent, caller, next, maximum, started), cancellationToken).ConfigureAwait(false); + index = 0; + } + if (cursor is not null && cursor.Expires <= manager.ProjectedBrowseClock.GetTimestamp()) + return new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; + if (page.Status != ProjectedBrowseReadiness.Ready) + return new BrowseResult { StatusCode = page.Status switch + { + ProjectedBrowseReadiness.Pending => StatusCodes.BadWaitingForInitialData, + ProjectedBrowseReadiness.InvalidContinuation => StatusCodes.BadContinuationPointInvalid, + _ => StatusCodes.BadNoCommunication + } }; + if (page.Children.Count > MaxProjectedBrowseChildren || page.Children.Sum(child => (long)child.IdentifierAsString.Length) > 2 * 1024 * 1024 || page.NextCursor?.Length > 16_384 || + (!page.Complete && string.IsNullOrEmpty(page.NextCursor)) || !ProjectedPageCurrent(page)) + return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication }; + while (index < page.Children.Count && references.Count < limit) + { + if (!ProjectedPageCurrent(page)) return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication }; + var child = page.Children[index++]; + if (manager.TryDescribeProjectedChild(child, caller, out var reference) && reference is not null && MatchesProjectedClass(reference, filter.NodeClassMask)) + references.Add(MaskProjectedReference(reference, filter.ResultMask)); + } + if (cursor is not null && cursor.Expires <= manager.ProjectedBrowseClock.GetTimestamp()) + return new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; + if (!manager.CanBrowseProjectedParent(parent, caller) || !ProjectedPageCurrent(page)) return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication }; + var result = new BrowseResult { StatusCode = StatusCodes.Good, References = references.ToArray() }; + if (index < page.Children.Count || !page.Complete) + { + var state = new ProjectedBrowseCursor(parent, session, BrowseCaller(caller), page, index, maximum, BrowseExpiry(manager.ProjectedBrowseClock), filter); + result.ContinuationPoint = SaveProjectedCursor(state, manager.ProjectedBrowseClock, cursor); + if (result.ContinuationPoint.IsEmpty) result.StatusCode = StatusCodes.BadNoContinuationPoints; + else if (!ProjectedPageCurrent(page)) + { + if (TryProjectedCursor(result.ContinuationPoint, out var retired)) UndoProjectedCursor(retired, cursor); + return new BrowseResult { StatusCode = StatusCodes.BadNoCommunication }; + } + } + return result; + } + + /// Browse mapped pages asynchronously, preserving the SDK path for local nodes. + public override async ValueTask BrowseAsync(SecureChannelContext secureChannelContext, RequestHeader? requestHeader, + ViewDescription? view, uint requestedMaxReferencesPerNode, ArrayOf nodesToBrowse, RequestLifetime requestLifetime) + { + var manager = _otOpcUaNodeManager; + var projected = false; + if (manager is not null) + for (var i = 0; i < nodesToBrowse.Count; i++) if (manager.IsProjectedBrowseNode(nodesToBrowse[i].NodeId)) { projected = true; break; } + if (!projected || manager is null) return await base.BrowseAsync(secureChannelContext, requestHeader, view, + requestedMaxReferencesPerNode, nodesToBrowse, requestLifetime).ConfigureAwait(false); + var started = manager.ProjectedBrowseClock.GetTimestamp(); + using var context = await ValidateRequestAsync(secureChannelContext, requestHeader, RequestType.Browse, requestLifetime).ConfigureAwait(false); + try + { + ValidateOperationLimits(nodesToBrowse, ServerInternal.ServerObject?.ServerCapabilities?.OperationLimits?.MaxNodesPerBrowse); + var results = new BrowseResult[nodesToBrowse.Count]; + var legacy = new List(); var indexes = new List(); + var caller = context.UserIdentity as RoleCarryingUserIdentity; + for (var i = 0; i < nodesToBrowse.Count; i++) + { + var request = nodesToBrowse[i]; + if (!manager.IsProjectedBrowseNode(request.NodeId)) { legacy.Add(request); indexes.Add(i); continue; } + if (caller is null || context.Session is null) + { results[i] = new BrowseResult { StatusCode = StatusCodes.BadUserAccessDenied }; continue; } + if (request.BrowseDirection is not (BrowseDirection.Forward or BrowseDirection.Inverse or BrowseDirection.Both)) + { results[i] = new BrowseResult { StatusCode = StatusCodes.BadBrowseDirectionInvalid }; continue; } + var viewError = manager.ValidateProjectedView(context, view); + if (viewError is not null) { results[i] = new BrowseResult { StatusCode = viewError.StatusCode }; continue; } + if (!request.ReferenceTypeId.IsNull && ServerInternal.TypeTree.FindReferenceTypeName(request.ReferenceTypeId).IsNull) + { results[i] = new BrowseResult { StatusCode = StatusCodes.BadReferenceTypeIdInvalid }; continue; } + var matchesReference = request.ReferenceTypeId.IsNull || request.ReferenceTypeId == ReferenceTypeIds.Organizes || + (request.IncludeSubtypes && ServerInternal.TypeTree.IsTypeOf(ReferenceTypeIds.Organizes, request.ReferenceTypeId)); + if (!matchesReference) { results[i] = new BrowseResult { StatusCode = StatusCodes.Good }; continue; } + var copiedView = view is null ? null : new ViewDescription { ViewId = view.ViewId, Timestamp = view.Timestamp, ViewVersion = view.ViewVersion }; + var filter = new ProjectedBrowseFilter(request.BrowseDirection, request.ReferenceTypeId, request.IncludeSubtypes, + request.NodeClassMask, request.ResultMask, copiedView); + results[i] = await ReadProjectedPageAsync(manager, caller, context.SessionId, null, request.NodeId, + requestedMaxReferencesPerNode, filter, started, requestLifetime.CancellationToken).ConfigureAwait(false); + } + if (legacy.Count > 0) + { + var (other, _) = await ServerInternal.NodeManager.BrowseAsync(context, view ?? new ViewDescription(), requestedMaxReferencesPerNode, + legacy.ToArray(), requestLifetime.CancellationToken).ConfigureAwait(false); + for (var i = 0; i < indexes.Count; i++) results[indexes[i]] = other[i]; + } + return new BrowseResponse { Results = results, ResponseHeader = CreateResponse(requestHeader, context.StringTable) }; + } + finally { OnRequestComplete(context); } + } + + /// BrowseNext for SDK-owned projected cursors, retaining standard handling for other tokens. + public override async ValueTask BrowseNextAsync(SecureChannelContext secureChannelContext, RequestHeader? requestHeader, + bool releaseContinuationPoints, ArrayOf continuationPoints, RequestLifetime requestLifetime) + { + var manager = _otOpcUaNodeManager; + var projected = false; + for (var i = 0; i < continuationPoints.Count; i++) if (TryProjectedCursor(continuationPoints[i], out _)) { projected = true; break; } + if (!projected || manager is null) return await base.BrowseNextAsync(secureChannelContext, requestHeader, + releaseContinuationPoints, continuationPoints, requestLifetime).ConfigureAwait(false); + var started = manager.ProjectedBrowseClock.GetTimestamp(); + using var context = await ValidateRequestAsync(secureChannelContext, requestHeader, RequestType.BrowseNext, requestLifetime).ConfigureAwait(false); + try + { + ValidateOperationLimits(continuationPoints, ServerInternal.ServerObject?.ServerCapabilities?.OperationLimits?.MaxNodesPerBrowse); + var results = new BrowseResult[continuationPoints.Count]; + var legacy = new List(); var indexes = new List(); + var caller = context.UserIdentity as RoleCarryingUserIdentity; + for (var i = 0; i < continuationPoints.Count; i++) + { + var token = continuationPoints[i]; + if (!TryProjectedCursor(token, out var id)) { legacy.Add(token); indexes.Add(i); continue; } + ProjectedBrowseCursor? state = null; + lock (_projectedBrowseLock) + { + if (caller is not null && context.Session is not null && _projectedBrowseCursors.TryGetValue(id, out var candidate) && + candidate.Session == context.SessionId && candidate.Caller == BrowseCaller(caller) && + candidate.Expires > manager.ProjectedBrowseClock.GetTimestamp()) + { state = candidate; _projectedBrowseCursors.Remove(id); } + } + if (state is null || caller is null) { results[i] = new BrowseResult { StatusCode = StatusCodes.BadContinuationPointInvalid }; continue; } + if (releaseContinuationPoints) { ReleaseProjectedCursor(state); results[i] = new BrowseResult { StatusCode = StatusCodes.Good }; continue; } + var viewError = manager.ValidateProjectedView(context, state.Filter.View); + if (viewError is not null) { ReleaseProjectedCursor(state); results[i] = new BrowseResult { StatusCode = viewError.StatusCode }; continue; } + try + { + results[i] = await ReadProjectedPageAsync(manager, caller, context.SessionId, state, state.Parent, state.Maximum, state.Filter, + started, requestLifetime.CancellationToken).ConfigureAwait(false); + if (StatusCode.IsBad(results[i].StatusCode) && state.Expires > manager.ProjectedBrowseClock.GetTimestamp()) + lock (_projectedBrowseLock) _projectedBrowseCursors.TryAdd(id, state); + else ReleaseProjectedCursor(state); + } + catch + { + lock (_projectedBrowseLock) _projectedBrowseCursors.TryAdd(id, state); + throw; + } + } + if (legacy.Count > 0) + { + var (other, _) = await ServerInternal.NodeManager.BrowseNextAsync(context, releaseContinuationPoints, legacy.ToArray(), + requestLifetime.CancellationToken).ConfigureAwait(false); + for (var i = 0; i < indexes.Count; i++) results[indexes[i]] = other[i]; + } + return new BrowseNextResponse { Results = results, ResponseHeader = CreateResponse(requestHeader, context.StringTable) }; + } + finally { OnRequestComplete(context); } + } + private long _publishesSinceSweep; /// @@ -382,6 +742,8 @@ public sealed class OtOpcUaSdkServer : StandardServer { var response = await base.PublishAsync(secureChannelContext, requestHeader, subscriptionAcknowledgements, requestLifetime) .ConfigureAwait(false); + if (response?.NotificationMessage is { } projectedMessage) + response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: false); if (_standby.Delivery is not { } record || response?.NotificationMessage is not { } message) return response!; if (message.NotificationData.Count > 0) @@ -402,6 +764,8 @@ public sealed class OtOpcUaSdkServer : StandardServer { var response = await base.RepublishAsync(secureChannelContext, requestHeader, subscriptionId, retransmitSequenceNumber, requestLifetime).ConfigureAwait(false); + if (response?.NotificationMessage is { } projectedMessage) + response.NotificationMessage = ProjectedNotificationRewriter.Project(projectedMessage, republish: true); if (_standby.Delivery is { } record && response?.NotificationMessage is { NotificationData.Count: > 0 } message) response.NotificationMessage = Decide(record, subscriptionId, message); return response!; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedBrowseContinuation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedBrowseContinuation.cs new file mode 100644 index 000000000..218df9423 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedBrowseContinuation.cs @@ -0,0 +1,44 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// SDK-owned, session-bound peer cursor; it does not expose or own the peer token to the client. +internal sealed class ProjectedBrowseContinuation : IDisposable +{ + private readonly object _sync = new(); + private readonly NodeId _parent; + private readonly NodeId _session; + private readonly DataCallerIdentity _caller; + private string? _cursor; + private bool _disposed; + + public ProjectedBrowseContinuation(NodeId parent, NodeId session, RoleCarryingUserIdentity caller, string? cursor) + { + _parent = parent; _session = session; + _caller = new(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + _cursor = cursor; + } + public bool TryGetCursor(NodeId parent, NodeId session, RoleCarryingUserIdentity caller, out string? cursor) + { + lock (_sync) + { + if (!_disposed && parent == _parent && session == _session && + _caller == new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc)) + { cursor = _cursor; return true; } + cursor = null; return false; + } + } + public bool TryAdvance(string? expectedCursor, string? nextCursor, Func commit) + { + ArgumentNullException.ThrowIfNull(commit); + lock (_sync) + { + if (_disposed || _cursor != expectedCursor || !commit()) return false; + _cursor = nextCursor; + return true; + } + } + public void Dispose() { lock (_sync) { _disposed = true; _cursor = null; } } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedCandidateBudget.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedCandidateBudget.cs new file mode 100644 index 000000000..e153cd7f4 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedCandidateBudget.cs @@ -0,0 +1,36 @@ +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// Shared retained-candidate accounting across projected monitored items. +internal sealed class ProjectedCandidateBudget +{ + private readonly object _sync = new(); + private readonly int _maxEntries; + private readonly long _maxBytes; + private int _entries; + private long _bytes; + public ProjectedCandidateBudget(int maxEntries, long maxBytes) + { + if (maxEntries <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxEntries)); + _maxEntries = maxEntries; _maxBytes = maxBytes; + } + public long RetainedBytes { get { lock (_sync) return _bytes; } } + public int RetainedEntries { get { lock (_sync) return _entries; } } + public bool TryReserve(long bytes, out IDisposable? lease) + { + lease = null; + if (bytes <= 0) return false; + lock (_sync) + { + if (_entries >= _maxEntries || bytes > _maxBytes - _bytes) return false; + _entries++; _bytes += bytes; + lease = new Reservation(this, bytes); + return true; + } + } + private void Release(long bytes) { lock (_sync) { _entries--; _bytes -= bytes; } } + private sealed class Reservation(ProjectedCandidateBudget owner, long bytes) : IDisposable + { + private int _released; + public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) owner.Release(bytes); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedNodeLifetime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedNodeLifetime.cs new file mode 100644 index 000000000..7108962d7 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedNodeLifetime.cs @@ -0,0 +1,56 @@ +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// A pin on one exact SDK materialization incarnation. +public interface IProjectedNodePin : IDisposable { bool IsValid { get; } } + +/// Atomically fences idle retirement against new demand. +public sealed class ProjectedNodeLifetime +{ + private readonly object _sync = new(); + private int _pins; + private bool _retired; + private Action? _drained; + public bool TryPin(out IProjectedNodePin? pin) + { + lock (_sync) + { + if (_retired) { pin = null; return false; } + checked { _pins++; } + pin = new Pin(this); + return true; + } + } + public bool TryRetire() + { + lock (_sync) { if (_retired || _pins != 0) return false; _retired = true; return true; } + } + public void ForceRetire() => ForceRetire(null); + internal void ForceRetire(Action? drained) + { + Action? ready = null; + lock (_sync) + { + _retired = true; + _drained += drained; + if (_pins == 0) { ready = _drained; _drained = null; } + } + ready?.Invoke(); + } + public bool IsActive { get { lock (_sync) return !_retired; } } + private void Release() + { + Action? ready = null; + lock (_sync) + { + _pins--; + if (_retired && _pins == 0) { ready = _drained; _drained = null; } + } + ready?.Invoke(); + } + private sealed class Pin(ProjectedNodeLifetime owner) : IProjectedNodePin + { + private int _disposed; + public bool IsValid => Volatile.Read(ref _disposed) == 0 && owner.IsActive; + public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) owner.Release(); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs index c939d9363..63eaf4af5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/SdkAddressSpaceSink.cs @@ -1,4 +1,6 @@ +using Opc.Ua; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; @@ -8,7 +10,7 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// . The host wires this in once the StandardServer has /// been started (so the node manager exists). /// -public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink +public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink, IProjectedNamespacePageSink, IProjectedNodeLookup, IProjectedAnchorSink { private readonly OtOpcUaNodeManager _nodeManager; @@ -20,6 +22,32 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre _nodeManager = nodeManager; } + /// + public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) => _nodeManager.TryResolve(nodeId, out definition); + + /// + public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) => _nodeManager.TryGetNodeId(namespaceUri, identifier, out nodeId); + + /// + public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition definition, out NodeId? nodeId) => _nodeManager.TryEnsureProjectedAnchor(definition, out nodeId); + + /// + public bool TryRemoveProjectedAnchor(NodeId nodeId, ProjectedAnchorDefinition expected) => _nodeManager.TryRemoveProjectedAnchor(nodeId, expected); + + /// + public bool TryApplyRootLeaf(NodeId anchorId, ProjectedVariableDefinition rootDefinition, Func commit) => + ((IProjectedNamespacePageSink)_nodeManager).TryApplyRootLeaf(anchorId, rootDefinition, commit); + + /// + public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => ((IProjectedNamespacePageSink)_nodeManager).TryRemove(nodeId, expected); + + /// + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) => + ((IProjectedNamespacePageSink)_nodeManager).TryApply(parent, nodes, commit); + + /// + public bool TryPublish(IReadOnlyList values) => ((IProjectedValueSink)_nodeManager).TryPublish(values); + /// public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) => _nodeManager.WriteValue(nodeId, value, statusCode, sourceTimestampUtc, realm); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs index 947b38839..df1f203c1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs @@ -141,6 +141,9 @@ public sealed class DataPlaneAuthorizer /// Live catalog classification owned by the node manager, consulted before either local path resolver. public Func? MappedSubjectResolver { get; set; } + /// Optional actual-namespace filter for projected subject classification. + public Func? MappedNamespacePredicate { get; set; } + /// Checks a mapped subject even when local ACL enforcement is disabled. public ServiceResult? AuthorizeIfRequired(RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId, AddressSpaceRealm realm, bool cached = true) => @@ -151,6 +154,7 @@ public sealed class DataPlaneAuthorizer NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto) { var resolver = MappedSubjectResolver; + if (MappedNamespacePredicate is { } predicate && !predicate(nodeId)) { veto = null; return false; } if (resolver is null) { veto = null; return false; } if (!nodeId.TryGetValue(out string identifier) || identifier.Length == 0 || identifier.Contains('\0')) { veto = DeniedResult; return true; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs index af53baaf6..9a1f01627 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/WarmStandby.cs @@ -1,6 +1,8 @@ using Microsoft.Extensions.Logging; using Opc.Ua; using Opc.Ua.Server; +using DataValue = Opc.Ua.DataValue; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; @@ -325,7 +327,7 @@ internal sealed class OrdinaryTagMonitoredItem : MonitoredItem /// its internal lifecycle interface keep working (T0c; the 2.0.1 MonitoredItemFactory hook exists only on /// AsyncCustomNodeManager). Installed only under Warm; Unset/None keep the SDK's manager. /// -internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, IServerInternal server) +internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, IServerInternal server, OtOpcUaNodeManager owner, bool warmMode) : MonitoredNodeMonitoredItemManager(nodeManager, server), IMonitoredItemManager { /// @@ -335,13 +337,22 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer Opc.Ua.Range euRange, MonitoringFilter filterToUse, double samplingInterval, uint revisedQueueSize, bool createDurable, MonitoredItemIdFactory monitoredItemIdFactory, Func addNodeToComponentCache) { - if (handle.Node is not EquipmentVariableState || itemToCreate.ItemToMonitor.AttributeId != Attributes.Value) + var projected = owner.IsProjectedItem(handle.NodeId) && itemToCreate.ItemToMonitor.AttributeId == Attributes.Value; + if (!projected && (!warmMode || handle.Node is not EquipmentVariableState || itemToCreate.ItemToMonitor.AttributeId != Attributes.Value)) { return CreateMonitoredItem(server, nodeManager, context, handle, subscriptionId, publishingInterval, diagnosticsMasks, timestampsToReturn, itemToCreate, euRange, filterToUse, samplingInterval, revisedQueueSize, createDurable, monitoredItemIdFactory, addNodeToComponentCache); } + IProjectedDemandLease? demand = null; + ProjectedValueWrite? initialSample = null; + ProjectedVariableDefinition? definition = null; + if (projected && !owner.TryAcquireProjectedItem(context, handle.NodeId, publishingInterval, out demand, out initialSample, out definition)) + throw new ServiceResultException(StatusCodes.BadUserAccessDenied); + uint? reservedId = null; + try + { // Mirrors MonitoredNodeMonitoredItemManager.CreateMonitoredItem in exact tagged 2.0.1, swapping only the item type. var cachedNode = addNodeToComponentCache(context, handle, handle.Node); if (!MonitoredNodes.TryGetValue(handle.Node.NodeId, out var monitoredNode)) @@ -358,12 +369,222 @@ internal sealed class OrdinaryTagItemManager(IAsyncNodeManager nodeManager, ISer id = monitoredItemIdFactory.GetNextId(); } while (!MonitoredItems.TryAdd(id, null!)); + reservedId = id; - var item = new OrdinaryTagMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks, - timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable); + ISampledDataChangeMonitoredItem item = projected + ? new ProjectedMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks, + timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable, + owner, demand!, initialSample, definition!) + : new OrdinaryTagMonitoredItem(server, nodeManager, handle, subscriptionId, id, itemToCreate, diagnosticsMasks, + timestampsToReturn, filterToUse, euRange, samplingInterval, revisedQueueSize, createDurable); monitoredNode.Add((IDataChangeMonitoredItem2)item); + if (item is ProjectedMonitoredItem projectedItem) owner.ObserveCurrentProjectedSource(projectedItem); MonitoredItems[id] = item; + demand = null; return item; + } + catch + { + if (reservedId is { } id) MonitoredItems.TryRemove(id, out _); + demand?.Dispose(); + throw; + } + } +} + +/// A projected item retains its original caller, item lifetime and source proof. +internal sealed class ProjectedMonitoredItem : MonitoredItem +{ + private readonly OtOpcUaNodeManager _owner; + private IProjectedDemandLease? _demand; + private ProjectedVariableDefinition? _definition; + private readonly NodeId _nodeId; + private sealed class SourceBinding(IProjectedSamplePublicationProof proof) + { + private readonly object _sync = new(); + private IProjectedSamplePublicationProof? _proof = proof; + private readonly List> _evidence = []; + public IProjectedSamplePublicationProof? Proof { get { lock (_sync) return _proof; } } + public bool IsValid => Proof is { IsSourceValid: true }; + public SampleEvidence? Capture(IProjectedSamplePublicationProof sample, DataAgeBounds age, long timestamp) + { + lock (_sync) + { + if (_proof is null) return null; + _evidence.RemoveAll(entry => !entry.TryGetTarget(out _)); + if (_evidence.Count >= 4096) return null; + var evidence = new SampleEvidence(this, sample, age, timestamp); + _evidence.Add(new(evidence)); + return evidence; + } + } + public void Retire() + { + lock (_sync) + { + _proof = null; + foreach (var entry in _evidence) if (entry.TryGetTarget(out var evidence)) evidence.Clear(); + _evidence.Clear(); + } + } + } + private sealed record Candidate(ProjectedValueWrite Sample, Variant Value, SourceBinding Binding, long Bytes, IDisposable Charge); + private sealed class SampleEvidence(SourceBinding binding, IProjectedSamplePublicationProof proof, DataAgeBounds age, long receivedTimestamp) + { + private IProjectedSamplePublicationProof? _proof = proof; + public SourceBinding Binding => binding; + public IProjectedSamplePublicationProof? Proof => Volatile.Read(ref _proof); + public DataAgeBounds Age => age; + public long ReceivedTimestamp => receivedTimestamp; + public void Clear() => Interlocked.Exchange(ref _proof, null); + } + private const int MaxCandidates = 1024; + private const long MaxCandidateBytes = 1024 * 1024; + private readonly object _bindingSync = new(); + private readonly List _candidates = []; + private long _candidateBytes; + private bool _needsSnapshot; + private int _snapshotRequested; + private SourceBinding? _binding; + private int _retired; + private int _released; + + public ProjectedMonitoredItem(IServerInternal server, IAsyncNodeManager nodeManager, NodeHandle handle, uint subscriptionId, + uint id, MonitoredItemCreateRequest request, DiagnosticsMasks masks, TimestampsToReturn timestamps, + MonitoringFilter? filter, Opc.Ua.Range? range, double samplingInterval, uint queueSize, bool durable, + OtOpcUaNodeManager owner, IProjectedDemandLease demand, ProjectedValueWrite? initialSample, ProjectedVariableDefinition definition) + : base(server, nodeManager, handle, subscriptionId, id, request.ItemToMonitor, masks, timestamps, + request.MonitoringMode, request.RequestedParameters.ClientHandle, filter, filter, range, samplingInterval, queueSize, + request.RequestedParameters.DiscardOldest, 0, durable) + { + _owner = owner; _demand = demand; _definition = definition; _nodeId = handle.NodeId; + if (initialSample is not null) + { + _binding = new(initialSample.Proof); + AddCandidate(initialSample, _binding); + } + } + + internal NodeId ProjectedNodeId => _nodeId; + internal bool ObserveSample(ProjectedValueWrite sample) + { + lock (_bindingSync) + { + var original = _binding; + var sameSource = original is not null && ReferenceEquals(original.Proof?.SourceIdentity, sample.Proof.SourceIdentity); + if (!sameSource || (_needsSnapshot && sample.IsCompleteSnapshot)) + { + original?.Retire(); + _binding = null; + if (Volatile.Read(ref _retired) != 0 || !sample.IsCompleteSnapshot || !sample.Proof.IsSourceValid || _demand?.IsValid != true) + { _needsSnapshot = true; return true; } + // Pinned SDK resets the entire data queue and last value across this transition. + var mode = MonitoringMode; + if (mode != MonitoringMode.Disabled) + { + SetMonitoringMode(MonitoringMode.Disabled); + SetMonitoringMode(mode); + } + ClearCandidates(); _needsSnapshot = false; + Interlocked.Exchange(ref _snapshotRequested, 0); + _binding = new(sample.Proof); + } + if (_binding is null) { _needsSnapshot = true; return true; } + if (_candidates.Any(candidate => ReferenceEquals(candidate.Sample, sample))) return false; + return !AddCandidate(sample, _binding); + } + } + private bool AddCandidate(ProjectedValueWrite sample, SourceBinding binding) + { + long bytes = 256; + if (sample.Snapshot.Value is string text) bytes += 2L * text.Length; + else if (sample.Snapshot.Value is Array array) + { + if (array.Rank != 1 || array.Length > 65_536) { _needsSnapshot = true; return false; } + bytes += 64L * array.Length; + if (array is string[] strings) foreach (var item in strings) bytes += 2L * (item?.Length ?? 0); + } + if (bytes > MaxCandidateBytes || _candidates.Count >= MaxCandidates || _candidateBytes > MaxCandidateBytes - bytes) + { _needsSnapshot = true; return false; } + if (!_owner.ProjectedCandidateBudget.TryReserve(bytes, out var charge) || charge is null) + { _needsSnapshot = true; return false; } + try + { + var value = SdkValueBoundary.FromClr(sample.Snapshot.Value, + _definition?.Metadata.ValueKind == DataValueKind.Array && _definition.Metadata.ArrayElementKind == DataValueKind.UInt8); + _candidates.Add(new(sample, value, binding, bytes, charge)); + _candidateBytes += bytes; + return true; + } + catch (ArgumentException) { charge.Dispose(); _needsSnapshot = true; return false; } + } + private void ClearCandidates() + { + foreach (var candidate in _candidates) candidate.Charge.Dispose(); + _candidates.Clear(); _candidateBytes = 0; + } + internal void RequestBaseline() + { + if (Volatile.Read(ref _retired) != 0 || _demand?.IsValid != true || Interlocked.CompareExchange(ref _snapshotRequested, 1, 0) != 0) return; + if (_demand is not { } demand || !_owner.RequestProjectedSnapshot(demand)) Interlocked.Exchange(ref _snapshotRequested, 0); + } + private bool IsCurrentCandidate(SourceBinding? binding, SampleEvidence? candidate) + { + if (candidate is null || !ReferenceEquals(candidate.Binding, binding) || !IsCurrentBinding(binding) || + _demand is not { } demand || demand.MaximumSampleAge <= TimeSpan.Zero) return false; + if (candidate.Proof is not { IsValid: true } proof) { RequestBaseline(); return false; } + try + { + var age = candidate.Age.Advance(proof.Clock.GetElapsedTime(candidate.ReceivedTimestamp, proof.Clock.GetTimestamp())); + if (age.IsFresh(demand.MaximumSampleAge)) return proof.IsValid && IsCurrentBinding(binding); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { } + RequestBaseline(); + return false; + } + private bool IsCurrentBinding(SourceBinding? binding) => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } && + binding is { IsValid: true } && _definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition); + internal bool IsCurrent => IsCurrentBinding(Volatile.Read(ref _binding)); + internal bool HasCurrentDemand => Volatile.Read(ref _retired) == 0 && _demand is { IsValid: true } && + _definition is { } definition && _owner.IsProjectedDefinitionCurrent(_nodeId, definition); + internal void Retire() + { + Interlocked.Exchange(ref _retired, 1); + lock (_bindingSync) { _binding?.Retire(); _binding = null; ClearCandidates(); } + _definition = null; + if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Exchange(ref _demand, null)?.Dispose(); + } + public override bool Publish(OperationContext context, Queue notifications, + Queue diagnostics, uint maximum, ILogger logger) + { + var captured = Volatile.Read(ref _binding); + var local = new Queue(); + var localDiagnostics = new Queue(); + var more = base.Publish(context, local, localDiagnostics, maximum, logger); + while (local.Count > 0) + { + var notification = local.Dequeue(); + SampleEvidence? evidence = null; + lock (_bindingSync) + { + var matching = _candidates.Where(candidate => ReferenceEquals(candidate.Binding, captured) && + candidate.Value.Equals(notification.Value.WrappedValue) && candidate.Sample.Snapshot.StatusCode == notification.Value.StatusCode.Code).Take(2).ToArray(); + if (matching.Length == 1) + { + var matched = matching[0]; _candidates.Remove(matched); _candidateBytes -= matched.Bytes; + evidence = matched.Binding.Capture(matched.Sample.Proof, matched.Sample.OriginAgeBounds, matched.Sample.ReceivedTimestamp); + matched.Charge.Dispose(); + } + else _needsSnapshot = true; + } + if (evidence is null) RequestBaseline(); + var originalSample = evidence; + notification.Message = new ProjectedNotificationMarker(notification.ClientHandle, notification.Value, () => IsCurrentCandidate(captured, originalSample)); + notifications.Enqueue(notification); + if (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue()); + } + while (localDiagnostics.Count > 0) diagnostics.Enqueue(localDiagnostics.Dequeue()); + return more; } } @@ -386,3 +607,81 @@ internal sealed class SdkStandbyProjection(OtOpcUaNodeManager nodeManager, WarmS /// public int RefreshAllEventItems() => nodeManager.RefreshAllEventItems(); } + +/// Captured per-notification proof. A stale pooled helper is treated as denied. +internal sealed class ProjectedNotificationMarker : NotificationMessage +{ + private readonly uint _clientHandle; + private readonly byte[]? _fingerprint; + private readonly Func _authorize; + public ProjectedNotificationMarker(uint clientHandle, DataValue value, Func authorize) + { _clientHandle = clientHandle; _fingerprint = Fingerprint(value); _authorize = authorize; } + public bool Permits(MonitoredItemNotification notification) + { + if (notification.ClientHandle != _clientHandle || _fingerprint is null) return false; + try + { + var current = Fingerprint(notification.Value); + return current is not null && System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(_fingerprint, current) && _authorize(); + } + catch { return false; } + } + private static byte[]? Fingerprint(DataValue value) + { + try + { + var payload = SdkValueBoundary.ToClr(value.WrappedValue); + if (payload is Array array) + { + if (array.Rank != 1 || array.Length > 65_536 || array.GetType().GetElementType() is not { } type || + type != typeof(bool) && type != typeof(sbyte) && type != typeof(byte) && type != typeof(short) && type != typeof(ushort) && + type != typeof(int) && type != typeof(uint) && type != typeof(long) && type != typeof(ulong) && + type != typeof(float) && type != typeof(double) && type != typeof(string) && type != typeof(DateTime)) return null; + } + else if (payload is not (null or bool or sbyte or byte or short or ushort or int or uint or long or ulong or float or double or string or DateTime or Guid) || + payload is string { Length: > 524288 }) return null; + var encoded = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(new + { + Type = payload?.GetType().FullName, Value = payload, Status = value.StatusCode.Code, + Source = value.SourceTimestamp.ToString(), Server = value.ServerTimestamp.ToString() + }); + return encoded.Length <= 1024 * 1024 ? System.Security.Cryptography.SHA256.HashData(encoded) : null; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NotSupportedException or System.Text.Json.JsonException) + { return null; } + } +} + +/// Rechecks captured projected notification authority for every delivery and retransmission. +internal static class ProjectedNotificationRewriter +{ + public static NotificationMessage Project(NotificationMessage message, bool republish) + { + var changed = false; + var payloads = new List(message.NotificationData.Count); + foreach (var payload in message.NotificationData) + { + if (!payload.TryGetValue(out var change) || change is null) + { payloads.Add(payload); continue; } + var items = new List(change.MonitoredItems.Count); + var changedPayload = false; + foreach (var item in change.MonitoredItems) + { + if (item.Message is ProjectedNotificationMarker marker && !marker.Permits(item)) + { + items.Add(new MonitoredItemNotification { ClientHandle = item.ClientHandle, + Value = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied, DateTimeUtc.MinValue, item.Value.ServerTimestamp) }); + changedPayload = true; + } + else items.Add(item); + } + if (changedPayload) + { + changed = true; + payloads.Add(new ExtensionObject(new DataChangeNotification { MonitoredItems = items, DiagnosticInfos = change.DiagnosticInfos })); + } + else payloads.Add(payload); + } + return changed ? new NotificationMessage { SequenceNumber = message.SequenceNumber, PublishTime = message.PublishTime, NotificationData = payloads } : message; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs new file mode 100644 index 000000000..effc1f466 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ActorProjectedValuePublisher.cs @@ -0,0 +1,397 @@ +using Akka.Actor; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Owns bounded imported-value messages through the actual SDK apply, with captured route ownership. +public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDisposable +{ + private sealed class Binding(ProjectedValueRoute route) + { + internal ProjectedValueRoute Route { get; } = route; + internal object? SourceIdentity; + internal object? PublicationIdentity; + } + private readonly object _sync = new(); + private readonly Dictionary<(DataRealm, string), Binding> _bindings = new(); + private readonly HashSet _pending = []; + private readonly HashSet _retiredReferences = new(StringComparer.Ordinal); + private readonly Dictionary _trackedReferences = new(StringComparer.Ordinal); + private long _controlBytes; + private readonly long _maximumControlBytes; + private IActorRef? _retirementHost; + private bool _retirementWakePending; + private IActorRef? _valueHost; + private bool _valueWakePending; + private IActorRef? _sdkActor; + private bool _sdkWakePending; + private readonly HashSet _sdkPending = []; + private IActorRef? _muxTarget; + private ProjectedCoalescingMailbox? _muxMailbox; + private readonly Func _host; + private readonly Func _authority; + private readonly int _maximumRoutes; + private readonly long _maximumBytes; + private readonly TimeProvider _clock; + private readonly ITimer _cleanup; + private long _pendingBytes; + private long _nextQueueSequence; + private bool _disposed; + + public ActorProjectedValuePublisher(Func host, Func authority, + int maximumRoutes, long maximumPendingBytes, TimeProvider clock, long maximumControlBytes = 16 * 1024 * 1024) + { + if (maximumRoutes <= 0 || maximumPendingBytes <= 0 || maximumControlBytes <= 0) + throw new ArgumentOutOfRangeException(nameof(maximumRoutes)); + _host = host; _authority = authority; _maximumRoutes = maximumRoutes; _maximumBytes = maximumPendingBytes; _clock = clock; + _maximumControlBytes = maximumControlBytes; + _cleanup = clock.CreateTimer(static state => ((ActorProjectedValuePublisher)state!).SweepQueued(), this, + TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); + } + public long PendingBytes { get { lock (_sync) return _pendingBytes; } } + public long RetainedControlBytes { get { lock (_sync) return _controlBytes; } } + private static (DataRealm, string) Key(ProjectedValueRoute route) => (route.Realm, route.LocalIdentifier); + private bool Authorized(ProjectedValueRoute route) + { + try + { + route.Serving.Validate(requireEpochs: true); + if (string.IsNullOrWhiteSpace(route.DriverInstanceId) || route.DriverInstanceId.Length > 512 || + route.Serving.NodeId.Length > 512 || route.Serving.Incarnation.Length > 256 || route.Serving.Role.Length > 32) + return false; + return route.PublicationId != Guid.Empty && route.ProjectionGeneration > 0 && route.Serving.ServingGeneration > 0 + && ProjectedDataIds.TryParseDependencyReference(route.DependencyReference, out var realm, out var id) + && realm == route.Realm && id == route.LocalIdentifier && _authority(route); + } + catch (Exception) { return false; } + } + public bool TryBind(ProjectedValueRoute route) + { + ArgumentNullException.ThrowIfNull(route); + if (!Authorized(route)) return false; + lock (_sync) + { + if (_disposed) return false; + var bytes = RouteCharge(route); + if (_trackedReferences.TryGetValue(route.DependencyReference, out var held)) + { + var additional = Math.Max(0, bytes - held); + if (additional > _maximumControlBytes - _controlBytes) return false; + _trackedReferences[route.DependencyReference] = Math.Max(held, bytes); _controlBytes += additional; + } + else + { + if (_trackedReferences.Count >= _maximumRoutes || bytes > _maximumControlBytes - _controlBytes) return false; + _trackedReferences.Add(route.DependencyReference, bytes); _controlBytes += bytes; + } + if (!_bindings.TryGetValue(Key(route), out var current) || current.Route != route) + _bindings[Key(route)] = new(route); + return true; + } + } + internal static long RouteCharge(ProjectedValueRoute route) => checked(1024L + 8L * + (route.DependencyReference.Length + route.LocalIdentifier.Length + route.DriverInstanceId.Length + + route.Serving.NodeId.Length + route.Serving.Incarnation.Length + route.Serving.Role.Length)); + private bool Current(Binding binding) + { + lock (_sync) + if (_disposed || !_bindings.TryGetValue(Key(binding.Route), out var now) || !ReferenceEquals(binding, now)) return false; + return Authorized(binding.Route); + } + private sealed class Witness(ActorProjectedValuePublisher owner, Binding binding, + IProjectedSamplePublicationProof source, object identity, DataAgeBounds ageBounds, + long receivedTimestamp, TimeSpan? maximumAge) : IProjectedSamplePublicationProof + { + public object SourceIdentity => identity; + public bool IsSourceValid { get { try { return owner.Current(binding) && source.IsSourceValid && owner.OwnsIdentity(binding, identity); } catch (Exception) { return false; } } } + public bool IsValid + { + get + { + try + { + if (!IsSourceValid || !source.IsValid) return false; + if (maximumAge is not { } limit) return owner.OwnsIdentity(binding, identity); + var elapsed = Clock.GetElapsedTime(receivedTimestamp); + return limit > TimeSpan.Zero && elapsed >= TimeSpan.Zero && ageBounds.Advance(elapsed).IsFresh(limit) && owner.OwnsIdentity(binding, identity); + } + catch (Exception) { return false; } + } + } + public TimeProvider Clock => source.Clock; + public void Invalidate() { try { source.Invalidate(); } finally { owner.RetireWitness(binding, identity); } } + } + private bool OwnsIdentity(Binding binding, object identity) + { + lock (_sync) return !_disposed && _bindings.TryGetValue(Key(binding.Route), out var current) && + ReferenceEquals(current, binding) && ReferenceEquals(binding.PublicationIdentity, identity); + } + private void RetireWitness(Binding binding, object identity) + { + var removed = false; + lock (_sync) + if (OwnsIdentity(binding, identity)) + { _bindings.Remove(Key(binding.Route)); _retiredReferences.Add(binding.Route.DependencyReference); removed = true; } + if (removed) NotifyRetirements(); + } + private Witness WitnessFor(Binding binding, ProjectedValueUpdate update) + { + var source = update.SourceProof; + var sourceIdentity = source.SourceIdentity ?? throw new InvalidOperationException("Source identity is required."); + lock (_sync) + { + if (!ReferenceEquals(binding.SourceIdentity, sourceIdentity)) + { binding.SourceIdentity = sourceIdentity; binding.PublicationIdentity = new object(); } + return new(this, binding, source, binding.PublicationIdentity!, update.OriginAgeBounds, + update.ReceivedTimestamp, update.MaximumSampleAge); + } + } + private void Invalidate(IEnumerable updates) + { + foreach (var update in updates) + { + try { update.SourceProof.Invalidate(); } catch (Exception) { } + Retire(update.Route); + } + } + private IActorRef? Host() { try { return _host(); } catch (Exception) { return null; } } + private void SweepQueued() + { + ProjectedPublicationBatch[] pending; + lock (_sync) { if (_disposed) return; pending = _pending.ToArray(); } + foreach (var batch in pending) if (!batch.IsValid) batch.AbortQueued(); + NotifyRetirements(); + } + + public bool TryPublish(IReadOnlyList updates) + { + ArgumentNullException.ThrowIfNull(updates); + if (updates.Count == 0 || updates.Count > _maximumRoutes) { Invalidate(updates); return false; } + var captured = updates.ToArray(); + var bindings = new Binding[captured.Length]; + long charge = 256; + try + { + if (captured.Select(update => Key(update.Route)).Distinct().Count() != captured.Length) throw new ArgumentException("Duplicate projected route."); + for (var i = 0; i < captured.Length; i++) + { + var update = captured[i]; + update.OriginAgeBounds.Validate(); + if (!ReferenceEquals(update.SourceProof.Clock, _clock) || !update.SourceProof.IsValid + || _clock.GetElapsedTime(update.ReceivedTimestamp) < TimeSpan.Zero || !Authorized(update.Route)) return Refused(); + charge = checked(charge + 512 + OwnedDataSample.Estimate(update.Snapshot.Value)); + } + var admitted = false; + lock (_sync) + { + if (!_disposed && charge <= _maximumBytes - _pendingBytes) + { + admitted = true; + for (var i = 0; i < captured.Length; i++) + if (!_bindings.TryGetValue(Key(captured[i].Route), out bindings[i]!) || bindings[i].Route != captured[i].Route) + { admitted = false; break; } + if (admitted) _pendingBytes += charge; + } + } + if (!admitted) return Refused(); + } + catch (Exception error) when (error is ArgumentException or OverflowException) { return Refused(); } + + ProjectedPublicationBatch? batch = null; + try + { + var writes = captured.Select((update, i) => new ProjectedValueWrite(update.Route.Realm, update.Route.LocalIdentifier, + update.Route.ProjectionGeneration, update.Route.Serving, + update.Snapshot with { Value = OwnedDataSample.CopyLegacy(update.Snapshot.Value) }, update.OriginAgeBounds, + update.ReceivedTimestamp, WitnessFor(bindings[i], update), update.IsCompleteSnapshot)).ToArray(); + batch = new(writes, captured.Select(update => update.Route).ToArray(), Complete, ForwardToMux); + lock (_sync) + { + // Enqueue is the publication order boundary. Completed slots may be reused in + // ownership sets; their enumeration order never determines sample order. + batch.QueueSequence = checked(++_nextQueueSequence); + _pending.Add(batch); + } + if (!batch.IsValid || Host() is not { } host) { batch.AbortQueued(); return false; } + NotifyValues(host); + return true; + } + catch (Exception) + { + if (batch is not null) batch.AbortQueued(); + else { lock (_sync) _pendingBytes -= charge; Invalidate(captured); } + return false; + } + bool Refused() { Invalidate(captured); return false; } + void Complete(ProjectedPublicationBatch completed) + { lock (_sync) { _pending.Remove(completed); _sdkPending.Remove(completed); _pendingBytes -= charge; } } + } + + private void NotifyValues(IActorRef host) + { + lock (_sync) + { + if (_pending.Count == 0 || _valueWakePending && Equals(host, _valueHost)) return; + _valueHost = host; _valueWakePending = true; + } + host.Tell(new DriverHostActor.DrainProjectedValues(this)); + } + internal ProjectedPublicationBatch[] TakeQueuedValues(IActorRef host) + { + lock (_sync) + { + if (!Equals(host, _valueHost)) return []; + _valueWakePending = false; + return _pending.OrderBy(batch => batch.QueueSequence).Where(batch => batch.TryForward()).ToArray(); + } + } + + internal void EnqueueForSdk(ProjectedPublicationBatch batch, IActorRef sdk, IActorRef? mux) + { + var wake = false; + lock (_sync) + { + if (!batch.IsQueued) return; + _sdkPending.Add(batch); + if (!_sdkWakePending || !Equals(_sdkActor, sdk)) { _sdkActor = sdk; _sdkWakePending = true; wake = true; } + } + if (wake) sdk.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.DrainProjectedValues(this, mux)); + } + internal ProjectedPublicationBatch[] TakeSdkValues(IActorRef sdk) + { + lock (_sync) + { + if (!Equals(_sdkActor, sdk)) return []; + _sdkWakePending = false; + var result = _sdkPending.Where(batch => batch.IsQueued).OrderBy(batch => batch.QueueSequence).ToArray(); + _sdkPending.Clear(); + return result; + } + } + + private bool ForwardToMux(IActorRef mux, IReadOnlyList routes, IReadOnlyList writes) + { + ProjectedCoalescingMailbox mailbox; + lock (_sync) + { + if (_disposed) return false; + if (_muxMailbox is null || !Equals(_muxTarget, mux)) + { + _muxMailbox?.Dispose(); _muxTarget = mux; + _muxMailbox = new(mux, queue => new ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.DrainProjectedBatch(queue), _maximumBytes, _maximumRoutes); + } + mailbox = _muxMailbox; + } + try + { + var items = routes.Select((route, index) => (route.DependencyReference, + new ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags.DependencyMuxActor.ProjectedDependency(route.PublicationId.ToString("N"), route.DependencyReference, writes[index]), + checked(512L + OwnedDataSample.Estimate(writes[index].Snapshot.Value) + 2L * route.DependencyReference.Length))).ToArray(); + return mailbox.TryOffer(items); + } + catch (Exception error) when (error is ArgumentException or OverflowException or IndexOutOfRangeException) { return false; } + } + + public void Retire(ProjectedValueRoute route) + { + var removed = false; + lock (_sync) + if (_bindings.TryGetValue(Key(route), out var binding) && binding.Route == route) + { _bindings.Remove(Key(route)); _retiredReferences.Add(route.DependencyReference); removed = true; } + if (removed) NotifyRetirements(); + } + internal bool IsCurrent(ProjectedValueRoute route) + { + lock (_sync) + if (_disposed || !_bindings.TryGetValue(Key(route), out var binding) || binding.Route != route) return false; + return Authorized(route); + } + internal string[] TakeRetiredReferences(IActorRef host) + { + lock (_sync) + { + if (!Equals(host, _retirementHost)) return []; + var references = _retiredReferences.ToArray(); + _retiredReferences.Clear(); _retirementWakePending = false; + foreach (var reference in references) + if (ProjectedDataIds.TryParseDependencyReference(reference, out var realm, out var identifier) && + !_bindings.ContainsKey((realm, identifier)) && _trackedReferences.Remove(reference, out var bytes)) + _controlBytes -= bytes; + return references; + } + } + /// Rearms outstanding retirement after the owning actor starts or restarts. + public void HostActivated(IActorRef host) + { + lock (_sync) { _retirementHost = host; _retirementWakePending = false; _valueHost = host; _valueWakePending = false; } + NotifyRetirements(host); + NotifyValues(host); + } + private void NotifyRetirements(IActorRef? activated = null) + { + var host = activated ?? Host(); + if (host is null) return; + lock (_sync) + { + if (_retiredReferences.Count == 0 || _retirementWakePending && Equals(host, _retirementHost)) return; + _retirementHost = host; _retirementWakePending = true; + } + host.Tell(new DriverHostActor.DrainProjectedRetirements(this)); + } + public void Dispose() + { + ProjectedPublicationBatch[] pending; + ProjectedValueRoute[] routes; + lock (_sync) + { + if (_disposed) return; + _disposed = true; routes = _bindings.Values.Select(binding => binding.Route).ToArray(); _bindings.Clear(); + foreach (var route in routes) _retiredReferences.Add(route.DependencyReference); + pending = _pending.ToArray(); + } + _cleanup.Dispose(); + _muxMailbox?.Dispose(); + foreach (var batch in pending) batch.AbortQueued(); + NotifyRetirements(); + } +} + +/// Queued ownership may abort; physical sink ownership remains charged until completion. +internal sealed class ProjectedPublicationBatch +{ + internal long QueueSequence { get; set; } + private int _state; + private int _forwarded; + private IReadOnlyList _writes; + private IReadOnlyList _routes; + private readonly Action _release; + private readonly Func, IReadOnlyList, bool> _forward; + internal ProjectedPublicationBatch(IReadOnlyList writes, + IReadOnlyList routes, Action release, + Func, IReadOnlyList, bool> forward) + { _writes = writes; _routes = routes; _release = release; _forward = forward; } + internal bool ForwardToMux(IActorRef mux) => _forward(mux, Routes, Writes); + internal IReadOnlyList Writes => Volatile.Read(ref _writes); + internal IReadOnlyList Routes => Volatile.Read(ref _routes); + internal bool IsQueued => Volatile.Read(ref _state) == 0; + internal bool TryForward() => IsQueued && Interlocked.Exchange(ref _forwarded, 1) == 0; + internal bool IsValid => Volatile.Read(ref _state) != 2 && Writes.All(value => value.Proof.IsValid); + internal bool TryBegin() => Interlocked.CompareExchange(ref _state, 1, 0) == 0; + internal void AbortQueued() + { + if (Interlocked.CompareExchange(ref _state, 2, 0) != 0) return; + var writes = Interlocked.Exchange(ref _writes, Array.Empty()); + Interlocked.Exchange(ref _routes, Array.Empty()); + Invalidate(writes); _release(this); + } + internal void Complete(bool success) + { + if (Interlocked.CompareExchange(ref _state, 2, 1) != 1) return; + var writes = Interlocked.Exchange(ref _writes, Array.Empty()); + Interlocked.Exchange(ref _routes, Array.Empty()); + if (!success) Invalidate(writes); + _release(this); + } + private static void Invalidate(IEnumerable writes) { foreach (var value in writes) try { value.Proof.Invalidate(); } catch (Exception) { } } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/BrowseContinuationRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/BrowseContinuationRegistry.cs new file mode 100644 index 000000000..1b877e3bf --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/BrowseContinuationRegistry.cs @@ -0,0 +1,119 @@ +using System.Security.Cryptography; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// All authority and topology facts that scope one remote browse continuation. +public sealed record BrowseContinuationBinding(string PrincipalId, string ApiKeyId, string CredentialVersion, + string MappingId, long MappingRevision, DataView Parent, string? Filter, long LocalCatalogEpoch, ServingIdentity RemoteServing, + DateTimeOffset? CredentialExpiresUtc = null); + +/// Bounded, opaque and single-commit peer cursors. Aborting a reservation preserves its cursor. +public sealed class BrowseContinuationRegistry +{ + private sealed class Entry(BrowseContinuationBinding binding, string cursor, long started, TimeSpan lifetime) + { + internal readonly BrowseContinuationBinding Binding = binding; + internal readonly string Cursor = cursor; + internal readonly long Started = started; + internal readonly TimeSpan Lifetime = lifetime; + internal bool Reserved; + } + private readonly object _sync = new(); + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly int _maximum; + private readonly TimeProvider _clock; + public BrowseContinuationRegistry(int maximum, TimeProvider clock) + { + if (maximum <= 0) throw new ArgumentOutOfRangeException(nameof(maximum)); + _maximum = maximum; _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + } + public string Issue(BrowseContinuationBinding binding, string peerCursor, TimeSpan lifetime, long? requestStartedTimestamp = null) + { + ArgumentNullException.ThrowIfNull(binding); ArgumentException.ThrowIfNullOrWhiteSpace(peerCursor); + if (peerCursor.Length > 4096 || lifetime <= TimeSpan.Zero || lifetime > TimeSpan.FromSeconds(60)) throw new ArgumentOutOfRangeException(nameof(lifetime)); + binding.Parent.Validate(); binding.RemoteServing.Validate(true); + if (binding.MappingRevision <= 0 || binding.LocalCatalogEpoch <= 0 || string.IsNullOrWhiteSpace(binding.PrincipalId) || + string.IsNullOrWhiteSpace(binding.ApiKeyId) || string.IsNullOrWhiteSpace(binding.CredentialVersion) || string.IsNullOrWhiteSpace(binding.MappingId)) + throw new ArgumentException("Invalid continuation binding.", nameof(binding)); + lock (_sync) + { + Sweep(); + if (_entries.Count >= _maximum) throw new InvalidOperationException("Continuation capacity exhausted."); + var entry = new Entry(binding, peerCursor, requestStartedTimestamp ?? _clock.GetTimestamp(), lifetime); + if (Expired(entry)) throw new InvalidOperationException("Continuation lifetime has already elapsed."); + var token = NewToken(); _entries.Add(token, entry); return token; + } + } + public bool TryPrepare(string token, BrowseContinuationBinding binding, out PreparedBrowseContinuation? prepared) + { + prepared = null; + if (string.IsNullOrWhiteSpace(token) || token.Length != 64) return false; + lock (_sync) + { + Sweep(); + if (!_entries.TryGetValue(token, out var entry) || entry.Reserved || entry.Binding != binding) return false; + entry.Reserved = true; prepared = new(this, token, entry.Cursor); return true; + } + } + private void Sweep() + { + foreach (var pair in _entries.Where(pair => Expired(pair.Value)).ToArray()) _entries.Remove(pair.Key); + } + private bool Expired(Entry entry) + { + var age = _clock.GetElapsedTime(entry.Started, _clock.GetTimestamp()); + return age < TimeSpan.Zero || age >= entry.Lifetime || + entry.Binding.CredentialExpiresUtc is { } expiry && expiry <= _clock.GetUtcNow(); + } + private string NewToken() + { + string token; + do { token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)); } while (_entries.ContainsKey(token)); + return token; + } + internal bool Commit(string token, string? nextCursor, out string? nextToken) + { + nextToken = null; + lock (_sync) + { + if (!_entries.TryGetValue(token, out var entry) || !entry.Reserved || Expired(entry)) { _entries.Remove(token); return false; } + if (nextCursor is { Length: > 4096 } || nextCursor is { Length: 0 }) return false; + _entries.Remove(token); + if (nextCursor is not null) + { + nextToken = NewToken(); + _entries.Add(nextToken, new(entry.Binding, nextCursor, entry.Started, entry.Lifetime)); + } + return true; + } + } + internal void Abort(string token) + { + lock (_sync) if (_entries.TryGetValue(token, out var entry)) { if (Expired(entry)) _entries.Remove(token); else entry.Reserved = false; } + } + public void InvalidateMapping(string mappingId) + { + lock (_sync) foreach (var pair in _entries.Where(pair => string.Equals(pair.Value.Binding.MappingId, mappingId, StringComparison.OrdinalIgnoreCase)).ToArray()) _entries.Remove(pair.Key); + } +} + +/// A cursor reservation, committed only after the corresponding page is published. +public sealed class PreparedBrowseContinuation : IDisposable +{ + private readonly BrowseContinuationRegistry _owner; + private readonly string _token; + private int _finished; + internal PreparedBrowseContinuation(BrowseContinuationRegistry owner, string token, string remoteCursor) + { _owner = owner; _token = token; RemoteCursor = remoteCursor; } + public string RemoteCursor { get; } + public bool TryCommit(string? nextPeerCursor, out string? nextToken) + { + nextToken = null; + if (Interlocked.Exchange(ref _finished, 1) != 0) return false; + var committed = _owner.Commit(_token, nextPeerCursor, out nextToken); + if (!committed) _owner.Abort(_token); + return committed; + } + public void Dispose() { if (Interlocked.Exchange(ref _finished, 1) == 0) _owner.Abort(_token); } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs new file mode 100644 index 000000000..29166d5f6 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectedInterestOwner.cs @@ -0,0 +1,139 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Retained, deployment-authorized configured projection acquisition. +public interface IConfiguredProjectionLease : IAsyncDisposable { bool IsValid { get; } } +/// Discovers a configured projection from current deployed scope and verified origin pages. +public interface IConfiguredProjectionDiscovery { Task ResolveAsync(string reference, CancellationToken cancellationToken); } + +/// Bounded aggregate interests driven by a fixed worker pool and one shared retry sweep. +public sealed class ConfiguredProjectedInterestOwner : IProjectedDependencyInterestSink, IAsyncDisposable +{ + private sealed class Entry(string reference, long bytes) + { + internal readonly string Reference = reference; + internal readonly long Bytes = bytes; + internal bool Desired = true, Queued, Running; + internal IConfiguredProjectionLease? Lease; + internal CancellationTokenSource? InFlight; + } + private readonly object _sync = new(); + private readonly Dictionary _entries = new(StringComparer.Ordinal); + private readonly Queue _ready = new(); + private readonly SemaphoreSlim _available = new(0); + private readonly CancellationTokenSource _stop = new(); + private readonly IConfiguredProjectionDiscovery _discovery; + private readonly int _maxInterests; + private readonly long _maxBytes; + private readonly TimeProvider _clock; + private readonly Task[] _workers; + private readonly Task _sweep; + private long _bytes; + private bool _disposed; + public ConfiguredProjectedInterestOwner(IConfiguredProjectionDiscovery discovery, int maxInterests, + int maxConcurrentCalls = 4, long maxTransportBytes = 16 * 1024 * 1024, TimeProvider? clock = null) + { + _discovery = discovery ?? throw new ArgumentNullException(nameof(discovery)); + if (maxInterests <= 0 || maxConcurrentCalls <= 0 || maxTransportBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxInterests)); + _maxInterests = maxInterests; _maxBytes = maxTransportBytes; _clock = clock ?? TimeProvider.System; + _workers = Enumerable.Range(0, maxConcurrentCalls).Select(_ => Task.Run(WorkAsync)).ToArray(); + _sweep = Task.Run(SweepAsync); + } + private void Queue(Entry entry) + { + if (entry.Queued || entry.Running) return; + entry.Queued = true; _ready.Enqueue(entry); _available.Release(); + } + public void SetInterest(string projectedReference, bool active) + { + if (!ProjectedDataIds.TryParseDependencyReference(projectedReference, out _, out _)) return; + lock (_sync) + { + if (_disposed) return; + if (_entries.TryGetValue(projectedReference, out var old)) + { + if (old.Desired == active) return; + old.Desired = active; if (!active && old.InFlight is { } stop) _ = stop.CancelAsync(); + Queue(old); return; + } + var bytes = checked(256L + 2L * projectedReference.Length); + if (!active || _entries.Count >= _maxInterests || bytes > _maxBytes - _bytes) return; + var entry = new Entry(projectedReference, bytes); _entries.Add(projectedReference, entry); _bytes += bytes; Queue(entry); + } + } + private async Task WorkAsync() + { + while (true) + { + await _available.WaitAsync().ConfigureAwait(false); + Entry? entry; + lock (_sync) + { + if (_ready.Count == 0) { if (_disposed) return; continue; } + entry = _ready.Dequeue(); entry.Queued = false; entry.Running = true; + } + IConfiguredProjectionLease? old; + bool desired; + lock (_sync) { desired = !_disposed && entry.Desired; old = entry.Lease; entry.Lease = null; } + var oldValid = false; + try { oldValid = old is not null && old.IsValid; } catch (Exception) { } + if (old is not null && desired && oldValid) + { + lock (_sync) { entry.Lease = old; entry.Running = false; if (!entry.Desired || _disposed) Queue(entry); } + continue; + } + if (old is not null) { try { await old.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } } + CancellationTokenSource? operation = null; + lock (_sync) + { + desired = !_disposed && entry.Desired; + if (desired) { operation = new CancellationTokenSource(); entry.InFlight = operation; } + } + IConfiguredProjectionLease? acquired = null; + var canceled = false; + if (operation is not null) + { + try { acquired = await _discovery.ResolveAsync(entry.Reference, operation.Token).ConfigureAwait(false); } + catch (Exception) { } + lock (_sync) entry.InFlight = null; + canceled = operation.IsCancellationRequested; operation.Dispose(); + } + bool retain; + try { retain = !canceled && acquired is { IsValid: true }; } catch (Exception) { retain = false; } + lock (_sync) retain = retain && !_disposed && entry.Desired; + if (!retain && acquired is not null) { try { await acquired.DisposeAsync().ConfigureAwait(false); } catch (Exception) { } acquired = null; } + lock (_sync) + { + entry.Lease = acquired; entry.Running = false; + if (!entry.Desired || _disposed) + { + if (entry.Lease is not null) Queue(entry); + else { _entries.Remove(entry.Reference); _bytes -= entry.Bytes; if (_disposed && _entries.Count == 0) for (var i = 0; i < _workers.Length; i++) _available.Release(); } + } + } + } + } + private async Task SweepAsync() + { + try + { + using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), _clock); + while (await timer.WaitForNextTickAsync(_stop.Token).ConfigureAwait(false)) + lock (_sync) foreach (var entry in _entries.Values) if (entry.Desired) Queue(entry); + } + catch (OperationCanceledException) { } + } + public async ValueTask DisposeAsync() + { + lock (_sync) + { + if (_disposed) return; + _disposed = true; _stop.Cancel(); + foreach (var entry in _entries.Values) { entry.Desired = false; if (entry.InFlight is { } operation) _ = operation.CancelAsync(); Queue(entry); } + if (_entries.Count == 0) for (var i = 0; i < _workers.Length; i++) _available.Release(); + } + await _sweep.ConfigureAwait(false); await Task.WhenAll(_workers).ConfigureAwait(false); + _stop.Dispose(); _available.Dispose(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectionCapability.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectionCapability.cs new file mode 100644 index 000000000..9d09d41fa --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectionCapability.cs @@ -0,0 +1,22 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Internal deployment-scoped authority; never accepted from an SDK caller. +internal sealed class ConfiguredProjectionCapability(string mappingId, long revision, DataRealm realm, DataOperations operations, + IDataMappedCatalogAuthority sourceAuthority, Func current) +{ + internal string Nonce { get; } = Guid.NewGuid().ToString("N"); + internal bool Matches(string mapping, DataView view, IDataMappedCatalogAuthority? authority) + { + try + { + return current() && sourceAuthority.IsActive && (operations & (DataOperations.Browse | DataOperations.Subscribe)) == (DataOperations.Browse | DataOperations.Subscribe) && + string.Equals(mapping, mappingId, StringComparison.OrdinalIgnoreCase) && + string.Equals(view.MappingId, mapping, StringComparison.OrdinalIgnoreCase) && view.MappingRevision == revision && + view.Realm == realm && (authority is null || ReferenceEquals(authority, sourceAuthority)); + } + catch (Exception) { return false; } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectionDiscovery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectionDiscovery.cs new file mode 100644 index 000000000..c7de125d5 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConfiguredProjectionDiscovery.cs @@ -0,0 +1,93 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Discovers configured dependencies by walking only committed, placement-scoped origin pages. +public sealed class ConfiguredProjectionDiscovery : IConfiguredProjectionDiscovery +{ + private readonly ProjectedMappingDeploymentRuntime _placements; + private readonly IFederatedProjectionCatalog _catalog; + private readonly ProjectedNamespaceApplier _applier; + private readonly IProjectedNodeLookup _nodes; + private readonly ProjectedDataAccess _access; + private readonly DataBudget _budget; + private readonly int _maxPages; + public ConfiguredProjectionDiscovery(ProjectedMappingDeploymentRuntime placements, IFederatedProjectionCatalog catalog, + ProjectedNamespaceApplier applier, IProjectedNodeLookup nodes, ProjectedDataAccess access, DataBudget budget, int maxPages) + { + _placements = placements ?? throw new ArgumentNullException(nameof(placements)); _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _applier = applier ?? throw new ArgumentNullException(nameof(applier)); _nodes = nodes ?? throw new ArgumentNullException(nameof(nodes)); + _access = access ?? throw new ArgumentNullException(nameof(access)); _budget = budget ?? throw new ArgumentNullException(nameof(budget)); + budget.Validate(); if (maxPages <= 0) throw new ArgumentOutOfRangeException(nameof(maxPages)); _maxPages = maxPages; + } + public async Task ResolveAsync(string reference, CancellationToken cancellationToken) + { + if (!ProjectedDataIds.TryParseDependencyReference(reference, out var realm, out var identifier) || + !ProjectedDataIds.TryDecodeIdentifier(identifier, out var mappingId, out var target) || target is null) return null; + if (!_placements.TryAcquireConfiguredCapability(mappingId, realm, out var capability, out var placement) || capability is null || placement is null || + target.NamespaceUri != placement.Mapping.RemoteNamespaceUri || + !string.Equals(target.OriginClusterId, placement.Anchor.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase) || + !capability.Matches(mappingId, placement.Anchor, placement.Authority)) return null; + if (_catalog.TryResolveProjected(realm, identifier, out var existing) && existing is not null && + existing.OriginMetadata.View.Address == target && capability.Matches(mappingId, existing.Metadata.View, existing.Resolver.LocalAuthority) && + _nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), identifier, out var existingNode) && existingNode is { } readyNode && + _access.TryAcquireConfigured(readyNode, capability, out var readyDemand) && readyDemand is not null) + { + if (_access.StartSubscription(readyDemand, TimeSpan.FromMilliseconds(placement.Mapping.PublishingIntervalMilliseconds))) + return new Lease(_access, readyDemand, capability, existing); + readyDemand.Dispose(); + } + var anchorId = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address); + if (!_nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), anchorId, out var anchor) || anchor is not { } anchorNode) return null; + var started = _catalog.Clock.GetTimestamp(); + var queue = new Queue<(DataView View, NodeId Node, int Depth)>(); queue.Enqueue((placement.Anchor, anchorNode, 0)); + var visited = new HashSet { placement.Anchor.Address }; var pages = 0; var nodes = 0; + while (queue.TryDequeue(out var current)) + { + string? cursor = null; + do + { + cancellationToken.ThrowIfCancellationRequested(); + if (++pages > _maxPages || !capability.Matches(mappingId, placement.Anchor, placement.Authority)) return null; + var request = new ProjectedBrowseRequest(mappingId, current.View, null, cursor, null!, _budget, started) { ConfiguredCapability = capability }; + if (await _applier.ApplyPageResultAsync(request, current.Node, cancellationToken).ConfigureAwait(false) != ProjectionPageStatus.Ready) return null; + var page = _catalog.TryGetParent(request); + if (page.Status != ProjectionPageStatus.Ready || page.Lease is not { IsValid: true } || !capability.Matches(mappingId, placement.Anchor, placement.Authority)) return null; + if (page.ParentProof is { } rootProof && ProjectedCatalogCache.IsValueNode(rootProof.Metadata) && + rootProof.OriginMetadata.View.Address == target && capability.Matches(mappingId, rootProof.Metadata.View, rootProof.Resolver.LocalAuthority) && + _catalog.TryResolveProjected(realm, rootProof.LocalIdentifier, out var indexedRoot) && indexedRoot is not null && + _nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), rootProof.LocalIdentifier, out var rootNode) && rootNode is { } actualRoot && + _access.TryAcquireConfigured(actualRoot, capability, out var rootDemand) && rootDemand is not null) + { + if (_access.StartSubscription(rootDemand, TimeSpan.FromMilliseconds(placement.Mapping.PublishingIntervalMilliseconds))) + return new Lease(_access, rootDemand, capability, indexedRoot); + rootDemand.Dispose(); return null; + } + foreach (var proof in page.Items) + { + if (++nodes > placement.Mapping.MaxProjectionNodes || !capability.Matches(mappingId, proof.Metadata.View, proof.Resolver.LocalAuthority)) return null; + if (!_nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), proof.LocalIdentifier, out var node) || node is not { } child) return null; + if (proof.OriginMetadata.View.Address == target) + { + if (!_access.TryAcquireConfigured(child, capability, out var demand) || demand is null) return null; + if (!_access.StartSubscription(demand, TimeSpan.FromMilliseconds(placement.Mapping.PublishingIntervalMilliseconds))) { demand.Dispose(); return null; } + return new Lease(_access, demand, capability, proof); + } + if (current.Depth + 1 < placement.Mapping.MaxProjectionDepth && visited.Add(proof.OriginMetadata.View.Address)) + queue.Enqueue((proof.Metadata.View, child, current.Depth + 1)); + } + cursor = page.Continuation; + if (page.Complete != (cursor is null)) return null; + } while (cursor is not null); + } + return null; + } + private sealed class Lease(ProjectedDataAccess access, IProjectedDemandLease demand, ConfiguredProjectionCapability capability, ProjectedNodeProof proof) : IConfiguredProjectionLease + { + private int _disposed; + public bool IsValid => Volatile.Read(ref _disposed) == 0 && demand.IsValid && capability.Matches(proof.Metadata.View.MappingId!, proof.Metadata.View, proof.Resolver.LocalAuthority); + public ValueTask DisposeAsync() => Interlocked.Exchange(ref _disposed, 1) == 0 ? access.DisposeConfiguredAsync(demand) : ValueTask.CompletedTask; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs index 2c9d5253f..1cd4b3caa 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataConnectionDeploymentRuntime.cs @@ -467,10 +467,17 @@ public sealed class DataConnectionDeploymentLease : IDataConnection, IDisposable public async Task SubscribeAsync(CancellationToken cancellationToken) { Check(DataOperations.Subscribe); var stream = await _inner.SubscribeAsync(cancellationToken).ConfigureAwait(false); - try { Check(DataOperations.Subscribe); return new ScopedSubscription(this, stream); } + try { Check(DataOperations.Subscribe); return stream is IDataSubscriptionProvenance provenance + ? new ProvenancedScopedSubscription(this, stream, provenance.Serving) + : new ScopedSubscription(this, stream); } catch { await stream.DisposeAsync().ConfigureAwait(false); throw; } } - private sealed class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription + private sealed class ProvenancedScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner, ServingIdentity serving) + : ScopedSubscription(owner, inner), IDataSubscriptionProvenance + { + public ServingIdentity Serving { get; } = serving; + } + private class ScopedSubscription(DataConnectionDeploymentLease owner, IDataSubscription inner) : IDataSubscription { public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs index ed17f743c..2abff3a48 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs @@ -72,7 +72,8 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, FuncUses the actual deployed, role-guarded connection registry for projection work. +public sealed class DeployedGrpcDataConnectionSource(DataConnectionDeploymentRuntime runtime) : IGrpcDataAdapterConnectionSource +{ + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!runtime.TryAcquire(connectionId, out var lease) || lease is null) + return ValueTask.FromResult(null); + if (cancellationToken.IsCancellationRequested) + { + lease.Dispose(); + cancellationToken.ThrowIfCancellationRequested(); + } + return ValueTask.FromResult(new Borrowed(lease)); + } + + private sealed class Borrowed(DataConnectionDeploymentLease lease) : IGrpcDataAdapterConnectionLease + { + public Core.Abstractions.DataConnections.IDataConnection Connection => lease.Connection; + public CancellationToken CancellationToken => lease.CancellationToken; + public ValueTask DisposeAsync() => lease.DisposeAsync(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs new file mode 100644 index 000000000..fcc7cef97 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/FederatedBrowseService.cs @@ -0,0 +1,104 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Combines the remote metadata lease with local catalog and connection retirement fences. +internal sealed class BoundProjectionLease(MetadataAuthorityLease remote, CancellationToken route, + IDataMappedCatalogAuthority local, ProjectedCatalogCache cache, string mapping, long generation, Func bindingCurrent) : IDataAuthorizationLease +{ + public ServingIdentity Serving => remote.Serving; + public bool IsValid => !route.IsCancellationRequested && local.IsActive && remote.IsValid && bindingCurrent() && cache.IsCurrentGeneration(mapping, generation); +} + +/// A page holds its physical connection lease until the caller commits or aborts it. +internal sealed class PreparedPage : IProjectedPreparedPage +{ + private readonly ProjectedCatalogCache? _cache; + private readonly BrowseContinuationRegistry? _cursors; + private readonly ProjectedBrowseRequest? _request; + private readonly BrowseContinuationBinding? _binding; + private readonly PreparedBrowseContinuation? _cursor; + private readonly string? _nextPeerCursor; + private readonly SharedPageConnection? _connection; + private readonly TimeProvider? _clock; + private readonly TimeSpan _cursorLifetime; + private readonly long _cursorStart; + private readonly int _maximumMappingNodes; + private int _finished; + private ProjectedParentSnapshot _snapshot; + private PreparedPage(ProjectionPageStatus status) => _snapshot = new(status, [], false, null, 0); + internal PreparedPage(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors, ProjectedBrowseRequest request, + ProjectedParentSnapshot snapshot, BrowseContinuationBinding binding, PreparedBrowseContinuation? cursor, string? nextPeerCursor, + IGrpcDataAdapterConnectionLease connection, SemaphoreSlim slots, TimeProvider clock, TimeSpan cursorLifetime, int maximumMappingNodes) + { + _cache = cache; _cursors = cursors; _request = request; _snapshot = snapshot; _binding = binding; + _cursor = cursor; _nextPeerCursor = nextPeerCursor; _connection = new SharedPageConnection(connection, slots); _clock = clock; + _cursorLifetime = cursorLifetime; _cursorStart = request.RequestStartedTimestamp; _maximumMappingNodes = maximumMappingNodes; + } + private PreparedPage(PreparedPage original, ProjectedBrowseRequest request) + { + _cache = original._cache; _cursors = original._cursors; _request = request; _snapshot = original._snapshot; _binding = original._binding; + _nextPeerCursor = original._nextPeerCursor; _connection = original._connection; _connection!.AddReference(); + _clock = original._clock; _cursorLifetime = original._cursorLifetime; _cursorStart = original._cursorStart; _maximumMappingNodes = original._maximumMappingNodes; + } + internal static PreparedPage Failed(ProjectionPageStatus status) => new(status); + internal PreparedPage CloneForWaiter(ProjectedBrowseRequest request) => _connection is null + ? Failed(_snapshot.Status) : new PreparedPage(this, request); + public ProjectedParentSnapshot Snapshot => _snapshot; + public bool TryCommit() + { + if (Interlocked.Exchange(ref _finished, 1) != 0 || _cache is null || _request is null || _binding is null || _cursors is null || _clock is null) return false; + try + { + if (_connection!.CancellationToken.IsCancellationRequested || _snapshot.Lease is not { IsValid: true } || + _clock.GetElapsedTime(_request.RequestStartedTimestamp, _clock.GetTimestamp()) >= _request.Budget.Timeout) return false; + var ok = _cache.TryPublish(_request, _snapshot, () => + { + if (_cursor is not null) return (_cursor.TryCommit(_nextPeerCursor, out var next), next); + if (_nextPeerCursor is null) return (true, null); + // The lease deadline is measured from the original RPC start, not reply receipt. + var lifetime = _cursorLifetime > TimeSpan.FromSeconds(60) ? TimeSpan.FromSeconds(60) : _cursorLifetime; + return (true, _cursors.Issue(_binding, _nextPeerCursor, lifetime, _cursorStart)); + }, out var committed, _maximumMappingNodes); + if (ok) _snapshot = committed!; + return ok; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + finally { _cursor?.Dispose(); Release(); } + } + public void Dispose() + { + if (Interlocked.Exchange(ref _finished, 1) != 0) return; + _cursor?.Dispose(); Release(); + } + private void Release() => _connection?.Release(); + internal async Task DisposeAndWaitAsync() + { + Dispose(); + if (_connection is not null) await _connection.Closed.ConfigureAwait(false); + } +} + +/// Counts every prepared page that still owns one shared physical connection. +internal sealed class SharedPageConnection(IGrpcDataAdapterConnectionLease connection, SemaphoreSlim slots) +{ + private int _references = 1; + private readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal Task Closed => _closed.Task; + public CancellationToken CancellationToken => connection.CancellationToken; + public void AddReference() + { + if (Interlocked.Increment(ref _references) <= 1) throw new ObjectDisposedException(nameof(SharedPageConnection)); + } + public void Release() + { + if (Interlocked.Decrement(ref _references) == 0) _ = CloseAsync(); + } + private async Task CloseAsync() + { + try { await connection.DisposeAsync().ConfigureAwait(false); } + catch (Exception) { } + finally { slots.Release(); _closed.TrySetResult(); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs index dd5b051e5..e92b41e89 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataConnection.cs @@ -225,10 +225,10 @@ public sealed class GrpcDataConnection : IDataConnection { var channel = await ChannelAsync(endpoint, ct).ConfigureAwait(false); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, _scope.CancellationToken, channel.Retired.Token, _shutdown.Token); - var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 2 }, + var response = await channel.Client.GetCapabilitiesAsync(new W.CapabilitiesRequest { ProtocolMajor = 1, ProtocolMinor = 3 }, Options(channel, start, budget, linked.Token)).ResponseAsync.ConfigureAwait(false); var caps = DataProtoMapper.DecodeCapabilities(response, new DataDecodeLimits(budget.MaxItems, _maxMessageBytes)); - if (!caps.ResponseServingIdentity || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) || + if (!caps.ResponseServingIdentity || (write && (caps.ProtocolMinor < 3 || !caps.WriteServingGenerationEnforced)) || caps.Serving.ServingGeneration <= 0 || !ClusterEndpointSelector.IsEligible(Target, caps, write) || Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId)) throw new InvalidOperationException("Endpoint is not an authenticated ready target."); linked.Token.ThrowIfCancellationRequested(); @@ -272,8 +272,13 @@ public sealed class GrpcDataConnection : IDataConnection } finally { if (admitted) _unaryCapacity.Release(); ExitWork(); } } + private static bool SupportsWrites(DataCapabilities caps) => caps.ProtocolMinor >= 3 && caps.WriteServingGenerationEnforced; + private static DataMetadata ExposeMetadata(DataMetadata metadata, ServingIdentity serving, DataCapabilities caps) => + SupportsWrites(caps) ? metadata with { Serving = serving } : metadata with + { Serving = serving, Writable = false, AllowedOperations = metadata.AllowedOperations & ~DataOperations.Write }; public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => - QueryAsync(budget, (selected, _, _) => Task.FromResult(selected.Capabilities), cancellationToken); + QueryAsync(budget, (selected, _, _) => Task.FromResult(SupportsWrites(selected.Capabilities) ? selected.Capabilities : + selected.Capabilities with { Operations = selected.Capabilities.Operations & ~DataOperations.Write }), cancellationToken); public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => QueryAsync(request.Budget, async (selected, budget, options) => { @@ -282,9 +287,11 @@ public sealed class GrpcDataConnection : IDataConnection if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch || lease.AuthorityEpoch != selected.Capabilities.Serving.AuthorityEpoch || lease.Duration > selected.Capabilities.Limits.MaxMetadataLease)) throw new InvalidOperationException("Browse lease has unexpected authority or duration."); - if (result.Parent != request.Parent || result.Items.Any(x => !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase))) + if (result.Parent != request.Parent || result.Items.Any(x => x.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase))) throw new InvalidOperationException("Browse response has unexpected provenance."); - Verify(wire.Serving, selected); return result; + Verify(wire.Serving, selected); + var serving = DataProtoMapper.DecodeServing(wire.Serving); + return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() }; }, cancellationToken); public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => QueryAsync(request.Budget, async (selected, budget, options) => @@ -292,9 +299,11 @@ public sealed class GrpcDataConnection : IDataConnection var wire = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false); Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeMetadataResponse(wire, Limits(budget, selected.Capabilities)); if (result.Count != request.Views.Count || result.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || - x.Value is not null && x.Value.View.Address != request.Views[i].Address).Any()) + x.Value is not null && (x.Value.View.Address != request.Views[i].Address || x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch)).Any()) throw new InvalidOperationException("Metadata response has unexpected items."); - Verify(wire.Serving, selected); return result; + Verify(wire.Serving, selected); + var serving = DataProtoMapper.DecodeServing(wire.Serving); + return (IReadOnlyList>)result.Select(x => x.Value is null ? x : x with { Value = ExposeMetadata(x.Value, serving, selected.Capabilities) }).ToArray(); }, cancellationToken); public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) { @@ -353,30 +362,61 @@ public sealed class GrpcDataConnection : IDataConnection catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException or TimeoutException) { continue; } using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, selected.Channel.Retired.Token, _shutdown.Token); + // Caller-bound generations are strict: never replace any supplied precondition or rebind. + var strictMismatch = eligible.Where(i => request.Items[i].ExpectedServingGeneration is { } generation && + (generation <= 0 || generation != selected.Capabilities.Serving.ServingGeneration || + request.Items[i].ExpectedCatalogRevision != selected.Capabilities.Serving.CatalogEpoch || + request.Items[i].ExpectedServingIncarnation != selected.Capabilities.Serving.Incarnation)).ToArray(); + foreach (var index in strictMismatch) + results[index] = new(request.Items[index].CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Serving precondition mismatch.")); + eligible = eligible.Except(strictMismatch).ToArray(); + if (eligible.Length == 0) { eligible = strictMismatch; continue; } var items = eligible.Select(i => request.Items[i]).ToArray(); + var deferred = strictMismatch.ToList(); if (attempted) { - // A retry needs fresh, authenticated metadata from the new primary. Never infer a - // catalog revision from its serving epoch or reuse the old node incarnation. - try + // Only legacy retries require fresh metadata. A failed lookup must not suppress + // independently matching, not-yet-dispatched strict items on this endpoint. + var legacy = Enumerable.Range(0, items.Length) + .Where(i => request.Items[eligible[i]].ExpectedServingGeneration is null).ToArray(); + var metadataValid = legacy.Length == 0; + if (legacy.Length > 0) { - var remaining = Remaining(start, request.Budget); - var budget = request.Budget with { Timeout = remaining }; - var metadataRequest = new MetadataRequest(items.Select(x => x.View).ToArray(), budget); - var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest), - Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false); - Verify(wireMetadata.Serving, selected); - var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities)); - if (metadata.Count != items.Length || metadata.Where((x, i) => x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || - x.Status != DataItemStatus.Good || x.Value is null || x.Value.View.Address != items[i].View.Address || - !x.Value.Writable || (x.Value.AllowedOperations & DataOperations.Write) == 0).Any()) continue; - linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected); - items = items.Select((x, i) => x with { ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision, - ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }).ToArray(); + try + { + var remaining = Remaining(start, request.Budget); + var budget = request.Budget with { Timeout = remaining }; + var metadataRequest = new MetadataRequest(legacy.Select(i => items[i].View).ToArray(), budget); + var wireMetadata = await selected.Channel.Client.GetMetadataAsync(DataProtoMapper.EncodeMetadataRequest(metadataRequest), + Options(selected.Channel, start, request.Budget, linked.Token)).ResponseAsync.ConfigureAwait(false); + Verify(wireMetadata.Serving, selected); + var metadata = DataProtoMapper.DecodeMetadataResponse(wireMetadata, Limits(budget, selected.Capabilities)); + metadataValid = metadata.Count == legacy.Length && !metadata.Where((x, i) => + x.CorrelationId != i.ToString(System.Globalization.CultureInfo.InvariantCulture) || + x.Status != DataItemStatus.Good || x.Value is null || x.Value.View != items[legacy[i]].View || + x.Value.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !x.Value.Writable || + (x.Value.AllowedOperations & DataOperations.Write) == 0).Any(); + if (metadataValid) + { + linked.Token.ThrowIfCancellationRequested(); Verify(wireMetadata.Serving, selected); + for (var i = 0; i < legacy.Length; i++) items[legacy[i]] = items[legacy[i]] with { + ExpectedCatalogRevision = metadata[i].Value!.CatalogRevision, + ExpectedServingIncarnation = selected.Capabilities.Serving.Incarnation }; + } + } + catch (Exception ex) when (ex is RpcException or HttpRequestException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException) + { if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break; } + } + if (!metadataValid) + { + deferred.AddRange(legacy.Select(i => eligible[i])); + var strict = Enumerable.Range(0, items.Length).Except(legacy).ToArray(); + eligible = strict.Select(i => eligible[i]).ToArray(); + items = strict.Select(i => items[i]).ToArray(); + if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; } } - catch (Exception ex) when (ex is RpcException or InvalidOperationException or ArgumentException or TimeoutException or OperationCanceledException) - { if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested) break; continue; } } + items = items.Select(x => x.ExpectedServingGeneration is null ? x with { ExpectedServingGeneration = selected.Capabilities.Serving.ServingGeneration } : x).ToArray(); var elapsed = Clock.GetElapsedTime(start); var live = Enumerable.Range(0, items.Length).Where(i => items[i].RemainingBudget > elapsed).ToArray(); foreach (var i in Enumerable.Range(0, items.Length).Except(live)) @@ -384,7 +424,7 @@ public sealed class GrpcDataConnection : IDataConnection new(DataWriteState.RejectedBeforeDispatch, 0x800A0000u, "Item budget expired before dispatch.")); eligible = live.Select(i => eligible[i]).ToArray(); items = live.Select(i => items[i] with { RemainingBudget = items[i].RemainingBudget - elapsed }).ToArray(); - if (eligible.Length == 0) break; + if (eligible.Length == 0) { eligible = deferred.ToArray(); continue; } var dispatchStarted = false; try { @@ -402,7 +442,7 @@ public sealed class GrpcDataConnection : IDataConnection VerifyWriteEnvelope(wire.Serving, selected, decoded); linked.Token.ThrowIfCancellationRequested(); for (var i = 0; i < eligible.Length; i++) results[eligible[i]] = decoded[i]; - eligible = eligible.Where((_, i) => decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch).ToArray(); + eligible = deferred.Concat(eligible.Where((index, i) => request.Items[index].ExpectedServingGeneration is null && decoded[i].Outcome.State == DataWriteState.RejectedBeforeDispatch)).ToArray(); attempted = true; } catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException or TimeoutException) @@ -410,7 +450,8 @@ public sealed class GrpcDataConnection : IDataConnection if (dispatchStarted) foreach (var index in eligible) results[index] = new(request.Items[index].CorrelationId, new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown.")); - break; + if (cancellationToken.IsCancellationRequested || _scope.CancellationToken.IsCancellationRequested || _shutdown.IsCancellationRequested) break; + eligible = dispatchStarted ? deferred.ToArray() : deferred.Concat(eligible).ToArray(); } } if (!attempted && eligible.Length > 0) ProbeFailed(); @@ -504,8 +545,9 @@ public sealed class GrpcDataConnection : IDataConnection AsyncDuplexStreamingCall call, Selected selected, CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands, TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func claimEpoch, Action? observePending, - Func? afterTimerCancelled, Action release) : IDataSubscription + Func? afterTimerCancelled, Action release) : IDataSubscription, IDataSubscriptionProvenance { + public ServingIdentity Serving { get; } = selected.Capabilities.Serving; private readonly SemaphoreSlim _send = new(1, 1); private readonly Task _headersReceipt = call.ResponseHeadersAsync; private Dictionary _handles = new(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs new file mode 100644 index 000000000..a18407679 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/GrpcDataDriverAdapter.cs @@ -0,0 +1,325 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A connection lease remains owned until every operation using it has physically completed. +public interface IGrpcDataAdapterConnectionLease : IAsyncDisposable +{ + IDataConnection Connection { get; } + CancellationToken CancellationToken { get; } +} + +public interface IGrpcDataAdapterConnectionSource +{ + ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken); +} + +/// Trusted route and its live authority, supplied by the local projection catalog. +public sealed record GrpcDataAdapterRoute(string DependencyReference, DataView View, DataMetadata Metadata, + ServingIdentity Serving, IDataAuthorizationLease Lease, long ProjectionGeneration, TimeSpan MaximumSampleAge = default); + +public interface IGrpcDataAdapterRouteSource +{ + bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route); +} + +/// A publication route is trusted local placement, never a remote path inferred by the publisher. +public sealed record ProjectedValueRoute(string DriverInstanceId, string DependencyReference, DataRealm Realm, + string LocalIdentifier, long ProjectionGeneration, ServingIdentity Serving, Guid PublicationId = default); + +public sealed record ProjectedValueUpdate(ProjectedValueRoute Route, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds, + long ReceivedTimestamp, IProjectedSamplePublicationProof SourceProof, bool IsCompleteSnapshot = false, + TimeSpan? MaximumSampleAge = null); + +public interface IProjectedValuePublisher +{ + bool TryBind(ProjectedValueRoute route); + bool TryPublish(IReadOnlyList updates); + void Retire(ProjectedValueRoute route); +} + +/// A driver facade over a configured, scoped data connection. +public sealed class GrpcDataDriverAdapter : IDriver, IBatchSubscribable, IWriteOutcomeCapability +{ + private readonly string _connectionId; + private readonly IGrpcDataAdapterConnectionSource _source; + private readonly IGrpcDataAdapterRouteSource _routes; + private readonly IProjectedValuePublisher? _publisher; + private readonly object _sync = new(); + private readonly HashSet _subscriptions = []; + private bool _running; + private long _epoch; + + public GrpcDataDriverAdapter(string driverInstanceId, string connectionId, + IGrpcDataAdapterConnectionSource source, IGrpcDataAdapterRouteSource routes, IProjectedValuePublisher? publisher = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId); + ArgumentException.ThrowIfNullOrWhiteSpace(connectionId); + DriverInstanceId = driverInstanceId; + _connectionId = connectionId; + _source = source ?? throw new ArgumentNullException(nameof(source)); + _routes = routes ?? throw new ArgumentNullException(nameof(routes)); + _publisher = publisher; + } + + public string DriverInstanceId { get; } + public string DriverType => "GrpcData"; + public event EventHandler? OnDataChange; + public event EventHandler? OnDataChangeBatch; + public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + lock (_sync) _running = true; + return Task.CompletedTask; + } + public async Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) + { + await ShutdownAsync(cancellationToken).ConfigureAwait(false); + await InitializeAsync(driverConfigJson, cancellationToken).ConfigureAwait(false); + } + public DriverHealth GetHealth() { lock (_sync) return new(_running ? DriverState.Healthy : DriverState.Unknown, null, null); } + public async Task ShutdownAsync(CancellationToken cancellationToken) + { + Subscription[] pending; + lock (_sync) { _running = false; pending = _subscriptions.ToArray(); _subscriptions.Clear(); } + foreach (var subscription in pending) await subscription.CloseAsync().ConfigureAwait(false); + } + + public async Task> WriteWithOutcomesAsync(IReadOnlyList writes, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(writes); + var results = new DataWriteOutcome[writes.Count]; + for (var i = 0; i < writes.Count; i++) + { + var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, 0x803B0000u, "Projection is unavailable."); + results[i] = rejected; + lock (_sync) { if (!_running) continue; } + if (!_routes.TryResolve(writes[i].FullReference, out var route) || route is null || !Valid(route)) continue; + await using var lease = await _source.AcquireAsync(_connectionId, cancellationToken).ConfigureAwait(false); + if (lease is null || lease.CancellationToken.IsCancellationRequested || !Valid(route)) continue; + using var value = OwnedDataSample.Copy(writes[i].Value); + var id = Guid.NewGuid().ToString("N"); + var item = new WriteItem(id, Guid.NewGuid().ToString("N"), route.View, value, + route.Serving.CatalogEpoch, route.Serving.Incarnation, TimeSpan.FromSeconds(5), route.Serving.ServingGeneration); + try + { + var response = await lease.Connection.WriteAsync(new WriteBatch([item], new(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024)), cancellationToken).ConfigureAwait(false); + results[i] = response.Count == 1 && response[0].CorrelationId == id ? response[0].Outcome : + new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Uncorrelated write response."); + } + catch (Exception) when (!cancellationToken.IsCancellationRequested) + { results[i] = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write completion is unknown."); } + } + return results; + } + + private static object DecodeArray(DataValue value) + { + var elements = value.GetArray(); + return value.ArrayElementKind switch + { + DataValueKind.Boolean => elements.Cast().ToArray(), DataValueKind.Int8 => elements.Cast().ToArray(), + DataValueKind.UInt8 => elements.Cast().ToArray(), DataValueKind.Int16 => elements.Cast().ToArray(), + DataValueKind.UInt16 => elements.Cast().ToArray(), DataValueKind.Int32 => elements.Cast().ToArray(), + DataValueKind.UInt32 => elements.Cast().ToArray(), DataValueKind.Int64 => elements.Cast().ToArray(), + DataValueKind.UInt64 => elements.Cast().ToArray(), DataValueKind.Float => elements.Cast().ToArray(), + DataValueKind.Double => elements.Cast().ToArray(), DataValueKind.String => elements.Cast().ToArray(), + DataValueKind.Timestamp => elements.Cast().Select(timestamp => timestamp.UtcDateTime).ToArray(), + _ => throw new InvalidOperationException("Unsupported projected array element type.") + }; + } + + private static bool Valid(GrpcDataAdapterRoute route) => route.Lease.IsValid && route.Lease.Serving == route.Serving && + route.Serving.ServingGeneration > 0 && route.Metadata.View == route.View; + + public async Task SubscribeAsync(IReadOnlyList fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(fullReferences); + lock (_sync) { if (!_running) throw new InvalidOperationException("Driver is stopped."); } + var routes = fullReferences.Select(reference => _routes.TryResolve(reference, out var route) && route is not null && Valid(route) + ? route : throw new InvalidOperationException("Projection is unavailable.")).ToArray(); + if (routes.Length == 0 || routes.Any(r => r.Serving != routes[0].Serving)) throw new InvalidOperationException("Incompatible projection authority."); + var lease = await _source.AcquireAsync(_connectionId, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("Connection is unavailable."); + IDataSubscription? stream = null; + try + { + stream = await lease.Connection.SubscribeAsync(cancellationToken).ConfigureAwait(false); + if (stream is not IDataSubscriptionProvenance proof || proof.Serving != routes[0].Serving || routes.Any(r => !Valid(r))) + throw new InvalidOperationException("Subscription authority changed."); + var epoch = Interlocked.Increment(ref _epoch); + var id = Guid.NewGuid().ToString("N"); + var subscription = new Subscription(this, lease, stream, routes, id, epoch); + lock (_sync) + { + if (!_running) throw new InvalidOperationException("Driver is stopped."); + _subscriptions.Add(subscription); + } + try + { + var settings = new DataSubscriptionSettings(publishingInterval, publishingInterval, DataChangeTrigger.StatusValueTimestamp, null); + var items = routes.Select((route, index) => new DataSubscriptionItem(index.ToString(System.Globalization.CultureInfo.InvariantCulture), route.View, settings)).ToArray(); + await stream.SendAsync(new OpenSubscription(id, epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), items, false, + TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), items.Length, 4 * 1024 * 1024)), cancellationToken).ConfigureAwait(false); + subscription.Start(); + return subscription; + } + catch { lock (_sync) _subscriptions.Remove(subscription); await subscription.CloseAsync().ConfigureAwait(false); stream = null; lease = null!; throw; } + } + catch + { + if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); + if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) + { + if (handle is not Subscription subscription || subscription.Owner != this) throw new ArgumentException("Unknown subscription.", nameof(handle)); + lock (_sync) _subscriptions.Remove(subscription); + await subscription.CloseAsync().ConfigureAwait(false); + } + + private sealed class Subscription(GrpcDataDriverAdapter owner, IGrpcDataAdapterConnectionLease lease, + IDataSubscription stream, GrpcDataAdapterRoute[] routes, string id, long epoch) : ISubscriptionHandle + { + private readonly CancellationTokenSource _stop = CancellationTokenSource.CreateLinkedTokenSource(lease.CancellationToken); + private readonly object _closeSync = new(); + private Task? _close; + private Task? _reader; + private readonly SampleProof _proof = new(lease.Connection.Clock, routes, lease.CancellationToken); + private readonly List _bound = []; + public GrpcDataDriverAdapter Owner => owner; + public string DiagnosticId => id; + public void Start() => _reader = ReadAsync(); + public Task CloseAsync() { lock (_closeSync) return _close ??= CloseCoreAsync(); } + private async Task CloseCoreAsync() + { + _proof.Invalidate(); + _stop.Cancel(); + ProjectedValueRoute[] retired; + lock (_closeSync) { retired = _bound.ToArray(); _bound.Clear(); } + foreach (var route in retired) owner._publisher?.Retire(route); + try { await stream.DisposeAsync().ConfigureAwait(false); } + finally + { + try { if (_reader is not null) await _reader.ConfigureAwait(false); } + catch (OperationCanceledException) { } + finally { await lease.DisposeAsync().ConfigureAwait(false); _stop.Dispose(); } + } + } + private async Task ReadAsync() + { + var handles = new Dictionary(); + long sequence = 0; + var snapshot = false; + var ready = false; + var pending = new List(); + long pendingBytes = 0; + var publishedRoutes = new Dictionary(StringComparer.Ordinal); + foreach (var route in routes) + { + if (!ProjectedDataIds.TryParseDependencyReference(route.DependencyReference, out var realm, out var identifier)) + { _proof.Invalidate(); return; } + publishedRoutes[route.DependencyReference] = new(owner.DriverInstanceId, route.DependencyReference, realm, + identifier, route.ProjectionGeneration, route.Serving, Guid.NewGuid()); + } + bool Publish(IReadOnlyList updates) + { + if (owner._publisher is null || !_proof.IsValid) { _proof.Invalidate(); return false; } + if (!owner._publisher.TryPublish(updates)) { _proof.Invalidate(); return false; } + if (!_proof.IsValid) return false; + var legacy = updates.Select(update => new DataChangeItem(update.Route.DependencyReference, update.Snapshot)).ToArray(); + if (legacy.Length > 0) + { + owner.OnDataChangeBatch?.Invoke(owner, new(this, legacy)); + foreach (var item in legacy) owner.OnDataChange?.Invoke(owner, new(this, item.FullReference, item.Snapshot)); + } + return _proof.IsValid; + } + try + { + await foreach (var frame in stream.ReadAllAsync(_stop.Token).ConfigureAwait(false)) + { + try + { + if (frame.SubscriptionId != id || frame.StreamEpoch != epoch || frame.Sequence <= sequence || routes.Any(r => !Valid(r))) break; + sequence = frame.Sequence; + if (frame is DataSubscriptionAck ack) + { + foreach (var item in ack.Items) + if (item.Status == DataItemStatus.Good && item.Handle is not null && int.TryParse(item.ClientItemId, out var index) && index >= 0 && index < routes.Length) + handles[item.Handle] = routes[index]; + } + else if (frame is DataSubscriptionControl control) + { + if (control.CatalogEpoch != routes[0].Serving.CatalogEpoch || control.AuthorityEpoch != routes[0].Serving.AuthorityEpoch) break; + if (control.Kind == DataStreamControlKind.SnapshotBegin) { snapshot = true; ready = false; pending.Clear(); pendingBytes = 0; } + else if (control.Kind == DataStreamControlKind.SnapshotEnd && snapshot) + { + snapshot = false; + foreach (var projected in publishedRoutes.Values) + { + if (owner._publisher is null || !owner._publisher.TryBind(projected)) { _proof.Invalidate(); break; } + lock (_closeSync) _bound.Add(projected); + if (!_proof.IsValid) + { + lock (_closeSync) _bound.Remove(projected); + owner._publisher.Retire(projected); + break; + } + } + if (!_proof.IsValid || (pending.Count > 0 && !Publish(pending.Select(update => + update with { IsCompleteSnapshot = true }).ToArray()))) break; + pending.Clear(); pendingBytes = 0; ready = true; + } + else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) break; + } + else if (frame is DataSubscriptionValues values && (snapshot || ready)) + { + var batch = new List(); + foreach (var item in values.Items) + { + if (!handles.TryGetValue(item.Handle, out var route) || item.Sample.Serving != route.Serving || + !Valid(route) || item.Readiness != DataReadiness.Ready) { _proof.Invalidate(); break; } + var value = item.Sample.Value; + if (value.Kind == DataValueKind.Array) { _proof.Invalidate(); break; } + item.AgeBounds.Validate(); + var bytes = value.EstimatedRetainedBytes; + pendingBytes = checked(pendingBytes + bytes); + if (pendingBytes > 4 * 1024 * 1024 || pending.Count + batch.Count >= 4096) { _proof.Invalidate(); break; } + object? payload = value.Kind switch { DataValueKind.Null => null, DataValueKind.Bytes => value.GetBytes().ToArray(), + DataValueKind.Array => DecodeArray(value), _ => value.GetScalar() }; + var legacy = new DataValueSnapshot(payload, item.Sample.StatusCode, + item.Sample.SourceTimestampUtc?.UtcDateTime, item.Sample.ServerTimestampUtc?.UtcDateTime); + batch.Add(new(publishedRoutes[route.DependencyReference], legacy, item.AgeBounds, + lease.Connection.Clock.GetTimestamp(), _proof, MaximumSampleAge: route.MaximumSampleAge)); + } + if (!_proof.IsValid) break; + if (snapshot) pending.AddRange(batch); + else + { + if (batch.Count > 0 && !Publish(batch)) break; + pendingBytes = 0; + } + } + } + finally { (frame as IDisposable)?.Dispose(); } + } + } + catch (OperationCanceledException) when (_stop.IsCancellationRequested) { } + finally { if (!_stop.IsCancellationRequested) _proof.Invalidate(); } + } + + private sealed class SampleProof(TimeProvider clock, GrpcDataAdapterRoute[] routes, CancellationToken cancellationToken) + : IProjectedSamplePublicationProof + { + private int _invalid; + public TimeProvider Clock => clock; + public bool IsValid => Volatile.Read(ref _invalid) == 0 && !cancellationToken.IsCancellationRequested && routes.All(Valid); + public void Invalidate() => Interlocked.Exchange(ref _invalid, 1); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IProjectedDependencyInterestSink.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IProjectedDependencyInterestSink.cs new file mode 100644 index 000000000..051f9efdb --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/IProjectedDependencyInterestSink.cs @@ -0,0 +1,7 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Receives aggregate configured dependency transitions without blocking the mux actor. +public interface IProjectedDependencyInterestSink +{ + void SetInterest(string projectedReference, bool active); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs index 56eaf097d..33e61d771 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs @@ -28,6 +28,20 @@ public sealed class LocalCatalogCoordinator private LocalExportCatalog? _published; private bool _terminal; private bool _catalogValid; + private ProjectedMappingDeploymentRuntime? _projectedMappings; + internal ProjectedMappingDeploymentRuntime? ProjectedMappings => Volatile.Read(ref _projectedMappings); + internal void AttachProjectedMappings(ProjectedMappingDeploymentRuntime runtime) + { + if (Interlocked.CompareExchange(ref _projectedMappings, runtime, null) is not null) + throw new InvalidOperationException("Projected mappings are already attached."); + } + internal void DetachProjectedMappings(ProjectedMappingDeploymentRuntime runtime) => + Interlocked.CompareExchange(ref _projectedMappings, null, runtime); + internal LocalExportCatalog? MappingCatalog(CatalogAttempt attempt) + { + lock (_gate) + return ReferenceEquals(_attempt, attempt) && _terminal ? Current : null; + } // A test can hold the host's existing subscription boundary to observe ordering. internal Action? BeforeSubscriptionApplyForTests { get; set; } @@ -84,16 +98,18 @@ public sealed class LocalCatalogCoordinator public CatalogAttempt BeginAttempt(string revision) { + CatalogAttempt attempt; lock (_gate) { - var attempt = new CatalogAttempt(_activation.Begin(revision), revision); + attempt = new CatalogAttempt(_activation.Begin(revision), revision); _attempt = attempt; _staged = null; _terminal = false; _catalogValid = false; using (DispatchFence.Enter()) Volatile.Write(ref _published, null); - return attempt; } + ProjectedMappings?.AttemptBegan(attempt); + return attempt; } /// Install independently readable credentials even when catalog topology is invalid. @@ -136,6 +152,7 @@ public sealed class LocalCatalogCoordinator public bool Complete(CatalogAttempt attempt, bool topologySucceeded) { ArgumentNullException.ThrowIfNull(attempt); + bool completed; lock (_gate) { if (_terminal || !ReferenceEquals(_attempt, attempt)) return false; @@ -144,12 +161,10 @@ public sealed class LocalCatalogCoordinator var valid = topologySucceeded && _staged is not null && _catalogValid && state.AuthorityEpoch == _authority.Current.GenerationId; if (valid) { using (DispatchFence.Enter()) Volatile.Write(ref _published, _staged); } - if (!_activation.Complete(attempt.Epoch, valid)) - { - using (DispatchFence.Enter()) Volatile.Write(ref _published, null); - return false; - } - return true; + completed = _activation.Complete(attempt.Epoch, valid); + if (!completed) { using (DispatchFence.Enter()) Volatile.Write(ref _published, null); } } + ProjectedMappings?.AttemptCompleted(attempt, completed); + return completed; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 7d2ff9b85..b045d32b5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -202,7 +202,7 @@ public sealed class LocalDataServices : IDataConnectionFactory && (operation != DataOperations.Write || node.Metadata.Writable && string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) && Allowed(catalog, context, node, operation)) operations |= operation; - return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write) }; + return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write), Serving = catalog.Serving }; } internal Task GetCapabilitiesAsync(DataAuthenticatedContext context, DataTarget target, DataBudget budget, CancellationToken cancellationToken) @@ -214,7 +214,7 @@ public sealed class LocalDataServices : IDataConnectionFactory catalog is null ? _capabilities.Limits : Limits(catalog, context)); if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; - return Task.FromResult(capabilities); + return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor) }); } internal Task>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken) @@ -375,7 +375,7 @@ public sealed class LocalDataServices : IDataConnectionFactory var token = complete ? null : EncodeContinuation(new(request.Parent, request.Filter, offset, context.PrincipalId, context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, leaseDuration.Ticks)); return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token, - new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration))); + new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration), catalog.Serving)); } internal async Task> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken) @@ -391,7 +391,8 @@ public sealed class LocalDataServices : IDataConnectionFactory if (_writes is not null && catalog is not null && Ready(catalog) && string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) && catalog.TryResolve(item.View, out var node) - && node.SourceEnabled && node.Supported && node.Metadata.Writable && Allowed(catalog, context, node, DataOperations.Write)) + && node.SourceEnabled && node.Supported && node.Metadata.Writable && Allowed(catalog, context, node, DataOperations.Write) + && (item.ExpectedServingGeneration is null || item.ExpectedServingGeneration > 0 && item.ExpectedServingGeneration == catalog.Serving.ServingGeneration)) { allowed.Add(item); indexes.Add(i); } else results[i] = new(item.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable or denied before dispatch.")); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index e0eab3592..6de13fcc1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -97,6 +97,7 @@ public sealed partial class LocalExportCatalog public string ClusterId { get; } public ServingIdentity Serving { get; } + internal IDataMappedCatalogAuthority MappingAuthority => _activation; public long AuthorityEpoch => _activation.AuthorityEpoch; public bool IsActive => _activation.IsActive && _activation.CatalogEpoch == Serving.CatalogEpoch && _activation.AuthorityEpoch == Serving.AuthorityEpoch; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedAdapterRouteSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedAdapterRouteSource.cs new file mode 100644 index 000000000..b96bad22d --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedAdapterRouteSource.cs @@ -0,0 +1,51 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Resolves canonical projected references while retaining their original local and origin authority. +public sealed class ProjectedAdapterRouteSource(IFederatedProjectionCatalog catalog, + Func connectionForMapping, string connectionId, Func authorize) + : IGrpcDataAdapterRouteSource +{ + private bool Current(DataRealm realm, string identifier, out ProjectedNodeProof? proof) + { + proof = null; + try + { + if (!catalog.TryResolveProjected(realm, identifier, out var found) || found is null || + found.Metadata.View.MappingId is not { } mapping || found.Generation <= 0 || + found.LocalIdentifier != identifier || found.Metadata.View.Realm != realm || + !found.Lease.IsValid || found.Lease.Serving.ServingGeneration <= 0 || + found.Metadata.Serving != found.Lease.Serving || found.OriginMetadata.Serving != found.Lease.Serving || + found.OriginMetadata.View.MappingId is not null || found.OriginMetadata.View.MappingRevision != 0 || + found.OriginMetadata.View.Address != found.Metadata.View.Address || found.OriginMetadata.View.Realm != realm || + found.Resolver.Resolve(found.Metadata.View, found.Subject).Kind != MappedSubjectResolutionKind.Mapped || + !string.Equals(connectionForMapping(mapping), connectionId, StringComparison.OrdinalIgnoreCase) || !authorize(found)) + return false; + proof = found; + return true; + } + catch (Exception) { return false; } + } + + public bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route) + { + route = null; + if (!ProjectedDataIds.TryParseDependencyReference(fullReference, out var realm, out var identifier) || + !Current(realm, identifier, out var proof) || proof is null) return false; + var captured = proof; + var lease = new RouteLease(captured.Lease.Serving, () => Current(realm, identifier, out var now) && now is not null && + now.Generation == captured.Generation && now.Lease.Serving == captured.Lease.Serving && + now.OriginMetadata == captured.OriginMetadata && now.Metadata.View == captured.Metadata.View && captured.Lease.IsValid); + route = new(fullReference, captured.OriginMetadata.View, captured.OriginMetadata, captured.Lease.Serving, lease, + captured.Generation, captured.MaximumSampleAge); + return lease.IsValid; + } + + private sealed class RouteLease(ServingIdentity serving, Func current) : IDataAuthorizationLease + { + public ServingIdentity Serving => serving; + public bool IsValid => current(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs new file mode 100644 index 000000000..cae7f41e7 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedBrowseAccess.cs @@ -0,0 +1,224 @@ +using System.Collections.Concurrent; +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Caller-bound projection browse scheduling and local anchor lifetime. +public sealed class ProjectedBrowseAccess : IProjectedBrowseAccess, IDisposable +{ + private sealed record Installed(NodeId Node, ProjectedAnchorDefinition Definition, ProjectedMappingPlacement Placement); + private readonly record struct WorkKey(NodeId Parent, DataCallerIdentity Caller, string? Cursor, int MaxItems); + private readonly ProjectedMappingDeploymentRuntime _lifecycle; + private readonly IFederatedProjectionCatalog _catalog; + private readonly ProjectedNamespaceApplier _applier; + private readonly IProjectedAnchorSink _anchors; + private readonly Func _resolveNode; + private readonly DataBudget _budget; + private readonly int _maxPending; + private readonly object _anchorGate = new(); + private readonly ConcurrentDictionary _installed = new(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _inflight = new(); + private readonly record struct Failure(ProjectionPageStatus Status, long Until); + private readonly object _resultGate = new(); + private readonly Dictionary _failures = new(); + private readonly CancellationTokenSource _stop = new(); + private int _pending, _disposed; + + public ProjectedBrowseAccess(ProjectedMappingDeploymentRuntime lifecycle, IFederatedProjectionCatalog catalog, + ProjectedNamespaceApplier applier, IProjectedAnchorSink anchors, Func resolveNode, + DataBudget budget, int maxPending) + { + _lifecycle = lifecycle ?? throw new ArgumentNullException(nameof(lifecycle)); + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _applier = applier ?? throw new ArgumentNullException(nameof(applier)); + _anchors = anchors ?? throw new ArgumentNullException(nameof(anchors)); + _resolveNode = resolveNode ?? throw new ArgumentNullException(nameof(resolveNode)); + _budget = budget ?? throw new ArgumentNullException(nameof(budget)); _budget.Validate(); + if (maxPending <= 0) throw new ArgumentOutOfRangeException(nameof(maxPending)); + _maxPending = maxPending; + _lifecycle.Changed += OnChanged; + RefreshAnchors(); + } + + private void OnChanged(IReadOnlyList _) => RefreshAnchors(); + private bool Current(ProjectedMappingPlacement placement) => _lifecycle.IsCurrentPlacement(placement); + + /// Reconciles against the live SDK binding; safe to call after the deferred sink binds. + public void RefreshAnchors() + { + lock (_anchorGate) + { + if (Volatile.Read(ref _disposed) != 0) return; + var placements = _lifecycle.Active; + foreach (var entry in _installed.ToArray()) + { + var old = entry.Value; + if (Current(old.Placement)) continue; + _installed.TryRemove(entry.Key, out _); + _anchors.TryRemoveProjectedAnchor(old.Node, old.Definition); + } + foreach (var placement in placements) + { + var mappingId = placement.Mapping.RemoteNamespaceMappingId; + if (_installed.ContainsKey(mappingId) || !Current(placement) || placement.Parent.Address.IdentifierKind != "string") continue; + var parent = _resolveNode(placement.Parent.Address.NamespaceUri, placement.Parent.Address.Identifier); + if (parent is not { } parentNode) continue; + var id = ProjectedDataIds.Identifier(mappingId, placement.Anchor.Address); + var definition = new ProjectedAnchorDefinition(placement.Mapping.Realm, id, parentNode, placement.Mapping.BranchName, + placement.Anchor.Subject, mappingId, placement.Mapping.Revision, () => Current(placement)); + if (_anchors.TryEnsureProjectedAnchor(definition, out var node) && node is { } anchorNode) + { + if (Current(placement)) _installed[mappingId] = new(anchorNode, definition, placement); + else _anchors.TryRemoveProjectedAnchor(anchorNode, definition); + } + } + } + } + + private sealed class PageGuard(ProjectedBrowseAccess owner, IProjectedPageGuard source) + { + public bool IsCurrent() => Volatile.Read(ref owner._disposed) == 0 && source.IsCurrent; + } + + private static ProjectedBrowsePage Empty(ProjectedBrowseReadiness status) => new(status, [], null, false, static () => false); + + public ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest input) + { + ArgumentNullException.ThrowIfNull(input); + if (Volatile.Read(ref _disposed) != 0) return Empty(ProjectedBrowseReadiness.Unavailable); + var id = input.Parent.IdentifierAsString; + if (!ProjectedDataIds.TryDecodeIdentifier(id, out var mappingId, out _)) return Empty(ProjectedBrowseReadiness.Unavailable); + if (!_installed.TryGetValue(mappingId, out var anchor) || !Current(anchor.Placement)) return Empty(ProjectedBrowseReadiness.Unavailable); + DataView parent; + if (anchor.Node == input.Parent) parent = anchor.Placement.Anchor; + else + { + var realm = anchor.Placement.Mapping.Realm; + var expected = _resolveNode(ProjectedDataIds.NamespaceUri(realm), id); + if (expected != input.Parent || !_catalog.TryResolveProjected(realm, id, out var proof) || proof is null || + proof.Subject.View.MappingId != mappingId || !proof.Lease.IsValid || !ReferenceEquals(proof.Resolver.LocalAuthority, anchor.Placement.Authority)) + return Empty(ProjectedBrowseReadiness.Unavailable); + parent = proof.Metadata.View; + } + var caller = input.Caller; + if (caller is null || string.IsNullOrWhiteSpace(caller.Principal) || string.IsNullOrWhiteSpace(caller.ApiKeyId) || + string.IsNullOrWhiteSpace(caller.CredentialVersion)) return Empty(ProjectedBrowseReadiness.Unavailable); + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + var maximum = input.MaximumResults == 0 ? _budget.MaxItems : (int)Math.Min((long)input.MaximumResults, _budget.MaxItems); + var budget = _budget with { MaxItems = maximum }; + var request = new ProjectedBrowseRequest(mappingId, parent, null, input.Cursor, identity, budget, input.RequestStartedTimestamp); + var snapshot = _catalog.TryGetParent(request); + if (snapshot.Status == ProjectionPageStatus.Ready) + { + if (snapshot.Lease is not { IsValid: true } lease || snapshot.LocalAuthority is not { IsActive: true } local || + !ReferenceEquals(local, anchor.Placement.Authority) || snapshot.Generation <= 0) + return Empty(ProjectedBrowseReadiness.Unavailable); + var nodes = new List(snapshot.Items.Count); + foreach (var item in snapshot.Items) + { + if (item.Generation != snapshot.Generation || !ReferenceEquals(item.Resolver.LocalAuthority, local) || !item.Lease.IsValid || + item.Subject.View.MappingId != mappingId || _resolveNode(ProjectedDataIds.NamespaceUri(item.Metadata.View.Realm), item.LocalIdentifier) is not { } node) + return Empty(ProjectedBrowseReadiness.Unavailable); + nodes.Add(node); + } + var expectedIds = nodes.ToArray(); + var sourceGuard = _catalog.CaptureParentGuard(request, snapshot); + if (sourceGuard is null) return Empty(ProjectedBrowseReadiness.Unavailable); + var guard = new PageGuard(this, sourceGuard); + if (!guard.IsCurrent()) return Empty(ProjectedBrowseReadiness.Unavailable); + var retainedBytes = checked(sourceGuard.RetainedBytes + 2048L + 2L * (snapshot.Continuation?.Length ?? 0) + + expectedIds.Sum(node => 128L + 2L * node.IdentifierAsString.Length)); + return new(ProjectedBrowseReadiness.Ready, Array.AsReadOnly(expectedIds), snapshot.Continuation, snapshot.Complete, + guard.IsCurrent, retainedBytes); + } + if (snapshot.Status == ProjectionPageStatus.InvalidContinuation) return Empty(ProjectedBrowseReadiness.InvalidContinuation); + var key = new WorkKey(input.Parent, identity, input.Cursor, maximum); + lock (_resultGate) + { + var now = _catalog.Clock.GetTimestamp(); + foreach (var expired in _failures.Where(x => x.Value.Until <= now).Select(x => x.Key).ToArray()) _failures.Remove(expired); + if (_failures.TryGetValue(key, out var failure)) + return Empty(failure.Status switch + { + ProjectionPageStatus.InvalidContinuation => ProjectedBrowseReadiness.InvalidContinuation, + ProjectionPageStatus.Pending => ProjectedBrowseReadiness.Pending, + _ => ProjectedBrowseReadiness.Unavailable + }); + if (_inflight.ContainsKey(key)) return Empty(ProjectedBrowseReadiness.Pending); + if (_failures.Count + _pending >= _maxPending) return Empty(ProjectedBrowseReadiness.Unavailable); + if (!_inflight.TryAdd(key, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously))) return Empty(ProjectedBrowseReadiness.Pending); + _pending++; + } + var exactParent = input.Parent; + _ = Task.Run(async () => + { + var result = ProjectionPageStatus.Unavailable; + try { if (Current(anchor.Placement)) result = await _applier.ApplyPageResultAsync(request, exactParent, _stop.Token).ConfigureAwait(false); } + catch (Exception) { } + finally + { + lock (_resultGate) + { + _inflight.TryRemove(key, out var completed); + _pending--; + if (result != ProjectionPageStatus.Ready && !_stop.IsCancellationRequested) + { + var now = _catalog.Clock.GetTimestamp(); + var seconds = result == ProjectionPageStatus.InvalidContinuation ? 60L : 0L; + var delay = seconds == 0 ? Math.Max(1, _catalog.Clock.TimestampFrequency / 4) : + _catalog.Clock.TimestampFrequency > long.MaxValue / seconds ? long.MaxValue : _catalog.Clock.TimestampFrequency * seconds; + _failures[key] = new(result, now > long.MaxValue - delay ? long.MaxValue : now + delay); + } + completed?.TrySetResult(); + } + } + }); + return Empty(ProjectedBrowseReadiness.Pending); + } + + public async Task WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + for (var retry = 0; retry < 3; retry++) + { + var page = GetOrSchedulePage(request); + if (page.Status != ProjectedBrowseReadiness.Pending) return page; + var caller = request.Caller; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + var max = request.MaximumResults == 0 ? _budget.MaxItems : (int)Math.Min((long)request.MaximumResults, _budget.MaxItems); + var key = new WorkKey(request.Parent, identity, request.Cursor, max); + if (!_inflight.TryGetValue(key, out var pending)) continue; + var elapsed = _catalog.Clock.GetElapsedTime(request.RequestStartedTimestamp, _catalog.Clock.GetTimestamp()); + var remaining = _budget.Timeout - elapsed; + if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return Empty(ProjectedBrowseReadiness.Unavailable); + try { await pending.Task.WaitAsync(remaining, _catalog.Clock, cancellationToken).ConfigureAwait(false); } + catch (TimeoutException) { return Empty(ProjectedBrowseReadiness.Unavailable); } + } + return Empty(ProjectedBrowseReadiness.Unavailable); + } + + public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (!ProjectedDataIds.TryDecodeIdentifier(context.Parent.IdentifierAsString, out _, out _)) return ProjectedBrowseReadiness.Ready; + if (context.Caller is null) return ProjectedBrowseReadiness.Unavailable; + var page = GetOrSchedulePage(new(context.Parent, context.Caller, null, context.Continuation.MaxResultsToReturn, context.RequestStartedTimestamp)); + return page.Status == ProjectedBrowseReadiness.Ready && !page.Complete ? ProjectedBrowseReadiness.Unavailable : page.Status; + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _lifecycle.Changed -= OnChanged; + _stop.Cancel(); + lock (_resultGate) _failures.Clear(); + lock (_anchorGate) + { + foreach (var item in _installed.Values) _anchors.TryRemoveProjectedAnchor(item.Node, item.Definition); + _installed.Clear(); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs new file mode 100644 index 000000000..afb9c3fbe --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -0,0 +1,379 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Observable per-parent projection status; pending and unavailable are not empty success. +public enum ProjectionPageStatus { Pending, Ready, Unavailable, InvalidContinuation } +/// One trusted immutable mapped subject and its currently leased remote authority. +public sealed record ProjectedNodeProof(string LocalIdentifier, DataMetadata Metadata, MappedNamespaceSubject Subject, + MappedSubjectResolver Resolver, IDataAuthorizationLease Lease, long Generation, DataMetadata OriginMetadata, TimeSpan MaximumSampleAge = default); +/// A caller-bound projection page. +public sealed record ProjectedParentSnapshot(ProjectionPageStatus Status, IReadOnlyList Items, + bool Complete, string? Continuation, long Generation, IDataAuthorizationLease? Lease = null, + IDataMappedCatalogAuthority? LocalAuthority = null, ProjectedNodeProof? ParentProof = null); +/// One bounded parent query, with the original monotonic request-start timestamp. +public sealed record ProjectedBrowseRequest(string MappingId, DataView Parent, string? Filter, string? Continuation, + DataCallerIdentity Caller, DataBudget Budget, long RequestStartedTimestamp) +{ + internal ConfiguredProjectionCapability? ConfiguredCapability { get; init; } +} +/// Prepared pages are committed only after the caller successfully applies their content. +public interface IProjectedPreparedPage : IDisposable +{ + ProjectedParentSnapshot Snapshot { get; } + bool TryCommit(); +} +/// Detached constant-work validity of one already-authorized cached page. +public interface IProjectedPageGuard +{ + bool IsCurrent { get; } + long RetainedBytes { get; } +} +/// Nonblocking catalog lookups and bounded asynchronous page preparation. +public interface IFederatedProjectionCatalog +{ + TimeProvider Clock { get; } + ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request); + IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => null; + Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken); + bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof); + bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin); + event Action? Invalidated; +} + +/// Bounded cache of caller-scoped, already-authorized projected pages. +public sealed class ProjectedCatalogCache +{ + private readonly record struct ParentKey(string Mapping, DataView Parent, string? Filter, string? Cursor, DataCallerIdentity? Caller, ConfiguredProjectionCapability? Capability); + private sealed class ParentEntry(ProjectedParentSnapshot snapshot) { internal readonly object Version = new(); internal ProjectedParentSnapshot Snapshot = snapshot; internal LinkedListNode? Sweep; } + private sealed class NodeEntry(ProjectedNodeProof proof) { internal ProjectedNodeProof Proof = proof; internal int Pins; internal bool Retired; internal LinkedListNode<(DataRealm Realm, string Id)>? Sweep; } + private readonly object _sync = new(); + private readonly Dictionary _parents = new(); + private readonly Dictionary<(DataRealm Realm, string Id), NodeEntry> _nodes = new(); + private readonly HashSet _retiredPinned = new(); + private readonly LinkedList _parentSweep = new(); + private readonly LinkedList<(DataRealm Realm, string Id)> _nodeSweep = new(); + private readonly Dictionary _mappingNodeCounts = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<(string Mapping, DataView Parent), Dictionary> _siblingNames = new(); + private long _retainedBytes; + private readonly Dictionary<(string Mapping, DataView Parent), long> _unavailable = new(); + private readonly Dictionary _mappingGenerations = new(StringComparer.OrdinalIgnoreCase); + private readonly int _maxParents, _maxNodes; + private readonly long _maxBytes; + private bool _saturated; + private long _nextGeneration; + private readonly DataOperationPolicy? _policy; + public ProjectedCatalogCache(int maxParents, int maxNodes, TimeProvider clock, DataOperationPolicy? policy = null, long maxBytes = 16 * 1024 * 1024) + { + if (maxParents <= 0 || maxNodes <= 0 || maxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxParents)); + _maxParents = maxParents; _maxNodes = maxNodes; _maxBytes = maxBytes; Clock = clock ?? throw new ArgumentNullException(nameof(clock)); _policy = policy; + } + public TimeProvider Clock { get; } + public event Action? Invalidated; + private static ParentKey Key(ProjectedBrowseRequest request) => new(request.MappingId.ToUpperInvariant(), request.Parent, + request.Filter, request.Continuation, request.Caller, request.ConfiguredCapability); + private static (string Mapping, DataView Parent) Parent(string mapping, DataView parent) => (mapping.ToUpperInvariant(), parent); + private bool ValidCore(ProjectedNodeProof proof) => proof.Generation > 0 && proof.Lease.IsValid && proof.Lease.Serving.ServingGeneration > 0 && + proof.Subject.Serving == proof.Lease.Serving && proof.Metadata.View == proof.Subject.View && + proof.Metadata.Serving == proof.Lease.Serving && proof.OriginMetadata.Serving == proof.Lease.Serving && + proof.OriginMetadata.View.MappingId is null && proof.OriginMetadata.View.MappingRevision == 0 && + proof.OriginMetadata.View.Address == proof.Metadata.View.Address && proof.OriginMetadata.View.Realm == proof.Metadata.View.Realm && + proof.OriginMetadata.CatalogRevision == proof.Lease.Serving.CatalogEpoch && + proof.LocalIdentifier == ProjectedDataIds.Identifier(proof.Subject.View.MappingId!, proof.OriginMetadata.View.Address) && + proof.Resolver.Resolve(proof.Metadata.View, proof.Subject).Kind == MappedSubjectResolutionKind.Mapped; + private bool Valid(ProjectedNodeProof proof) + { + try { return ValidCore(proof); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; } + } + private static ProjectedNodeProof Freeze(ProjectedNodeProof proof) => proof with + { + Metadata = proof.Metadata with { Dimensions = Array.AsReadOnly(proof.Metadata.Dimensions.ToArray()) }, + OriginMetadata = proof.OriginMetadata with { Dimensions = Array.AsReadOnly(proof.OriginMetadata.Dimensions.ToArray()) }, + Subject = proof.Subject with + { + Scope = proof.Subject.Scope with { Segments = Array.AsReadOnly(proof.Subject.Scope.Segments.ToArray()) }, + LocalAncestry = Array.AsReadOnly(proof.Subject.LocalAncestry.ToArray()) + } + }; + internal static bool IsValueNode(DataMetadata metadata) => metadata.NodeKind is "Variable" or "Tag"; + private static long Bytes(ProjectedNodeProof proof) => ProjectedProofSize.Estimate(proof); + private static long KeyBytes(ParentKey k) => checked(256L + 2L * (k.Mapping.Length + k.Parent.Subject.Length + + k.Parent.Address.OriginClusterId.Length + k.Parent.Address.NamespaceUri.Length + k.Parent.Address.IdentifierKind.Length + + k.Parent.Address.Identifier.Length + (k.Parent.MappingId?.Length ?? 0) + (k.Filter?.Length ?? 0) + + (k.Cursor?.Length ?? 0) + (k.Caller?.Principal.Length ?? 0) + (k.Caller?.ApiKeyId?.Length ?? 0) + (k.Caller?.CredentialVersion?.Length ?? 0))); + private static long PageBytes(ParentKey key, ProjectedParentSnapshot page) => checked(KeyBytes(key) + + (page.ParentProof is { } parent ? Bytes(parent) : 0) + page.Items.Sum(Bytes)); + private void ChangeMappingCount(NodeEntry entry, int delta) + { + var mapping = entry.Proof.Subject.View.MappingId!; + _mappingNodeCounts.TryGetValue(mapping, out var current); + if (current + delta == 0) _mappingNodeCounts.Remove(mapping); else _mappingNodeCounts[mapping] = checked(current + delta); + } + private void RemoveParent(ParentKey key) + { + if (!_parents.Remove(key, out var entry)) return; + _parentSweep.Remove(entry.Sweep!); _retainedBytes -= PageBytes(key, entry.Snapshot); + var parent = (key.Mapping, key.Parent); + if (!_siblingNames.TryGetValue(parent, out var names)) return; + foreach (var item in entry.Snapshot.Items) + { + var name = item.Metadata.BrowseName; var old = names[name]; + if (old.Count == 1) names.Remove(name); else names[name] = (old.Address, old.Count - 1); + } + if (names.Count == 0) _siblingNames.Remove(parent); + } + private void AddParent(ParentKey key, ProjectedParentSnapshot page) + { + RemoveParent(key); + var entry = new ParentEntry(page) { Sweep = _parentSweep.AddLast(key) }; _parents.Add(key, entry); + _retainedBytes = checked(_retainedBytes + PageBytes(key, page)); + var parent = (key.Mapping, key.Parent); + if (!_siblingNames.TryGetValue(parent, out var names)) _siblingNames[parent] = names = new(StringComparer.Ordinal); + foreach (var item in page.Items) + { + names.TryGetValue(item.Metadata.BrowseName, out var old); + names[item.Metadata.BrowseName] = (item.OriginMetadata.View.Address, old.Count + 1); + } + } + private void RemoveNode((DataRealm Realm, string Id) key) + { + if (!_nodes.Remove(key, out var node)) return; + _nodeSweep.Remove(node.Sweep!); node.Sweep = null; + if (node.Pins > 0) { node.Retired = true; _retiredPinned.Add(node); } + else { _retainedBytes -= Bytes(node.Proof); ChangeMappingCount(node, -1); } + } + private void AddNode((DataRealm Realm, string Id) key, ProjectedNodeProof proof) + { + RemoveNode(key); + var node = new NodeEntry(proof) { Sweep = _nodeSweep.AddLast(key) }; _nodes.Add(key, node); + _retainedBytes = checked(_retainedBytes + Bytes(proof)); ChangeMappingCount(node, 1); + } + // Fixed work per admission. Rotate live entries so repeated capacity pressure reaches idle expired entries. + private void ReclaimExpired() + { + for (var i = 0; i < 64 && _parentSweep.First is { } first; i++) + { + var key = first.Value; var entry = _parents[key]; + if (entry.Snapshot.Lease is not { IsValid: true } || entry.Snapshot.LocalAuthority is not { IsActive: true }) RemoveParent(key); + else { _parentSweep.RemoveFirst(); _parentSweep.AddLast(first); } + if (_parentSweep.Count <= i + 1) break; + } + for (var i = 0; i < 64 && _nodeSweep.First is { } first; i++) + { + var key = first.Value; var node = _nodes[key]; + if (!Valid(node.Proof)) RemoveNode(key); + else { _nodeSweep.RemoveFirst(); _nodeSweep.AddLast(first); } + if (_nodeSweep.Count <= i + 1) break; + } + } + /// Captures a generation before asynchronous work begins. + public long CaptureGeneration(string mappingId) + { + ArgumentException.ThrowIfNullOrWhiteSpace(mappingId); + lock (_sync) + { + if (_mappingGenerations.TryGetValue(mappingId, out var value)) return value; + if (_mappingGenerations.Count >= _maxParents) throw new InvalidOperationException("Projection mapping capacity exhausted."); + var generation = checked(++_nextGeneration); + _mappingGenerations.Add(mappingId, generation); return generation; + } + } + internal bool IsCurrentGeneration(string mappingId, long generation) + { + lock (_sync) return !_saturated && _mappingGenerations.TryGetValue(mappingId, out var current) && current == generation; + } + private static bool SamePlacement(MappedNamespaceSubject left, MappedNamespaceSubject right) => + left.View == right.View && left.Serving == right.Serving && left.AllowedOperations == right.AllowedOperations && + left.WriteThrough == right.WriteThrough && left.Scope.Kind == right.Scope.Kind && + string.Equals(left.Scope.ClusterId, right.Scope.ClusterId, StringComparison.OrdinalIgnoreCase) && + left.Scope.Segments.SequenceEqual(right.Scope.Segments, StringComparer.Ordinal) && + left.LocalAncestry.SequenceEqual(right.LocalAncestry, StringComparer.OrdinalIgnoreCase); + private bool Usable(ProjectedBrowseRequest request) => request.ConfiguredCapability is { } capability + ? capability.Matches(request.MappingId, request.Parent, null) : request.Caller is not null && _policy is not null && _policy.IsCallerUsable(request.Caller); + private bool Allowed(ProjectedBrowseRequest request, ProjectedNodeProof proof) => Valid(proof) && + (request.ConfiguredCapability is { } capability ? capability.Matches(request.MappingId, proof.Metadata.View, proof.Resolver.LocalAuthority) : + _policy is not null && request.Caller is not null && _policy.AuthorizeMapped(request.Caller, OpcUaOperation.Browse, proof.Metadata.View, proof.Subject.Serving, proof.Subject, proof.Resolver, proof.Lease)); + private static ProjectedParentSnapshot Empty(ProjectionPageStatus status, long generation = 0) => new(status, [], false, null, generation); + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) + { + ArgumentNullException.ThrowIfNull(request); + lock (_sync) + { + if (_saturated) return Empty(ProjectionPageStatus.Unavailable); + if (_unavailable.TryGetValue(Parent(request.MappingId, request.Parent), out var unavailable)) return Empty(ProjectionPageStatus.Unavailable, unavailable); + if (!_parents.TryGetValue(Key(request), out var entry)) return Empty(ProjectionPageStatus.Pending); + if (_policy is null || !Usable(request) || + entry.Snapshot.Lease is not { IsValid: true } || entry.Snapshot.LocalAuthority is not { IsActive: true } local || + local.AuthorityEpoch != _policy.AuthorityEpoch || + (request.ConfiguredCapability is null && request.Caller.CredentialExpiresUtc is { } expiry && expiry <= Clock.GetUtcNow())) return Empty(ProjectionPageStatus.Unavailable); + if (entry.Snapshot.ParentProof is not { } parent || parent.Metadata.View != request.Parent || !Allowed(request, parent) || + entry.Snapshot.Items.Any(item => !Allowed(request, item))) return Empty(ProjectionPageStatus.Unavailable); + return entry.Snapshot; + } + } + private sealed class ParentGuard(ProjectedCatalogCache owner, ParentKey key, object version, + ProjectedBrowseRequest request, ProjectedNodeProof parent, IDataAuthorizationLease lease, + IDataMappedCatalogAuthority local, long generation, long bytes) : IProjectedPageGuard + { + public long RetainedBytes => bytes; + public bool IsCurrent + { + get + { + try + { + lock (owner._sync) + { + if (owner._saturated || !owner._parents.TryGetValue(key, out var entry) || !ReferenceEquals(entry.Version, version) || + !owner._mappingGenerations.TryGetValue(key.Mapping, out var current) || current != generation || + owner._unavailable.ContainsKey((key.Mapping, key.Parent)) || owner._policy is null || + local.AuthorityEpoch != owner._policy.AuthorityEpoch || !owner.Usable(request) || !owner.Allowed(request, parent)) return false; + // External authorization can change authority while it executes. The fast source fence is last. + return local.IsActive && local.AuthorityEpoch == owner._policy.AuthorityEpoch && lease.IsValid && + owner._parents.TryGetValue(key, out var final) && ReferenceEquals(final.Version, version) && + owner._mappingGenerations.TryGetValue(key.Mapping, out var latest) && latest == generation; + } + } + catch (Exception) { return false; } + } + } + } + public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) + { + lock (_sync) + { + var key = Key(request); + if (!_parents.TryGetValue(key, out var entry) || !ReferenceEquals(entry.Snapshot, expected) || + expected.Status != ProjectionPageStatus.Ready || expected.ParentProof is not { } parent || + expected.Lease is not { } lease || expected.LocalAuthority is not { } local) return null; + return new ParentGuard(this, key, entry.Version, request, parent, lease, local, expected.Generation, + checked(1024L + KeyBytes(key) + Bytes(parent))); + } + } + /// Publishes a fully verified page; collisions, inactive leases and capacity fail closed. + public bool TryPublish(ProjectedBrowseRequest request, ProjectedParentSnapshot page) => TryPublish(request, page, null, out _); + internal bool TryPublish(ProjectedBrowseRequest request, ProjectedParentSnapshot page, + Func<(bool Success, string? Cursor)>? commitCursor, out ProjectedParentSnapshot? committed, int maximumMappingNodes = int.MaxValue) + { + committed = null; + ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(page); + if (page.Status != ProjectionPageStatus.Ready || page.Generation <= 0 || _policy is null || page.Lease is not { IsValid: true } || + page.LocalAuthority is not { IsActive: true } local || local.AuthorityEpoch != _policy.AuthorityEpoch || !Usable(request) || + page.ParentProof is not { } parent || parent.Metadata.View != request.Parent || parent.Generation != page.Generation || + !ReferenceEquals(parent.Resolver.LocalAuthority, local) || parent.Lease.Serving != page.Lease.Serving || !Allowed(request, parent)) return false; + ProjectedNodeProof[] items; + try { items = page.Items.Select(Freeze).ToArray(); parent = Freeze(parent); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NullReferenceException) { return false; } + var indexedItems = IsValueNode(parent.Metadata) ? items.Append(parent).ToArray() : items; + lock (_sync) + { + if (_saturated || !_mappingGenerations.TryGetValue(request.MappingId, out var mappingGeneration) || mappingGeneration != page.Generation || + !page.Lease.IsValid || !local.IsActive || !Usable(request) || !Allowed(request, parent) || + items.Any(item => item.Generation != page.Generation || item.Lease.Serving != page.Lease.Serving || + !ReferenceEquals(item.Resolver.LocalAuthority, local) || !Allowed(request, item)) || + indexedItems.Select(item => (item.Metadata.View.Realm, item.LocalIdentifier)).Distinct().Count() != indexedItems.Length) return false; + var key = Key(request); + var estimatedPage = KeyBytes(key) + Bytes(parent) + items.Sum(Bytes); + _mappingNodeCounts.TryGetValue(request.MappingId, out var initialMappingCount); + if ((!_parents.ContainsKey(key) && _parents.Count >= _maxParents) || _nodes.Count + _retiredPinned.Count + indexedItems.Length > _maxNodes || + _retainedBytes + estimatedPage > _maxBytes || (long)initialMappingCount + indexedItems.Length > maximumMappingNodes) ReclaimExpired(); + if (!_parents.ContainsKey(key) && _parents.Count >= _maxParents) return false; + if (_nodes.Count + _retiredPinned.Count + indexedItems.Count(item => !_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var prior) || prior.Pins > 0) > _maxNodes) return false; + _mappingNodeCounts.TryGetValue(request.MappingId, out var retainedForMapping); + var additions = indexedItems.Count(item => !_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var existing) || existing.Pins > 0); + if ((long)retainedForMapping + additions > maximumMappingNodes) return false; + var oldPageBytes = _parents.TryGetValue(key, out var previousPage) ? KeyBytes(key) + (previousPage.Snapshot.ParentProof is { } oldParent ? Bytes(oldParent) : 0) + previousPage.Snapshot.Items.Sum(Bytes) : 0; + var nodeDelta = indexedItems.Sum(item => _nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var current) + ? current.Pins > 0 ? Bytes(item) : Bytes(item) - Bytes(current.Proof) : Bytes(item)); + if (_retainedBytes - oldPageBytes + KeyBytes(key) + Bytes(parent) + items.Sum(Bytes) + nodeDelta > _maxBytes) return false; + // Each mapped parent has an index across its pages, so unrelated pages do no work here. + if (_siblingNames.TryGetValue(Parent(request.MappingId, request.Parent), out var siblingNames)) + foreach (var item in items) + if (siblingNames.TryGetValue(item.Metadata.BrowseName, out var old) && old.Address != item.OriginMetadata.View.Address) return false; + foreach (var item in indexedItems) + if (_nodes.TryGetValue((item.Metadata.View.Realm, item.LocalIdentifier), out var existing) && + (existing.Retired || !SamePlacement(existing.Proof.Subject, item.Subject))) return false; + var cursor = commitCursor is null ? (true, page.Continuation) : commitCursor(); + if (!cursor.Item1) return false; + foreach (var item in indexedItems) + { + var nodeKey = (item.Metadata.View.Realm, item.LocalIdentifier); + AddNode(nodeKey, item); + } + _unavailable.Remove(Parent(request.MappingId, request.Parent)); + committed = page with { Items = Array.AsReadOnly(items), ParentProof = parent, Continuation = cursor.Item2 }; + AddParent(key, committed); + return true; + } + } + public void MarkUnavailable(string mappingId, DataView parent) + { + long generation; + lock (_sync) + { + generation = checked(++_nextGeneration); + if (!_mappingGenerations.ContainsKey(mappingId) && _mappingGenerations.Count >= _maxParents) _saturated = true; + else _mappingGenerations[mappingId] = generation; + if (!_unavailable.ContainsKey(Parent(mappingId, parent)) && _unavailable.Count >= _maxParents) _saturated = true; + else _unavailable[Parent(mappingId, parent)] = generation; + foreach (var key in _parents.Keys.Where(k => string.Equals(k.Mapping, mappingId, StringComparison.OrdinalIgnoreCase)).ToArray()) RemoveParent(key); + foreach (var key in _nodes.Where(p => string.Equals(p.Value.Proof.Subject.View.MappingId, mappingId, StringComparison.OrdinalIgnoreCase)).Select(p => p.Key).ToArray()) + { + RemoveNode(key); + } + } + Invalidated?.Invoke(mappingId, generation); + } + /// Reclaims a removed mapping after its current generation has been fenced. + public void ForgetMapping(string mappingId) + { + lock (_sync) + { + _mappingGenerations.Remove(mappingId); + foreach (var key in _unavailable.Keys.Where(key => string.Equals(key.Mapping, mappingId, StringComparison.OrdinalIgnoreCase)).ToArray()) _unavailable.Remove(key); + } + } + /// Checks one exact committed proof without retaining or scanning its original page. + internal bool IsCurrentProof(ProjectedNodeProof proof) + { + lock (_sync) return _nodes.TryGetValue((proof.Metadata.View.Realm, proof.LocalIdentifier), out var entry) && + !entry.Retired && ReferenceEquals(entry.Proof, proof) && Valid(proof); + } + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) + { + lock (_sync) + { + if (_nodes.TryGetValue((realm, localId), out var entry) && !entry.Retired && Valid(entry.Proof)) { proof = entry.Proof; return true; } + proof = null; return false; + } + } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) + { + lock (_sync) + { + if (!_nodes.TryGetValue((realm, localId), out var entry) || entry.Retired || !Valid(entry.Proof)) { pin = null; return false; } + entry.Pins++; pin = new Pin(this, entry); return true; + } + } + private sealed class Pin(ProjectedCatalogCache owner, NodeEntry entry) : IDisposable + { + private int _disposed; + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + lock (owner._sync) + { + entry.Pins--; + if (entry.Pins == 0 && entry.Retired) + { + var key = (entry.Proof.Metadata.View.Realm, entry.Proof.LocalIdentifier); + if (owner._nodes.TryGetValue(key, out var current) && ReferenceEquals(current, entry)) owner.RemoveNode(key); + if (owner._retiredPinned.Remove(entry)) { owner._retainedBytes -= Bytes(entry.Proof); owner.ChangeMappingCount(entry, -1); } + } + } + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCoalescingMailbox.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCoalescingMailbox.cs new file mode 100644 index 000000000..ad02f3a71 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCoalescingMailbox.cs @@ -0,0 +1,118 @@ +using Akka.Actor; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +internal sealed class ProjectedByteQuota(long maximum) +{ + private readonly object _gate = new(); + private long _used; + internal bool TryAdjust(long delta) + { + lock (_gate) + { + if (delta > 0 && delta > maximum - _used) return false; + _used += delta; + return true; + } + } +} + +/// Byte-charged coalescing storage; actor messages carry only a wake, never values. +internal sealed class ProjectedCoalescingMailbox : IDisposable where T : class +{ + private readonly object _gate = new(); + private readonly IActorRef _target; + private readonly Func, object> _wake; + private readonly long _maximumBytes; + private readonly int _maximumItems; + private readonly ProjectedByteQuota? _sharedQuota; + private readonly bool _retainDelivered; + private readonly Dictionary _delivered = new(StringComparer.Ordinal); + private readonly Dictionary _queued = new(StringComparer.Ordinal); + private long _bytes; + private bool _notified, _disposed; + + internal ProjectedCoalescingMailbox(IActorRef target, Func, object> wake, long maximumBytes, int maximumItems, ProjectedByteQuota? sharedQuota = null, bool retainDelivered = false) + { _target = target; _wake = wake; _maximumBytes = maximumBytes; _maximumItems = maximumItems; _sharedQuota = sharedQuota; _retainDelivered = retainDelivered; } + + internal bool TryOffer(IReadOnlyList<(string Key, T Value, long Charge)> items) + { + bool notify; + lock (_gate) + { + if (_disposed || items.Any(x => x.Charge <= 0) || items.Select(x => x.Key).Distinct(StringComparer.Ordinal).Count() != items.Count) return false; + long next = _bytes; + var added = 0; + try + { + foreach (var item in items) + { + if (_queued.TryGetValue(item.Key, out var old)) next = checked(next - old.Charge); + else added++; + next = checked(next + item.Charge); + } + } + catch (OverflowException) { return false; } + if (next > _maximumBytes || _queued.Count + added > _maximumItems || + _sharedQuota is not null && !_sharedQuota.TryAdjust(next - _bytes)) return false; + foreach (var item in items) _queued[item.Key] = (item.Value, item.Charge); + _bytes = next; notify = !_notified; _notified = true; + } + if (notify) _target.Tell(_wake(this)); + return true; + } + + internal Batch Take() + { + lock (_gate) + { + _notified = false; + var items = _queued.ToArray(); _queued.Clear(); + return new Batch(this, items); + } + } + private void Release(KeyValuePair[] items) + { + lock (_gate) + { + long released = 0; + foreach (var item in items) + { + if (_retainDelivered && !_disposed) + { + if (_delivered.TryGetValue(item.Key, out var prior)) released += prior.Charge; + _delivered[item.Key] = item.Value; + } + else released += item.Value.Charge; + } + _bytes -= released; _sharedQuota?.TryAdjust(-released); + } + } + internal sealed class Batch : IDisposable + { + private readonly ProjectedCoalescingMailbox _owner; + private readonly KeyValuePair[] _items; + private int _done; + internal Batch(ProjectedCoalescingMailbox owner, KeyValuePair[] items) + { _owner = owner; _items = items; Items = items.Select(x => x.Value.Value).ToArray(); } + internal IReadOnlyList Items { get; } + public void Dispose() { if (Interlocked.Exchange(ref _done, 1) == 0) _owner.Release(_items); } + } + internal void Clear() + { + lock (_gate) + { + var released = _queued.Values.Sum(x => x.Charge); + _bytes -= released; _sharedQuota?.TryAdjust(-released); _queued.Clear(); + } + } + public void Dispose() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; var released = _queued.Values.Sum(x => x.Charge) + _delivered.Values.Sum(x => x.Charge); + _bytes -= released; _sharedQuota?.TryAdjust(-released); _queued.Clear(); _delivered.Clear(); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs new file mode 100644 index 000000000..2aba47db4 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedDataAccess.cs @@ -0,0 +1,732 @@ +using Opc.Ua; +using System.Threading.Channels; +using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Finite ownership limits for mapped access and its physical work. +public sealed record ProjectedDataAccessLimits(int MaxDemands, int MaxUnaryOperations, long MaxUnaryBytes, int MaxStreams); + +/// Admission and asynchronous transport for projected SDK access. +public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable +{ + private readonly object _sync = new(); + public TimeProvider Clock { get; } + private readonly IFederatedProjectionCatalog _catalog; + private readonly IProjectedNodeLookup _nodes; + private readonly Func _connectionForMapping; + private readonly DataOperationPolicy _policy; + private readonly ProjectedDataAccessLimits _limits; + private readonly IGrpcDataAdapterConnectionSource _connections; + private readonly IProjectedValuePublisher _publisher; + private readonly Func<(bool Allowed, long Generation)> _localWriteRole; + private readonly Dictionary _sources = new(); + private readonly System.Collections.Concurrent.ConcurrentDictionary> _sourcesByMapping = new(StringComparer.OrdinalIgnoreCase); + private readonly object _sourceRetirementGate = new(); + private readonly LinkedList _sourceSweep = new(); + private readonly Dictionary> _sourceSweepNodes = new(); + private readonly Dictionary _pendingSourceRetirement = new(StringComparer.OrdinalIgnoreCase); + private bool _sourceRetirementRunning; + internal Action? BeforeSourceRetirementForTests { get; set; } + internal int PendingSourceRetirementsForTests { get { lock (_sourceRetirementGate) return _pendingSourceRetirement.Count; } } + private int _unaryCount; + private long _unaryBytes; + private readonly Dictionary _cohorts = new(); + private readonly Dictionary _demandCohorts = new(); + private readonly HashSet _demands = []; + private readonly Dictionary<(DataRealm Realm, string Identifier), int> _demandCounts = new(); + private bool _disposed; + public ProjectedDataAccess(IFederatedProjectionCatalog catalog, IProjectedNodeLookup nodes, + IGrpcDataAdapterConnectionSource connections, Func connectionForMapping, + DataOperationPolicy policy, IProjectedValuePublisher publisher, TimeProvider clock, ProjectedDataAccessLimits limits, + Func<(bool Allowed, long Generation)>? localWriteRole = null) + { + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _nodes = nodes ?? throw new ArgumentNullException(nameof(nodes)); + _connections = connections ?? throw new ArgumentNullException(nameof(connections)); _connectionForMapping = connectionForMapping ?? throw new ArgumentNullException(nameof(connectionForMapping)); + _policy = policy ?? throw new ArgumentNullException(nameof(policy)); _publisher = publisher ?? throw new ArgumentNullException(nameof(publisher)); Clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _limits = limits ?? throw new ArgumentNullException(nameof(limits)); + _localWriteRole = localWriteRole ?? (() => (true, 1)); + if (limits.MaxDemands <= 0 || limits.MaxUnaryOperations <= 0 || limits.MaxUnaryBytes <= 0 || limits.MaxStreams <= 0) throw new ArgumentOutOfRangeException(nameof(limits)); + _catalog.Invalidated += OnCatalogInvalidated; + } + private static bool MetadataMatches(DataMetadata left, DataMetadata right) => + left.Dimensions.SequenceEqual(right.Dimensions) && (left with { Dimensions = right.Dimensions }) == right; + private static ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue EncodeValue(DataMetadata metadata, object? value) + { + if (value is null) return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.Null(); + if (metadata.ValueKind == DataValueKind.Array) + { + if (metadata.ValueRank != 1 || metadata.Dimensions.Count != 1 || metadata.ArrayElementKind is not { } kind || value is not Array array || array.Rank != 1 || + (metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != array.Length)) throw new ArgumentException("Incompatible array shape."); + var values = new object[array.Length]; + for (var i = 0; i < values.Length; i++) + { + var item = array.GetValue(i) ?? throw new ArgumentException("Null array element."); + values[i] = kind == DataValueKind.Timestamp && item is DateTime time ? new DateTimeOffset(time.ToUniversalTime()) : item; + } + return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(kind, values, [array.Length]); + } + if (metadata.ValueKind == DataValueKind.Bytes && value is byte[] bytes) + return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromBytes(bytes); + if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime()); + return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value); + } + private static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata) + { + if (value.Kind == DataValueKind.Null) return null; + if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata."); + if (value.Kind == DataValueKind.Bytes) return value.GetBytes().ToArray(); + if (value.Kind != DataValueKind.Array) return value.GetScalar(); + if (metadata.ValueRank != 1 || metadata.ArrayElementKind != value.ArrayElementKind || value.Dimensions is not { Count: 1 } dims || + metadata.Dimensions.Count != 1 || (metadata.Dimensions[0] != 0 && metadata.Dimensions[0] != dims[0])) throw new ArgumentException("Incompatible array shape."); + var items = value.GetArray(); + return value.ArrayElementKind switch + { + DataValueKind.Boolean => items.Cast().ToArray(), DataValueKind.Int8 => items.Cast().ToArray(), + DataValueKind.UInt8 => items.Cast().ToArray(), DataValueKind.Int16 => items.Cast().ToArray(), + DataValueKind.UInt16 => items.Cast().ToArray(), DataValueKind.Int32 => items.Cast().ToArray(), + DataValueKind.UInt32 => items.Cast().ToArray(), DataValueKind.Int64 => items.Cast().ToArray(), + DataValueKind.UInt64 => items.Cast().ToArray(), DataValueKind.Float => items.Cast().ToArray(), + DataValueKind.Double => items.Cast().ToArray(), DataValueKind.String => items.Cast().ToArray(), + DataValueKind.Timestamp => items.Cast().Select(x => x.UtcDateTime).ToArray(), + DataValueKind.Guid => items.Cast().ToArray(), _ => throw new ArgumentException("Unsupported array element kind.") + }; + } + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) + { + demand = null; + if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) return false; + try + { + if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() || + !_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null || + proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || + ((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) || + proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 || + _connectionForMapping(mapping) is not { Length: > 0 } connectionId) return false; + var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc); + var localRole = operation == DataOperations.Write ? _localWriteRole() : (Allowed: true, Generation: 1L); + if (!localRole.Allowed || localRole.Generation <= 0) return false; + var op = Operation(operation); + if (!_policy.AuthorizeMapped(identity, op, proof.Metadata.View, proof.Lease.Serving, proof.Subject, proof.Resolver, proof.Lease) || + !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false; + if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; } + var candidate = new Demand(this, nodeId, definition, proof, identity, operation, pin, nodePin, connectionId, localRole.Generation, null); + lock (_sync) + { + if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); return false; } + _demands.Add(candidate); + var key = (candidate.Realm, candidate.LocalIdentifier); + _demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1); + } + if (!candidate.IsValid) { candidate.Dispose(); return false; } + demand = candidate; return true; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + internal bool TryAcquireConfigured(NodeId nodeId, ConfiguredProjectionCapability capability, out IProjectedDemandLease? demand) + { + demand = null; + try + { + if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() || + !_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null || + proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) || proof.MaximumSampleAge <= TimeSpan.Zero || + proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 || + (proof.Subject.AllowedOperations & DataOperations.Subscribe) == 0 || !capability.Matches(mapping, proof.Metadata.View, proof.Resolver.LocalAuthority) || + _connectionForMapping(mapping) is not { Length: > 0 } connectionId || !definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return false; + if (!_catalog.TryPinProjected(definition.Realm, definition.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return false; } + var candidate = new Demand(this, nodeId, definition, proof, null, DataOperations.Subscribe, pin, nodePin, connectionId, 1, capability); + lock (_sync) + { + if (_disposed || _demands.Count >= _limits.MaxDemands) { pin.Dispose(); nodePin.Dispose(); return false; } + _demands.Add(candidate); var key = (candidate.Realm, candidate.LocalIdentifier); + _demandCounts.TryGetValue(key, out var count); _demandCounts[key] = checked(count + 1); + } + if (!candidate.IsValid) { candidate.Dispose(); return false; } + demand = candidate; return true; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + internal async ValueTask DisposeConfiguredAsync(IProjectedDemandLease lease) + { + lease.Dispose(); + if (lease is Demand demand) await demand.Completion.ConfigureAwait(false); + } + public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); } + private static OpcUaOperation Operation(DataOperations operation) => operation switch + { + DataOperations.Browse => OpcUaOperation.Browse, + DataOperations.Read => OpcUaOperation.Read, + DataOperations.Write => OpcUaOperation.WriteOperate, + DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems, + _ => throw new ArgumentOutOfRangeException(nameof(operation)) + }; + private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition, + ProjectedNodeProof proof, DataCallerIdentity? caller, DataOperations operation, IDisposable pin, IProjectedNodePin nodePin, string connectionId, long writeRoleGeneration, ConfiguredProjectionCapability? configured) : IProjectedDemandLease + { + private int _disposed; + private int _holds; + private bool _cleaned; + private readonly TaskCompletionSource _completed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly CancellationTokenSource _stop = new(); + internal ProjectedNodeProof Proof => proof; + internal ProjectedVariableDefinition Definition => definition; + internal DataOperations RequestedOperation => operation; + internal bool Disposed => Volatile.Read(ref _disposed) != 0; + internal bool TryHold() { lock (owner._sync) { if (_disposed != 0) return false; _holds++; return true; } } + internal void ReleaseHold() { lock (owner._sync) { _holds--; if (_disposed != 0 && _holds == 0) Cleanup(); } } + private void Cleanup() + { + if (_cleaned) return; + _cleaned = true; + pin.Dispose(); nodePin.Dispose(); owner._demands.Remove(this); + var key = (Realm, LocalIdentifier); var count = owner._demandCounts[key]; + if (count == 1) owner._demandCounts.Remove(key); else owner._demandCounts[key] = count - 1; + _completed.TrySetResult(); + } + internal Task Completion => _completed.Task; + public TimeSpan MaximumSampleAge => proof.MaximumSampleAge; + public DataView OriginView => proof.OriginMetadata.View; + public DataRealm Realm => definition.Realm; + public string LocalIdentifier => definition.LocalIdentifier; + public long ProjectionGeneration => proof.Generation; + public ServingIdentity Serving => proof.Lease.Serving; + public CancellationToken CancellationToken => _stop.Token; + public bool IsValid + { + get + { + if (Volatile.Read(ref _disposed) != 0) return false; + try + { + var role = operation == DataOperations.Write ? owner._localWriteRole() : (Allowed: true, Generation: 1L); + return role.Allowed && role.Generation == writeRoleGeneration && role.Generation > 0 && nodePin.IsValid && definition.AuthorityIsCurrent() && owner._nodes.TryResolve(nodeId, out var now) && now is not null && ReferenceEquals(now.Lifetime, definition.Lifetime) && now.ProjectionGeneration == definition.ProjectionGeneration && now.Metadata.View == definition.Metadata.View && + owner._catalog.TryResolveProjected(Realm, LocalIdentifier, out var current) && ReferenceEquals(current, proof) && + string.Equals(owner._connectionForMapping(proof.Metadata.View.MappingId!), connectionId, StringComparison.OrdinalIgnoreCase) && + (configured is not null ? configured.Matches(proof.Metadata.View.MappingId!, proof.Metadata.View, proof.Resolver.LocalAuthority) && (proof.Subject.AllowedOperations & DataOperations.Subscribe) != 0 : + caller is not null && owner._policy.AuthorizeMapped(caller, Operation(operation), proof.Metadata.View, Serving, proof.Subject, proof.Resolver, proof.Lease)) && + Volatile.Read(ref _disposed) == 0; + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + } + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _ = _stop.CancelAsync(); + lock (owner._sync) + { + if (owner._demandCohorts.TryGetValue(this, out var cohort)) cohort.Remove(this); + if (_holds == 0) Cleanup(); + } + } + } + private sealed record SourceKey(string Connection, DataView View, ServingIdentity Serving, long Generation); + private sealed class SourceState : IProjectedSamplePublicationProof + { + private readonly ProjectedDataAccess _owner; private readonly SourceKey _key; private readonly ProjectedValueRoute _route; + private ProjectedNodeProof? _proof; private ProjectedVariableDefinition? _definition; private IDisposable? _pin; private IProjectedNodePin? _nodePin; + internal readonly object Gate = new(); internal long LastVersion; + internal string MappingId { get; } + internal SourceState(ProjectedDataAccess owner, SourceKey key, ProjectedNodeProof proof, ProjectedVariableDefinition definition, + IDisposable pin, IProjectedNodePin nodePin, ProjectedValueRoute route) + { _owner = owner; _key = key; _proof = proof; _definition = definition; _pin = pin; _nodePin = nodePin; _route = route; MappingId = proof.Metadata.View.MappingId!; } + internal ProjectedValueRoute Route => _route; + public TimeProvider Clock => _owner.Clock; + public bool IsValid + { + get + { + lock (Gate) + { + var proof = _proof; var definition = _definition; + try { return proof is not null && definition is not null && _nodePin is { IsValid: true } && definition.AuthorityIsCurrent() && proof.Lease.IsValid && + _owner._catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var now) && ReferenceEquals(now, proof) && + string.Equals(_owner._connectionForMapping(proof.Metadata.View.MappingId!), _key.Connection, StringComparison.OrdinalIgnoreCase); } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return false; } + } + } + } + public void Invalidate() + { + IDisposable? pin; IProjectedNodePin? nodePin; + lock (Gate) + { + if (_proof is null) return; + _proof = null; _definition = null; pin = _pin; _pin = null; nodePin = _nodePin; _nodePin = null; + } + try { _owner._publisher.Retire(_route); } + catch (Exception) { } + finally { nodePin?.Dispose(); pin?.Dispose(); } + } + } + private bool RemoveSourceLocked(SourceKey key, out SourceState? source) + { + if (!_sources.Remove(key, out source)) return false; + if (_sourceSweepNodes.Remove(key, out var sweep)) _sourceSweep.Remove(sweep); + if (_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) + { + keys.Remove(key); + if (keys.Count == 0) + { + _sourcesByMapping.TryRemove(source.MappingId, out _); + lock (_sourceRetirementGate) _pendingSourceRetirement.Remove(source.MappingId); + } + } + return true; + } + private void OnCatalogInvalidated(string mapping, long generation) + { + // Mapping activation may hold its own lock. Never acquire the data-access + // lock on this callback; publication is allowed to consult mapping authority. + lock (_sourceRetirementGate) + { + if (Volatile.Read(ref _disposed) || !_sourcesByMapping.ContainsKey(mapping)) return; + _pendingSourceRetirement[mapping] = generation; + if (_sourceRetirementRunning) return; + _sourceRetirementRunning = true; _ = Task.Run(RetireInvalidatedSources); + } + } + private void RetireInvalidatedSources() + { + BeforeSourceRetirementForTests?.Invoke(); + while (true) + { + SourceState[] retired; + KeyValuePair item; + lock (_sourceRetirementGate) + { + if (_pendingSourceRetirement.Count == 0) { _sourceRetirementRunning = false; return; } + item = _pendingSourceRetirement.First(); _pendingSourceRetirement.Remove(item.Key); + } + lock (_sync) + { + var list = new List(); + if (_sourcesByMapping.TryGetValue(item.Key, out var keys)) + foreach (var key in keys.Where(key => key.Generation != item.Value).ToArray()) + if (RemoveSourceLocked(key, out var state) && state is not null) list.Add(state); + retired = list.ToArray(); + } + foreach (var source in retired) source.Invalidate(); + } + } + private SourceState? GetSource(Demand demand, string connection) + { + var proof = demand.Proof; var key = new SourceKey(connection.ToUpperInvariant(), demand.OriginView, demand.Serving, demand.ProjectionGeneration); + lock (_sync) + { + if (_sources.TryGetValue(key, out var existing)) + { + if (existing.IsValid) return existing; + RemoveSourceLocked(key, out _); existing.Invalidate(); + } + if (_sources.Count >= _limits.MaxDemands) + { + var count = Math.Min(16, _sourceSweep.Count); + for (var i = 0; i < count && _sourceSweep.First is { } first; i++) + { + var sourceKey = first.Value; var state = _sources[sourceKey]; + if (!state.IsValid) { RemoveSourceLocked(sourceKey, out _); state.Invalidate(); } + else { _sourceSweep.RemoveFirst(); _sourceSweep.AddLast(first); } + } + } + if (_sources.Count >= _limits.MaxDemands || !demand.Definition.Lifetime.TryPin(out var nodePin) || nodePin is null) return null; + if (!_catalog.TryPinProjected(demand.Realm, demand.LocalIdentifier, out var pin) || pin is null) { nodePin.Dispose(); return null; } + var route = new ProjectedValueRoute("grpc-data:" + connection, ProjectedDataIds.DependencyReference(demand.Realm, demand.LocalIdentifier), + demand.Realm, demand.LocalIdentifier, demand.ProjectionGeneration, demand.Serving, Guid.NewGuid()); + var source = new SourceState(this, key, proof, demand.Definition, pin, nodePin, route); + if (!source.IsValid || !_publisher.TryBind(route)) { source.Invalidate(); return null; } + _sources.Add(key, source); _sourceSweepNodes.Add(key, _sourceSweep.AddLast(key)); + if (!_sourcesByMapping.TryGetValue(source.MappingId, out var keys)) _sourcesByMapping[source.MappingId] = keys = new(); + keys.Add(key); + // Attach before the final authority check: invalidation either observes this + // bucket or is detected here, so no source can strand its physical pins. + if (!source.IsValid) { RemoveSourceLocked(key, out _); source.Invalidate(); return null; } + return source; + } + } + public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) + { + if (demand is not Demand item || item.RequestedOperation != DataOperations.Read || !item.IsValid || budget is null) return false; + try { budget.Validate(); } catch (ArgumentException) { return false; } + var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp()); + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout) return false; + lock (_sync) + { + if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) return false; + _unaryCount++; _unaryBytes += budget.MaxBytes; + } + _ = Task.Run(() => ReadCoreAsync(item, budget, requestStartedTimestamp)); return true; + } + private async Task ReadCoreAsync(Demand demand, DataBudget budget, long started) + { + IGrpcDataAdapterConnectionLease? connection = null; + try + { + var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (remaining <= TimeSpan.Zero || !demand.IsValid) return; + var connectionId = _connectionForMapping(demand.Proof.Metadata.View.MappingId!); + if (string.IsNullOrWhiteSpace(connectionId)) return; + using var timeout = new CancellationTokenSource(remaining, Clock); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, demand.CancellationToken); + connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false); + if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || !demand.IsValid) return; + using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken); + var result = await connection.Connection.ReadAsync(new DataReadRequest([new ReadItem("0", demand.OriginView, null)], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); + try + { + if (result.Count != 1 || result[0].CorrelationId != "0" || result[0].Status != DataItemStatus.Good || result[0].Readiness != DataReadiness.Ready || + result[0].Sample is not { } sample || sample.Serving != demand.Serving || sample.Version <= 0 || !demand.IsValid || route.IsCancellationRequested) return; + result[0].AgeBounds.Validate(); + if (!result[0].AgeBounds.IsFresh(demand.MaximumSampleAge)) return; + if (sample.Value.EstimatedRetainedBytes > budget.MaxBytes) return; + var payload = DecodeValue(sample.Value, demand.Proof.OriginMetadata); + var snapshot = new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime); + var received = Clock.GetTimestamp(); var source = GetSource(demand, connectionId); + if (source is null) return; + lock (source.Gate) + { + if (!demand.IsValid || !source.IsValid || sample.Version <= source.LastVersion) return; + if (_publisher.TryPublish([new(source.Route, snapshot, result[0].AgeBounds, received, source, true, demand.MaximumSampleAge)])) source.LastVersion = sample.Version; + else source.Invalidate(); + } + } + finally { foreach (var item in result) item.Dispose(); } + } + catch (Exception) { } + finally + { + try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } + finally { demand.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } } + } + } + public async Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, + long requestStartedTimestamp, CancellationToken cancellationToken) + { + var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null); + var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null); + if (demand is not Demand item || item.RequestedOperation != DataOperations.Write || !item.IsValid || budget is null || cancellationToken.IsCancellationRequested) return rejected; + ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue owned; + try + { + budget.Validate(); + owned = EncodeValue(item.Proof.OriginMetadata, value); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { return rejected; } + var elapsed = Clock.GetElapsedTime(requestStartedTimestamp, Clock.GetTimestamp()); + if (elapsed < TimeSpan.Zero || elapsed >= budget.Timeout || owned.EstimatedRetainedBytes > budget.MaxBytes) { owned.Dispose(); return rejected; } + lock (_sync) + { + if (_disposed || _unaryCount >= _limits.MaxUnaryOperations || budget.MaxBytes > _limits.MaxUnaryBytes - _unaryBytes || !item.TryHold()) { owned.Dispose(); return rejected; } + _unaryCount++; _unaryBytes += budget.MaxBytes; + } + var task = Task.Run(() => WriteCoreAsync(item, owned, budget, requestStartedTimestamp, cancellationToken)); + try { return await task.WaitAsync(budget.Timeout - elapsed, Clock, cancellationToken).ConfigureAwait(false); } + catch (OperationCanceledException) { return unknown; } + catch (TimeoutException) { return unknown; } + } + private async Task WriteCoreAsync(Demand demand, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataBudget budget, long started, CancellationToken callerStop) + { + var rejected = new DataWriteOutcome(DataWriteState.RejectedBeforeDispatch, StatusCodes.BadNotConnected.Code, null); + var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, StatusCodes.BadTimeout.Code, null); + IGrpcDataAdapterConnectionLease? connection = null; var dispatched = false; + try + { + var remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (remaining <= TimeSpan.Zero || !demand.IsValid || callerStop.IsCancellationRequested) return rejected; + var connectionId = _connectionForMapping(demand.Proof.Metadata.View.MappingId!); + if (string.IsNullOrWhiteSpace(connectionId)) return rejected; + using var timeout = new CancellationTokenSource(remaining, Clock); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, callerStop, demand.CancellationToken); + connection = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false); + if (connection is null || !ReferenceEquals(connection.Connection.Clock, Clock) || connection.CancellationToken.IsCancellationRequested || !demand.IsValid) return rejected; + remaining = budget.Timeout - Clock.GetElapsedTime(started, Clock.GetTimestamp()); + if (remaining <= TimeSpan.Zero || linked.IsCancellationRequested) return rejected; + using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken); + var correlation = Guid.NewGuid().ToString("N"); + var item = new WriteItem(correlation, Guid.NewGuid().ToString("N"), demand.OriginView, value, + demand.Proof.OriginMetadata.CatalogRevision, demand.Serving.Incarnation, remaining, demand.Serving.ServingGeneration); + dispatched = true; + var results = await connection.Connection.WriteAsync(new WriteBatch([item], budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); + if (results.Count != 1 || results[0].CorrelationId != correlation) return unknown; + return results[0].Outcome; + } + catch (Exception) { return dispatched ? unknown : rejected; } + finally + { + try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } + finally { value.Dispose(); demand.ReleaseHold(); lock (_sync) { _unaryCount--; _unaryBytes -= budget.MaxBytes; } } + } + } + private sealed record CohortKey(string Connection, ServingIdentity Serving, TimeSpan Interval); + public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) + { + if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || publishingInterval <= TimeSpan.Zero || !item.IsValid) return false; + var connection = _connectionForMapping(item.Proof.Metadata.View.MappingId!); + if (string.IsNullOrWhiteSpace(connection)) return false; + var key = new CohortKey(connection.ToUpperInvariant(), item.Serving, publishingInterval); + lock (_sync) + { + if (_disposed || _demandCohorts.ContainsKey(item)) return false; + var created = false; + if (!_cohorts.TryGetValue(key, out var cohort)) + { + if (_cohorts.Count >= _limits.MaxStreams) return false; + cohort = new Cohort(this, key, connection); _cohorts.Add(key, cohort); created = true; + } + if (cohort.Closing || !item.TryHold()) { if (created) _cohorts.Remove(key); return false; } + _demandCohorts.Add(item, cohort); + if (!cohort.Add(item)) { _demandCohorts.Remove(item); item.ReleaseHold(); if (created) _cohorts.Remove(key); return false; } + cohort.Start(); return true; + } + } + private sealed class Cohort + { + private abstract record Event; + private sealed record AddEvent(Demand Demand) : Event; + private sealed record RemoveEvent(Demand Demand) : Event; + private sealed record FrameEvent(DataSubscriptionFrame Frame, long Bytes) : Event; + private sealed record EndEvent : Event; + private sealed class Registration(Demand demand, string id) + { internal readonly Demand Demand = demand; internal readonly string Id = id; internal DataItemHandle? Handle; internal bool Removed; } + private readonly ProjectedDataAccess _owner; + private readonly CohortKey _key; + private readonly string _connectionId; + private readonly Channel _events; + private readonly CancellationTokenSource _stop = new(); + private readonly Dictionary _registrations = new(); + private readonly Dictionary _byId = new(StringComparer.Ordinal); + private readonly Dictionary _byHandle = new(); + private readonly Dictionary _removing = new(StringComparer.Ordinal); + private readonly string _id = Guid.NewGuid().ToString("N"); + private const long Epoch = 1; + private int _started, _closing, _restart; + private long _sequence; + private long _frameBytes; + internal bool Closing => Volatile.Read(ref _closing) != 0; + internal Cohort(ProjectedDataAccess owner, CohortKey key, string connectionId) + { + _owner = owner; _key = key; _connectionId = connectionId; + _events = Channel.CreateBounded(new BoundedChannelOptions(Math.Clamp(owner._limits.MaxDemands * 2, 4, 128)) + { SingleReader = true, FullMode = BoundedChannelFullMode.Wait }); + } + internal bool Add(Demand demand) => _events.Writer.TryWrite(new AddEvent(demand)); + internal void Remove(Demand demand) { if (!_events.Writer.TryWrite(new RemoveEvent(demand))) Stop(); } + internal void Start() { if (Interlocked.Exchange(ref _started, 1) == 0) _ = Task.Run(RunAsync); } + internal void Stop() { if (Interlocked.Exchange(ref _closing, 1) == 0) _ = _stop.CancelAsync(); } + internal bool Restart() + { + if (Volatile.Read(ref _restart) != 0) return true; + if (Closing) return false; + Interlocked.Exchange(ref _restart, 1); Stop(); return true; + } + private async Task PumpAsync(IDataSubscription stream) + { + try + { + await foreach (var frame in stream.ReadAllAsync(_stop.Token).ConfigureAwait(false)) + { + var bytes = frame is DataSubscriptionValues values ? checked(512L + values.Items.Sum(x => x.Sample.Value.EstimatedRetainedBytes)) : 512L; + if (bytes > _owner._limits.MaxUnaryBytes || Interlocked.Add(ref _frameBytes, bytes) > _owner._limits.MaxUnaryBytes) + { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); break; } + try { await _events.Writer.WriteAsync(new FrameEvent(frame, bytes), _stop.Token).ConfigureAwait(false); } + catch { Interlocked.Add(ref _frameBytes, -bytes); (frame as IDisposable)?.Dispose(); throw; } + } + } + catch (Exception) { } + finally { _events.Writer.TryWrite(new EndEvent()); } + } + private DataSubscriptionItem Item(Registration registration) => new(registration.Id, registration.Demand.OriginView, + new DataSubscriptionSettings(_key.Interval, _key.Interval, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataChangeTrigger.StatusValueTimestamp, null)); + private async Task RunAsync() + { + IGrpcDataAdapterConnectionLease? connection = null; IDataSubscription? stream = null; Task? pump = null; + var opened = false; var inSnapshot = false; long snapshotBytes = 0; + var pending = new List<(Registration Registration, ProjectedValueUpdate Update, long Version)>(); + try + { + connection = await _owner._connections.AcquireAsync(_connectionId, _stop.Token).ConfigureAwait(false); + if (connection is null || !ReferenceEquals(connection.Connection.Clock, _owner.Clock) || connection.CancellationToken.IsCancellationRequested) return; + using var route = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token, connection.CancellationToken); + stream = await connection.Connection.SubscribeAsync(route.Token).ConfigureAwait(false); + if (stream is not IDataSubscriptionProvenance provenance || provenance.Serving != _key.Serving) return; + pump = PumpAsync(stream); + await foreach (var message in _events.Reader.ReadAllAsync(route.Token).ConfigureAwait(false)) + { + if (message is AddEvent add) + { + if (!add.Demand.IsValid) continue; + var registration = new Registration(add.Demand, Guid.NewGuid().ToString("N")); + _registrations[add.Demand] = registration; _byId[registration.Id] = registration; + DataSubscriptionCommand command = !opened + ? new OpenSubscription(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)], false, TimeSpan.FromMinutes(1), new(TimeSpan.FromSeconds(5), 1, _owner._limits.MaxUnaryBytes)) + : new AddSubscriptionItems(_id, Epoch, Guid.NewGuid().ToString("N"), TimeSpan.FromSeconds(5), [Item(registration)]); + await stream.SendAsync(command, route.Token).ConfigureAwait(false); opened = true; + } + else if (message is RemoveEvent remove) + { + if (_registrations.TryGetValue(remove.Demand, out var registration)) + { + registration.Removed = true; + if (registration.Handle is { } handle) + { + var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; + await stream.SendAsync(new RemoveSubscriptionItems(_id, Epoch, commandId, TimeSpan.FromSeconds(5), [handle]), route.Token).ConfigureAwait(false); + } + } + if (_registrations.Values.All(x => x.Removed)) break; + } + else if (message is EndEvent) break; + else if (message is FrameEvent delivered) + { + var frame = delivered.Frame; + try + { + if (frame.SubscriptionId != _id || frame.StreamEpoch != Epoch || frame.Sequence <= _sequence) break; + _sequence = frame.Sequence; + if (frame is DataSubscriptionAck ack) + { + if (_removing.Remove(ack.CommandId, out var removed)) + { + if (ack.Items.Count != 1 || ack.Items[0].Status != DataItemStatus.Good || ack.Items[0].Handle != removed.Handle || ack.Items[0].ClientItemId != removed.Id) { Stop(); continue; } + _registrations.Remove(removed.Demand); _byId.Remove(removed.Id); + if (removed.Handle is { } removedHandle) _byHandle.Remove(removedHandle); + SourceState? retiredSource = null; + lock (_owner._sync) + { + _owner._demandCohorts.Remove(removed.Demand); + if (!_registrations.Values.Any(x => !x.Removed && x.Demand.OriginView == removed.Demand.OriginView && x.Demand.ProjectionGeneration == removed.Demand.ProjectionGeneration)) + { + var sourceKey = new SourceKey(_key.Connection, removed.Demand.OriginView, _key.Serving, removed.Demand.ProjectionGeneration); + _owner.RemoveSourceLocked(sourceKey, out retiredSource); + } + } + retiredSource?.Invalidate(); + removed.Demand.ReleaseHold(); + } + else foreach (var response in ack.Items) + { + if (!_byId.TryGetValue(response.ClientItemId, out var registration) || response.Status != DataItemStatus.Good || response.Handle is null) { Stop(); break; } + registration.Handle = response.Handle; _byHandle[response.Handle] = registration; + if (registration.Removed) + { + var commandId = Guid.NewGuid().ToString("N"); _removing[commandId] = registration; + await stream.SendAsync(new RemoveSubscriptionItems(_id, Epoch, commandId, TimeSpan.FromSeconds(5), [response.Handle]), route.Token).ConfigureAwait(false); + } + } + } + else if (frame is DataSubscriptionControl control) + { + if (control.CatalogEpoch != _key.Serving.CatalogEpoch || control.AuthorityEpoch != _key.Serving.AuthorityEpoch) break; + if (control.Kind == DataStreamControlKind.SnapshotBegin) { inSnapshot = true; pending.Clear(); snapshotBytes = 0; } + else if (control.Kind == DataStreamControlKind.SnapshotEnd && inSnapshot) + { + foreach (var item in pending) Publish(item.Registration, item.Update with { IsCompleteSnapshot = true }, item.Version); + pending.Clear(); snapshotBytes = 0; inSnapshot = false; + } + else if (control.Kind is DataStreamControlKind.Reset or DataStreamControlKind.CatalogInvalidated or DataStreamControlKind.AuthorityInvalidated) break; + } + else if (frame is DataSubscriptionValues values) + { + foreach (var item in values.Items) + { + if (!_byHandle.TryGetValue(item.Handle, out var registration) || registration.Removed || !registration.Demand.IsValid || + item.Sample.Serving != _key.Serving || item.Sample.Version <= 0 || item.Readiness != DataReadiness.Ready || + !item.AgeBounds.IsFresh(registration.Demand.MaximumSampleAge) || item.Sample.Value.EstimatedRetainedBytes > _owner._limits.MaxUnaryBytes) + { Stop(); break; } + var source = _owner.GetSource(registration.Demand, _connectionId); if (source is null) { Stop(); break; } + var sample = item.Sample; + var payload = DecodeValue(sample.Value, registration.Demand.Proof.OriginMetadata); + var update = new ProjectedValueUpdate(source.Route, new DataValueSnapshot(payload, sample.StatusCode, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime), + item.AgeBounds, _owner.Clock.GetTimestamp(), source, false, registration.Demand.MaximumSampleAge); + if (inSnapshot) + { + snapshotBytes = checked(snapshotBytes + sample.Value.EstimatedRetainedBytes + 512); + if (pending.Count >= _owner._limits.MaxDemands || snapshotBytes > _owner._limits.MaxUnaryBytes) { Stop(); break; } + pending.Add((registration, update, sample.Version)); + } + else Publish(registration, update, sample.Version); + } + } + } + finally { Interlocked.Add(ref _frameBytes, -delivered.Bytes); (frame as IDisposable)?.Dispose(); } + } + } + } + catch (Exception) { } + finally + { + Stop(); + try { if (stream is not null) await stream.DisposeAsync().ConfigureAwait(false); } + catch (Exception) { } + try { if (pump is not null) await pump.ConfigureAwait(false); } + catch (Exception) { } + try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } + catch (Exception) { } + while (_events.Reader.TryRead(out var remaining)) if (remaining is FrameEvent f) { Interlocked.Add(ref _frameBytes, -f.Bytes); (f.Frame as IDisposable)?.Dispose(); } + Demand[] owned; var transferred = new HashSet(); var retired = new List(); + lock (_owner._sync) + { + owned = _owner._demandCohorts.Where(x => ReferenceEquals(x.Value, this)).Select(x => x.Key).ToArray(); + foreach (var item in owned) _owner._demandCohorts.Remove(item); + if (_owner._cohorts.TryGetValue(_key, out var current) && ReferenceEquals(current, this)) _owner._cohorts.Remove(_key); + foreach (var item in owned) + { + var sourceKey = new SourceKey(_key.Connection, item.OriginView, _key.Serving, item.ProjectionGeneration); + if (_owner.RemoveSourceLocked(sourceKey, out var state) && state is not null) retired.Add(state); + } + } + foreach (var source in retired) source.Invalidate(); + lock (_owner._sync) + { + if (Volatile.Read(ref _restart) != 0 && !_owner._disposed) + { + var eligible = owned.Where(d => !d.Disposed).ToArray(); + if (eligible.Length > 0 && !_owner._cohorts.ContainsKey(_key) && _owner._cohorts.Count < _owner._limits.MaxStreams) + { + var replacement = new Cohort(_owner, _key, _connectionId); _owner._cohorts.Add(_key, replacement); + foreach (var demand in eligible) + if (replacement.Add(demand)) { _owner._demandCohorts[demand] = replacement; transferred.Add(demand); } + if (transferred.Count > 0) replacement.Start(); else _owner._cohorts.Remove(_key); + } + } + } + foreach (var item in owned) if (!transferred.Contains(item)) { item.Dispose(); item.ReleaseHold(); } + _stop.Dispose(); + } + } + private void Publish(Registration registration, ProjectedValueUpdate update, long version) + { + if (!registration.Demand.IsValid || update.SourceProof is not SourceState source) return; + lock (source.Gate) + { + if (!source.IsValid || version <= source.LastVersion) return; + if (_owner._publisher.TryPublish([update])) source.LastVersion = version; else source.Invalidate(); + } + } + } + public bool RequestFreshSnapshot(IProjectedDemandLease demand) + { + if (demand is not Demand item || item.RequestedOperation != DataOperations.Subscribe || !item.IsValid) return false; + lock (_sync) return !_disposed && _demandCohorts.TryGetValue(item, out var cohort) && cohort.Restart(); + } + public void Dispose() + { + _catalog.Invalidated -= OnCatalogInvalidated; + Demand[] demands; + lock (_sync) { if (_disposed) return; _disposed = true; demands = _demands.ToArray(); } + foreach (var demand in demands) demand.Dispose(); + Cohort[] cohorts; + lock (_sync) cohorts = _cohorts.Values.ToArray(); + foreach (var cohort in cohorts) cohort.Stop(); + SourceState[] sources; + lock (_sync) { sources = _sources.Values.ToArray(); _sources.Clear(); _sourcesByMapping.Clear(); _sourceSweep.Clear(); _sourceSweepNodes.Clear(); lock (_sourceRetirementGate) _pendingSourceRetirement.Clear(); } + foreach (var source in sources) source.Invalidate(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs new file mode 100644 index 000000000..bd20a8635 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedMappingDeploymentRuntime.cs @@ -0,0 +1,249 @@ +using System.Text.Json; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// A mapped root placed under an applied local catalog parent. +public sealed record ProjectedMappingPlacement(RemoteNamespaceMapping Mapping, DataView Parent, DataView Anchor, + NodeScope Scope, IReadOnlyList LocalAncestry, IDataMappedCatalogAuthority Authority); + +/// Owns mapping placements tied to one activated catalog attempt. +public sealed class ProjectedMappingDeploymentRuntime : IDisposable +{ + private readonly object _gate = new(); + private readonly LocalCatalogCoordinator _coordinator; + private readonly RemoteNamespaceResolver _resolver; + private CatalogAttempt? _attempt; + private RemoteNamespaceMapping[] _staged = []; + private DataConnection[] _connections = []; + private IReadOnlyList _active = Array.Empty(); + private Dictionary _byMapping = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _configuredCapabilities = new(StringComparer.OrdinalIgnoreCase); + private object _configuredStamp = new(); + private bool _disposed; + + public ProjectedMappingDeploymentRuntime(LocalCatalogCoordinator coordinator, RemoteNamespaceResolver resolver) + { + _coordinator = coordinator ?? throw new ArgumentNullException(nameof(coordinator)); + _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); + _coordinator.AttachProjectedMappings(this); + } + + private static T Copy(T value) => JsonSerializer.Deserialize(JsonSerializer.SerializeToUtf8Bytes(value))!; + private long _placementCopiesForTests; + internal long PlacementCopiesForTests => Interlocked.Read(ref _placementCopiesForTests); + private IReadOnlyList CopyPlacements(IReadOnlyList source) + { + Interlocked.Add(ref _placementCopiesForTests, source.Count); + return Array.AsReadOnly(source.Select(x => x with { Mapping = Copy(x.Mapping) }).ToArray()); + } + // Mint only from an exact currently published placement. The capability guard is + // deliberately lock-free: cache validation can run under the cache lock while a + // mapping transition holds _gate and calls into that cache. + internal bool TryAcquireConfiguredCapability(string mappingId, DataRealm realm, + out ConfiguredProjectionCapability? capability, out ProjectedMappingPlacement? placement) + { + capability = null; + placement = null; + lock (_gate) + { + if (_disposed || _attempt is null || !_byMapping.TryGetValue(mappingId, out var original) || + !original.Authority.IsActive || original.Mapping.Realm != realm || original.Mapping.RemoteRealm != realm || + !original.Mapping.Enabled || + (original.Mapping.AllowedOperations & (DataOperations.Browse | DataOperations.Subscribe)) != + (DataOperations.Browse | DataOperations.Subscribe)) return false; + var catalog = _coordinator.MappingCatalog(_attempt); + if (catalog is null || !ReferenceEquals(catalog.MappingAuthority, original.Authority)) return false; + var published = Volatile.Read(ref _active); + if (!published.Any(item => ReferenceEquals(item, original))) return false; + placement = CopyPlacements([original])[0]; + if (!_configuredCapabilities.TryGetValue(original.Mapping.RemoteNamespaceMappingId, out capability)) + { + var stamp = Volatile.Read(ref _configuredStamp); + capability = new ConfiguredProjectionCapability(original.Mapping.RemoteNamespaceMappingId, original.Mapping.Revision, + original.Mapping.Realm, original.Mapping.AllowedOperations, original.Authority, + () => ReferenceEquals(Volatile.Read(ref _configuredStamp), stamp)); + _configuredCapabilities.Add(original.Mapping.RemoteNamespaceMappingId, capability); + } + return true; + } + } + + internal bool IsCurrentPlacement(ProjectedMappingPlacement placement) + { + lock (_gate) + { + if (_disposed || _attempt is null || !placement.Authority.IsActive || + !_byMapping.TryGetValue(placement.Mapping.RemoteNamespaceMappingId, out var current) || + !ReferenceEquals(current.Authority, placement.Authority) || + current.Mapping.RemoteNamespaceMappingId != placement.Mapping.RemoteNamespaceMappingId || + current.Mapping.Revision != placement.Mapping.Revision || + !string.Equals(current.Mapping.DataConnectionId, placement.Mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) || + current.Parent != placement.Parent || current.Anchor != placement.Anchor) return false; + var catalog = _coordinator.MappingCatalog(_attempt); + return catalog is not null && ReferenceEquals(catalog.MappingAuthority, current.Authority); + } + } + + public IReadOnlyList Active + { + get + { + lock (_gate) + return _active.All(x => x.Authority.IsActive) ? CopyPlacements(_active) : Array.Empty(); + } + } + public event Action>? Changed; + /// Resolve a mapping only while its original activated authority remains current. + public bool TryGetConnectionId(string mappingId, out string? connectionId) + { + lock (_gate) + { + connectionId = null; + if (_disposed || _attempt is null || !_byMapping.TryGetValue(mappingId, out var placement) || !placement.Authority.IsActive) + return false; + var current = _coordinator.MappingCatalog(_attempt); + if (current is null || !ReferenceEquals(current.MappingAuthority, placement.Authority)) return false; + connectionId = placement.Mapping.DataConnectionId; + return true; + } + } + + public void Stage(CatalogAttempt attempt, IReadOnlyList mappings, IReadOnlyList connections) + { + ArgumentNullException.ThrowIfNull(attempt); + ArgumentNullException.ThrowIfNull(mappings); + ArgumentNullException.ThrowIfNull(connections); + var frozenMappings = mappings.Select(Copy).ToArray(); + var frozenConnections = connections.Select(Copy).ToArray(); + lock (_gate) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!ReferenceEquals(attempt, _attempt)) return; + _staged = frozenMappings; + _connections = frozenConnections; + } + } + + internal void AttemptBegan(CatalogAttempt attempt) + { + bool changed; + lock (_gate) + { + if (_disposed || _attempt is not null && attempt.Epoch <= _attempt.Epoch) return; + _attempt = attempt; + Volatile.Write(ref _configuredStamp, new object()); + _configuredCapabilities.Clear(); + _staged = []; _connections = []; + changed = _active.Count != 0; + Volatile.Write(ref _active, Array.Empty()); + _byMapping.Clear(); + _resolver.ApplyMappings([]); + } + if (changed) Notify([]); + } + + internal void AttemptCompleted(CatalogAttempt attempt, bool completed) + { + IReadOnlyList published; + lock (_gate) + { + if (_disposed || !ReferenceEquals(_attempt, attempt)) return; + Volatile.Write(ref _configuredStamp, new object()); + _configuredCapabilities.Clear(); + var catalog = completed ? _coordinator.MappingCatalog(attempt) : null; + if (catalog is null || !catalog.IsActive) + { + _resolver.ApplyMappings([]); + Volatile.Write(ref _active, Array.Empty()); + } + else + { + try + { + var placements = Build(catalog, _staged, _connections); + var bindings = placements.Select(p => new ProjectedMappingBinding(p.Mapping, p.Anchor, p.Scope, + p.LocalAncestry, p.Authority, (_, _) => false)).ToArray(); + _resolver.ApplyMappings(bindings); + var current = _coordinator.MappingCatalog(attempt); + if (current is null || !ReferenceEquals(current.MappingAuthority, catalog.MappingAuthority) || !catalog.IsActive) + throw new InvalidOperationException("Catalog attempt changed during projection activation."); + Volatile.Write(ref _active, Array.AsReadOnly(placements)); + } + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException) + { + _resolver.ApplyMappings([]); + Volatile.Write(ref _active, Array.Empty()); + } + } + _byMapping = _active.ToDictionary(x => x.Mapping.RemoteNamespaceMappingId, StringComparer.OrdinalIgnoreCase); + published = CopyPlacements(_active); + } + Notify(published); + } + + private static ProjectedMappingPlacement[] Build(LocalExportCatalog catalog, IReadOnlyList mappings, + IReadOnlyList connections) + { + var placements = new List(); + foreach (var mapping in mappings.Where(x => x.Enabled)) + { + var parentMatches = catalog.Nodes.Where(x => x.EntityKind == mapping.LocalParentKind && + string.Equals(x.EntityId, mapping.LocalParentId, StringComparison.OrdinalIgnoreCase) && x.Metadata.View.Realm == mapping.Realm).ToArray(); + var connectionMatches = connections.Where(x => x.Enabled && string.Equals(x.DataConnectionId, mapping.DataConnectionId, StringComparison.OrdinalIgnoreCase) && + string.Equals(x.ClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (parentMatches.Length != 1 || connectionMatches.Length != 1 || string.IsNullOrWhiteSpace(connectionMatches[0].ExpectedClusterId) || + !string.Equals(mapping.ClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(mapping.BranchName) || + mapping.BranchName.Contains('/') || mapping.BranchName.Contains('\\') || mapping.Realm != mapping.RemoteRealm || + catalog.Children(parentMatches[0]).Any(x => string.Equals(x.Metadata.BrowseName, mapping.BranchName, StringComparison.OrdinalIgnoreCase)) || + placements.Any(x => x.Parent == parentMatches[0].Metadata.View && string.Equals(x.Mapping.BranchName, mapping.BranchName, StringComparison.OrdinalIgnoreCase))) + throw new ArgumentException("Invalid or colliding mapping placement."); + var parent = parentMatches[0]; + var ancestry = new List(); + var cursor = parent; + var seen = new HashSet(); + while (true) + { + if (!seen.Add(cursor.Metadata.View)) throw new ArgumentException("Catalog parent cycle."); + ancestry.Add(cursor.EntityId); + if (cursor.Parent is null) break; + if (!catalog.TryResolve(cursor.Parent, out cursor!)) throw new ArgumentException("Catalog parent missing."); + } + ancestry.Reverse(); + var segments = Array.AsReadOnly(parent.Scope.Segments.Concat([mapping.BranchName]).ToArray()); + var scope = parent.Scope with { Segments = segments }; + var address = new DataAddress(connectionMatches[0].ExpectedClusterId, mapping.RemoteNamespaceUri, + mapping.RemoteIdentifierKind, mapping.RemoteIdentifier); + var anchor = new DataView(address, mapping.Realm, mapping.RemoteNamespaceMappingId, mapping.Revision, string.Join('/', segments)); + anchor.Validate(); + placements.Add(new(mapping, parent.Metadata.View, anchor, scope, Array.AsReadOnly(ancestry.ToArray()), catalog.MappingAuthority)); + } + return placements.ToArray(); + } + + private void Notify(IReadOnlyList placements) + { + var handlers = Changed; + if (handlers is null) return; + foreach (Action> handler in handlers.GetInvocationList()) + try { handler(CopyPlacements(placements)); } catch (Exception) { } + } + + public void Dispose() + { + lock (_gate) + { + if (_disposed) return; + _disposed = true; + Volatile.Write(ref _configuredStamp, new object()); + _configuredCapabilities.Clear(); + Volatile.Write(ref _active, Array.Empty()); + _byMapping.Clear(); + _resolver.ApplyMappings([]); + _coordinator.DetachProjectedMappings(this); + } + Notify([]); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs new file mode 100644 index 000000000..f25055075 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedNamespaceApplier.cs @@ -0,0 +1,132 @@ +using Opc.Ua; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Prepares bounded remote pages and hands them to the local atomic publication boundary. +public sealed class ProjectedNamespaceApplier : IDisposable +{ + private readonly IFederatedProjectionCatalog _catalog; + private readonly IProjectedNamespacePageSink _sink; + private readonly SemaphoreSlim _slots; + private readonly CancellationTokenSource _stop = new(); + private int _disposed; + + public ProjectedNamespaceApplier(IFederatedProjectionCatalog catalog, IProjectedNamespacePageSink sink, int maxConcurrent) + { + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _sink = sink ?? throw new ArgumentNullException(nameof(sink)); + if (maxConcurrent <= 0) throw new ArgumentOutOfRangeException(nameof(maxConcurrent)); + _slots = new(maxConcurrent, maxConcurrent); + } + + private sealed class CommitState(long generation, ServingIdentity serving) + { + private int _aborted; + internal long Generation => generation; + internal ServingIdentity Serving => serving; + internal bool Aborted => Volatile.Read(ref _aborted) != 0; + internal void Abort() => Interlocked.Exchange(ref _aborted, 1); + } + + // This object deliberately owns one frozen item and small shared control only. A bound method + // must never capture the preparation frame, its siblings, request, linked CTS or cursor owner. + private sealed class ItemGuard : IProjectedRetainedAuthority + { + internal readonly ProjectedNodeProof Proof; + private readonly CommitState _state; + private readonly CancellationToken _stop; + internal ItemGuard(ProjectedNodeProof proof, CommitState state, CancellationToken stop) + { + Proof = proof with + { + Metadata = proof.Metadata with { Dimensions = Array.AsReadOnly(proof.Metadata.Dimensions.ToArray()) }, + OriginMetadata = proof.OriginMetadata with { Dimensions = Array.AsReadOnly(proof.OriginMetadata.Dimensions.ToArray()) }, + Subject = proof.Subject with + { + Scope = proof.Subject.Scope with { Segments = Array.AsReadOnly(proof.Subject.Scope.Segments.ToArray()) }, + LocalAncestry = Array.AsReadOnly(proof.Subject.LocalAncestry.ToArray()) + } + }; + _state = state; _stop = stop; + RetainedBytes = checked(2048L + ProjectedProofSize.Estimate(Proof)); + } + public long RetainedBytes { get; } + public bool IsCurrent() + { + try + { + return !_state.Aborted && !_stop.IsCancellationRequested && Proof.Generation == _state.Generation && + Proof.Lease.Serving == _state.Serving && Proof.Resolver.LocalAuthority.IsActive && + Proof.Resolver.Resolve(Proof.Metadata.View, Proof.Subject).Kind == MappedSubjectResolutionKind.Mapped && Proof.Lease.IsValid; + } + catch (Exception) { return false; } + } + + } + + public async Task ApplyPageAsync(ProjectedBrowseRequest request, NodeId exactParent, CancellationToken cancellationToken) => + await ApplyPageResultAsync(request, exactParent, cancellationToken).ConfigureAwait(false) == ProjectionPageStatus.Ready; + + public async Task ApplyPageResultAsync(ProjectedBrowseRequest request, NodeId exactParent, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (Volatile.Read(ref _disposed) != 0 || !_slots.Wait(0)) return ProjectionPageStatus.Unavailable; + try + { + request.Budget.Validate(); + var elapsed = _catalog.Clock.GetElapsedTime(request.RequestStartedTimestamp, _catalog.Clock.GetTimestamp()); + var remaining = request.Budget.Timeout - elapsed; + if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return ProjectionPageStatus.Unavailable; + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _stop.Token); + linked.CancelAfter(remaining); + using var prepared = await _catalog.PreparePageAsync(request, linked.Token).ConfigureAwait(false); + var page = prepared.Snapshot; + if (page.Status != ProjectionPageStatus.Ready) return page.Status; + if (page.Generation <= 0 || page.Lease is not { IsValid: true } pageLease || page.LocalAuthority is not { IsActive: true } local || + page.Items.Count > request.Budget.MaxItems) return ProjectionPageStatus.Unavailable; + var state = new CommitState(page.Generation, pageLease.Serving); + var guards = page.Items.Select(item => new ItemGuard(item, state, _stop.Token)).ToArray(); + var root = page.ParentProof is { } parentProof ? new ItemGuard(parentProof, state, _stop.Token) : null; + bool PageCurrent() => Volatile.Read(ref _disposed) == 0 && !linked.IsCancellationRequested && + !state.Aborted && local.IsActive && pageLease.IsValid; + if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent()) + return ProjectionPageStatus.Unavailable; + var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm, + guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray(); + var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata); + if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable; + var attempted = 0; + var committed = false; + var accepted = false; + bool Commit() + { + if (Interlocked.Exchange(ref attempted, 1) != 0 || !PageCurrent() || + guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent()) return false; + committed = prepared.TryCommit(); + return committed && PageCurrent(); + } + try + { + accepted = rootLeaf + ? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm, + root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit) + : _sink.TryApply(exactParent, definitions, Commit); + return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable; + } + // Successful SDK/cache acceptance publishes shared metadata. A later caller timeout + // does not revoke it; its independent lease/deployment guards still fence every use. + finally { if (!accepted || !committed) state.Abort(); } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || _stop.IsCancellationRequested) { return ProjectionPageStatus.Unavailable; } + catch (OperationCanceledException) { return ProjectionPageStatus.Unavailable; } + finally { _slots.Release(); } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) _stop.Cancel(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedProofSize.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedProofSize.cs new file mode 100644 index 000000000..bca5f0f13 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedProofSize.cs @@ -0,0 +1,23 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Conservative retained size of one detached projected proof, including both metadata views. +internal static class ProjectedProofSize +{ + internal static long Estimate(ProjectedNodeProof proof) => checked(1024L + Text(proof.LocalIdentifier) + + Metadata(proof.Metadata) + Metadata(proof.OriginMetadata) + View(proof.Subject.View) + + Text(proof.Subject.Scope.ClusterId) + Strings(proof.Subject.Scope.Segments) + + Strings(proof.Subject.LocalAncestry) + Serving(proof.Subject.Serving) + Serving(proof.Lease.Serving)); + + private static long Text(string? value) => checked(32L + 2L * (value?.Length ?? 0)); + private static long Strings(IReadOnlyList values) => checked(64L + 8L * values.Count + values.Sum(Text)); + private static long View(DataView view) => checked(128L + Text(view.Subject) + Text(view.MappingId) + + Text(view.Address.OriginClusterId) + Text(view.Address.NamespaceUri) + + Text(view.Address.IdentifierKind) + Text(view.Address.Identifier)); + private static long Serving(ServingIdentity? serving) => serving is null ? 0 : checked(128L + + Text(serving.NodeId) + Text(serving.Incarnation) + Text(serving.Role)); + private static long Metadata(DataMetadata value) => checked(256L + View(value.View) + + Text(value.BrowseName) + Text(value.NodeKind) + Text(value.StableSourceId) + Text(value.EngineeringUnits) + + 64L + 4L * value.Dimensions.Count + Serving(value.Serving)); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs new file mode 100644 index 000000000..e1331ce4e --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -0,0 +1,287 @@ +using System.Collections.ObjectModel; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Trusted placement compiled from an applied mapping and its local catalog authority. +public sealed record ProjectedMappingBinding(RemoteNamespaceMapping Mapping, DataView LocalAnchor, NodeScope LocalScope, + IReadOnlyList LocalAncestry, IDataMappedCatalogAuthority LocalAuthority, Func LocalNameOccupied); + +/// Resolves direct peer browse pages without routing origin-owned exports through a projection. +public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisposable +{ + private readonly object _sync = new(); + private readonly ProjectedCatalogCache _cache; + private readonly BrowseContinuationRegistry _cursors; + private readonly IGrpcDataAdapterConnectionSource _source; + private readonly DataOperationPolicy _policy; + private readonly int _maxMappings; + private readonly SemaphoreSlim _fetchSlots; + private readonly int _maximumWaiters; + private readonly Func? _beforeFetch; + private int _waiterCount; + private sealed record FetchKey(ProjectedBrowseRequest Request, ProjectedMappingBinding Binding); + private sealed class SharedFetch(CancellationTokenSource stop) + { + internal readonly CancellationTokenSource Stop = stop; + internal Task Task = null!; + internal int Waiters; + internal readonly TaskCompletionSource Finished = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + private readonly Dictionary _fetches = new(); + private readonly HashSet _physicalJobs = new(); + private Dictionary _mappings = new(StringComparer.OrdinalIgnoreCase); + private bool _disposed; + public RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors, + IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches) + { + _cache = cache ?? throw new ArgumentNullException(nameof(cache)); _cursors = cursors ?? throw new ArgumentNullException(nameof(cursors)); + _source = source ?? throw new ArgumentNullException(nameof(source)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); + if (maxMappings <= 0 || maxConcurrentFetches <= 0) throw new ArgumentOutOfRangeException(nameof(maxMappings)); + _maxMappings = maxMappings; _fetchSlots = new(maxConcurrentFetches, maxConcurrentFetches); + _maximumWaiters = checked(maxConcurrentFetches * 16); + _cache.Invalidated += OnInvalidated; + } + internal RemoteNamespaceResolver(ProjectedCatalogCache cache, BrowseContinuationRegistry cursors, + IGrpcDataAdapterConnectionSource source, DataOperationPolicy policy, int maxMappings, int maxConcurrentFetches, + Func? beforeFetch) : this(cache, cursors, source, policy, maxMappings, maxConcurrentFetches) + { _beforeFetch = beforeFetch; } + internal int OutstandingPhysicalJobs { get { lock (_sync) return _physicalJobs.Count; } } + internal Task WaitForPhysicalJobsAsync() + { + lock (_sync) return Task.WhenAll(_physicalJobs.Select(x => x.Finished.Task)); + } + public TimeProvider Clock => _cache.Clock; + public event Action? Invalidated; + private void OnInvalidated(string mappingId, long generation) { _cursors.InvalidateMapping(mappingId); Invalidated?.Invoke(mappingId, generation); } + /// Installs only an already validated local mapping snapshot. + public void ApplyMappings(IReadOnlyList bindings) + { + ArgumentNullException.ThrowIfNull(bindings); + if (bindings.Count > _maxMappings) throw new InvalidOperationException("Mapping capacity exceeded."); + var next = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var binding in bindings) + { + ArgumentNullException.ThrowIfNull(binding); + var mapping = binding.Mapping; + if (!mapping.Enabled || mapping.Revision <= 0 || string.IsNullOrWhiteSpace(mapping.RemoteNamespaceMappingId) || + string.IsNullOrWhiteSpace(mapping.DataConnectionId) || mapping.Realm != mapping.RemoteRealm || mapping.Realm == DataRealm.Unspecified || + mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 || mapping.StaleTimeoutMilliseconds <= 0 || + binding.LocalAnchor.MappingId != mapping.RemoteNamespaceMappingId || binding.LocalAnchor.MappingRevision != mapping.Revision || + binding.LocalAnchor.Realm != mapping.Realm || binding.LocalAuthority is not { IsActive: true } || binding.LocalNameOccupied is null) + throw new ArgumentException("Invalid projection binding.", nameof(bindings)); + var copy = System.Text.Json.JsonSerializer.Deserialize(System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(mapping))!; + var frozen = binding with { Mapping = copy, LocalScope = binding.LocalScope with { Segments = Array.AsReadOnly(binding.LocalScope.Segments.ToArray()) }, + LocalAncestry = Array.AsReadOnly(binding.LocalAncestry.ToArray()) }; + if (!next.TryAdd(copy.RemoteNamespaceMappingId, frozen)) throw new ArgumentException("Duplicate mapping identity.", nameof(bindings)); + } + ProjectedMappingBinding[] oldBindings; + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + oldBindings = _mappings.Values.ToArray(); _mappings = next; + } + foreach (var old in oldBindings) + { + _cache.MarkUnavailable(old.Mapping.RemoteNamespaceMappingId, old.LocalAnchor); + if (!next.ContainsKey(old.Mapping.RemoteNamespaceMappingId)) _cache.ForgetMapping(old.Mapping.RemoteNamespaceMappingId); + } + foreach (var item in next.Values) _cache.CaptureGeneration(item.Mapping.RemoteNamespaceMappingId); + } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => _cache.TryGetParent(request); + public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => _cache.CaptureParentGuard(request, expected); + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) => _cache.TryResolveProjected(realm, localId, out proof); + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) => _cache.TryPinProjected(realm, localId, out pin); + public async Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate(); + // Continuations remain exclusive reservations; initial requests can share one physical fetch. + if (request.Continuation is not null) return await PrepareCoreAsync(request, cancellationToken).ConfigureAwait(false); + var elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp()); + var remaining = request.Budget.Timeout - elapsed; + if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + SharedFetch work; FetchKey key; + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!_mappings.TryGetValue(request.MappingId, out var binding) || _waiterCount >= _maximumWaiters) + return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + key = new FetchKey(request with { RequestStartedTimestamp = 0 }, binding); + if (!_fetches.TryGetValue(key, out work!)) + { + if (_physicalJobs.Count >= _maximumWaiters) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + work = new SharedFetch(new CancellationTokenSource()); + _fetches.Add(key, work); _physicalJobs.Add(work); + var current = work; + current.Task = Task.Run(async () => + { + if (_beforeFetch is not null) await _beforeFetch(current.Stop.Token).ConfigureAwait(false); + return await PrepareCoreAsync(request, current.Stop.Token).ConfigureAwait(false); + }); + } + work.Waiters++; _waiterCount++; + } + try + { + using var timeout = new CancellationTokenSource(remaining, Clock); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); + var prepared = await work.Task.WaitAsync(linked.Token).ConfigureAwait(false); + return prepared.CloneForWaiter(request); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { return PreparedPage.Failed(ProjectionPageStatus.Unavailable); } + finally + { + lock (_sync) + { + _waiterCount--; work.Waiters--; + if (work.Waiters == 0) + { + if (_fetches.TryGetValue(key, out var active) && ReferenceEquals(active, work)) _fetches.Remove(key); + if (!work.Task.IsCompleted) _ = work.Stop.CancelAsync(); + _ = FinishSharedFetchAsync(work); + } + } + } + } + private async Task FinishSharedFetchAsync(SharedFetch work) + { + try { var page = await work.Task.ConfigureAwait(false); await page.DisposeAndWaitAsync().ConfigureAwait(false); } + catch (Exception) { } + finally + { + work.Stop.Dispose(); + lock (_sync) _physicalJobs.Remove(work); + work.Finished.TrySetResult(); + } + } + private async Task PrepareCoreAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); request.Budget.Validate(); request.Parent.Validate(); + ProjectedMappingBinding binding; + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (!_mappings.TryGetValue(request.MappingId, out binding!)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + } + if ((request.ConfiguredCapability is { } capability + ? !capability.Matches(request.MappingId, request.Parent, binding.LocalAuthority) + : request.Caller is null || !_policy.IsCallerUsable(request.Caller) || !_policy.AuthorizeLocal(request.Caller, OpcUaOperation.Browse, binding.LocalScope)) || + !binding.LocalAuthority.IsActive || request.Parent.MappingId != binding.Mapping.RemoteNamespaceMappingId || + request.Parent.MappingRevision != binding.Mapping.Revision || request.Parent.Realm != binding.Mapping.Realm) + return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp()); + var remaining = request.Budget.Timeout - elapsed; + if (elapsed < TimeSpan.Zero || remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + if (!await _fetchSlots.WaitAsync(0, cancellationToken).ConfigureAwait(false)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + IGrpcDataAdapterConnectionLease? connection = null; PreparedBrowseContinuation? cursor = null; var transferred = false; + try + { + using var timeout = new CancellationTokenSource(remaining, Clock); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token); + connection = await _source.AcquireAsync(binding.Mapping.DataConnectionId, linked.Token).ConfigureAwait(false); + if (connection is null) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + if (!ReferenceEquals(connection.Connection.Clock, Clock) || !string.Equals(connection.Connection.Target.ExpectedClusterId, + request.Parent.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + using var route = CancellationTokenSource.CreateLinkedTokenSource(linked.Token, connection.CancellationToken); + var generation = _cache.CaptureGeneration(request.MappingId); + DataMetadata originParent; + ProjectedNodeProof? previousParent = null; + if (request.Parent == binding.LocalAnchor) + { + var originView = new DataView(request.Parent.Address, request.Parent.Realm, null, 0, binding.Mapping.RemoteRootEntityId); + var metadata = await connection.Connection.GetMetadataAsync(new([originView], request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); + if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null) + return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + originParent = root; + } + else + { + var localId = ProjectedDataIds.Identifier(request.MappingId, request.Parent.Address); + if (!_cache.TryResolveProjected(request.Parent.Realm, localId, out previousParent) || previousParent!.Metadata.View != request.Parent) + return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + originParent = previousParent.OriginMetadata; + } + var serving = originParent.Serving!; + var target = connection.Connection.Target; + if (serving.ServingGeneration <= 0 || !(string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) || + target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase))) + return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var continuationBinding = new BrowseContinuationBinding(request.ConfiguredCapability?.Nonce ?? request.Caller.Principal, + request.ConfiguredCapability is null ? request.Caller.ApiKeyId ?? "" : "configured", + request.ConfiguredCapability is null ? request.Caller.CredentialVersion ?? "" : "configured", + binding.Mapping.RemoteNamespaceMappingId, binding.Mapping.Revision, request.Parent, request.Filter, binding.LocalAuthority.CatalogEpoch, + serving, request.ConfiguredCapability is null ? request.Caller.CredentialExpiresUtc : null); + if (request.Continuation is not null && !_cursors.TryPrepare(request.Continuation, continuationBinding, out cursor)) + return PreparedPage.Failed(ProjectionPageStatus.InvalidContinuation); + elapsed = Clock.GetElapsedTime(request.RequestStartedTimestamp, Clock.GetTimestamp()); remaining = request.Budget.Timeout - elapsed; + if (remaining <= TimeSpan.Zero) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var branch = await connection.Connection.BrowseAsync(new BrowseRequest(originParent.View, request.Filter, cursor?.RemoteCursor, + request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); + if (branch.Status != DataItemStatus.Good || branch.Parent != originParent.View || branch.Serving is null || branch.Serving != serving || branch.Lease is null || + branch.Lease.CatalogEpoch != serving.CatalogEpoch || branch.Lease.AuthorityEpoch != serving.AuthorityEpoch || + branch.Items.Count > Math.Min(request.Budget.MaxItems, binding.Mapping.MaxProjectionNodes) || + branch.Complete != (branch.Continuation is null) || connection.CancellationToken.IsCancellationRequested) + return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var maxLease = TimeSpan.FromMilliseconds(binding.Mapping.MetadataLeaseMilliseconds); + var lease = new BoundProjectionLease(new MetadataAuthorityLease(serving, branch.Lease, request.RequestStartedTimestamp, maxLease, TimeSpan.Zero, Clock), + connection.CancellationToken, binding.LocalAuthority, _cache, request.MappingId, generation, () => IsCurrent(binding)); + if (!lease.IsValid) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var parentScope = previousParent?.Subject.Scope ?? binding.LocalScope; + var ancestry = previousParent?.Subject.LocalAncestry ?? binding.LocalAncestry; + var mappedParent = originParent with { View = request.Parent, Serving = serving }; + var parentSubject = new MappedNamespaceSubject(request.Parent, parentScope, ancestry, serving, + binding.Mapping.AllowedOperations & originParent.AllowedOperations, binding.Mapping.WriteThrough && originParent.Writable); + var parentResolver = new MappedSubjectResolver([parentSubject], serving.CatalogEpoch, binding.LocalAuthority); + var parentProof = new ProjectedNodeProof(ProjectedDataIds.Identifier(request.MappingId, originParent.View.Address), mappedParent, parentSubject, parentResolver, lease, generation, originParent, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds)); + var results = new List(); var seenNames = new HashSet(StringComparer.Ordinal); + foreach (var item in branch.Items) + { + item.Validate(); + if (item.Serving != serving || item.View.MappingId is not null || item.View.Realm != request.Parent.Realm || + item.CatalogRevision != serving.CatalogEpoch || !string.Equals(item.View.Address.OriginClusterId, originParent.View.Address.OriginClusterId, StringComparison.OrdinalIgnoreCase) || + string.IsNullOrWhiteSpace(item.BrowseName) || item.BrowseName.Contains('/') || !seenNames.Add(item.BrowseName) || + binding.LocalNameOccupied(request.Parent, item.BrowseName)) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var segments = parentScope.Segments.Concat([item.BrowseName]).ToArray(); + if (segments.Length - binding.LocalScope.Segments.Count > binding.Mapping.MaxProjectionDepth) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); + var localView = item.View with { MappingId = binding.Mapping.RemoteNamespaceMappingId, MappingRevision = binding.Mapping.Revision, Subject = string.Join('/', segments) }; + var scope = parentScope with { Segments = Array.AsReadOnly(segments) }; + var subject = new MappedNamespaceSubject(localView, scope, ancestry, serving, binding.Mapping.AllowedOperations & item.AllowedOperations, binding.Mapping.WriteThrough && item.Writable); + var resolver = new MappedSubjectResolver([subject], serving.CatalogEpoch, binding.LocalAuthority); + results.Add(new ProjectedNodeProof(ProjectedDataIds.Identifier(request.MappingId, item.View.Address), item with { View = localView }, subject, resolver, lease, generation, item, TimeSpan.FromMilliseconds(binding.Mapping.StaleTimeoutMilliseconds))); + } + var snapshot = new ProjectedParentSnapshot(ProjectionPageStatus.Ready, Array.AsReadOnly(results.ToArray()), branch.Complete, null, generation, lease, binding.LocalAuthority, parentProof); + var prepared = new PreparedPage(_cache, _cursors, request, snapshot, continuationBinding, cursor, branch.Continuation, connection, _fetchSlots, Clock, branch.Lease.Duration < maxLease ? branch.Lease.Duration : maxLease, binding.Mapping.MaxProjectionNodes); + cursor = null; connection = null; transferred = true; return prepared; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch (Exception) { return PreparedPage.Failed(ProjectionPageStatus.Unavailable); } + finally + { + cursor?.Dispose(); + if (!transferred) + { + try { if (connection is not null) await connection.DisposeAsync().ConfigureAwait(false); } + finally { _fetchSlots.Release(); } + } + } + } + private bool IsCurrent(ProjectedMappingBinding binding) + { + lock (_sync) return !_disposed && _mappings.TryGetValue(binding.Mapping.RemoteNamespaceMappingId, out var current) && ReferenceEquals(current, binding); + } + public void Dispose() + { + ProjectedMappingBinding[] old; + lock (_sync) + { + if (_disposed) return; _disposed = true; old = _mappings.Values.ToArray(); _mappings.Clear(); + foreach (var work in _fetches.Values) _ = work.Stop.CancelAsync(); + } + foreach (var item in old) _cache.MarkUnavailable(item.Mapping.RemoteNamespaceMappingId, item.LocalAnchor); + _cache.Invalidated -= OnInvalidated; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index da03321d2..6bb9dc71b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -28,6 +28,7 @@ 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.OpcUa; using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; using ZB.MOM.WW.OtOpcUa.Runtime.Telemetry; @@ -663,6 +664,35 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// Failure detail when is false; null on success. public sealed record NodeWriteResult(bool Success, string? Reason); internal sealed record RouteRichWrite(WriteAdmissionTicket Ticket, WriteClaim Claim); + internal sealed record DrainProjectedValues(ActorProjectedValuePublisher Publisher); + internal sealed record DrainProjectedRetirements(ActorProjectedValuePublisher Publisher); + private readonly Dictionary _projectedRoutes = new(StringComparer.Ordinal); + private readonly ActorProjectedValuePublisher? _projectedPublisher; + + private void ForwardProjected(DrainProjectedValues message) + { + foreach (var batch in message.Publisher.TakeQueuedValues(Self)) + { + if (!batch.IsValid || _opcUaPublishActor is null) { batch.AbortQueued(); continue; } + foreach (var route in batch.Routes) + { + var key = route.DependencyReference; + if (_projectedRoutes.TryGetValue(key, out var old) && old != route) + _dependencyMux?.Tell(new DependencyMuxActor.ProjectedReferenceRetired(old.PublicationId.ToString("N"), old.DependencyReference)); + _projectedRoutes[key] = route; + } + message.Publisher.EnqueueForSdk(batch, _opcUaPublishActor, _dependencyMux); + } + } + private void RetireProjected(DrainProjectedRetirements message) + { + foreach (var key in message.Publisher.TakeRetiredReferences(Self)) + { + if (!_projectedRoutes.TryGetValue(key, out var current) || message.Publisher.IsCurrent(current)) continue; + _projectedRoutes.Remove(key); + _dependencyMux?.Tell(new DependencyMuxActor.ProjectedReferenceRetired(current.PublicationId.ToString("N"), current.DependencyReference)); + } + } /// /// Routes an inbound native-condition acknowledge to the owning driver child. The host wires the @@ -843,7 +873,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, DataWriteRuntime? dataWriteRuntime = null, SubscriptionAcquisitionCapacity? acquisitionCapacity = null, - DataConnectionDeploymentRuntime? dataConnections = null) => + DataConnectionDeploymentRuntime? dataConnections = null, + ActorProjectedValuePublisher? projectedPublisher = 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 @@ -858,7 +889,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, dataWriteRuntime, acquisitionCapacity, dataConnections)); + enforceSnapshotOrdering, sourcePublisher, catalogCoordinator, dataWriteRuntime, acquisitionCapacity, dataConnections, projectedPublisher)); /// Initializes a new DriverHostActor with the specified dependencies. /// Database context factory for configuration database access. @@ -999,8 +1030,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null, DataWriteRuntime? dataWriteRuntime = null, SubscriptionAcquisitionCapacity? acquisitionCapacity = null, - DataConnectionDeploymentRuntime? dataConnections = null) + DataConnectionDeploymentRuntime? dataConnections = null, + ActorProjectedValuePublisher? projectedPublisher = null) { + _projectedPublisher = projectedPublisher; _dataWriteRuntime = dataWriteRuntime; _dataConnections = dataConnections; _acquisitionCapacity = acquisitionCapacity; @@ -1059,6 +1092,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS /// protected override void PreStart() { + _projectedPublisher?.HostActivated(Self); // Resolve the cluster DPS mediator once, on the actor thread, and reuse it for every subscribe + // the Primary-gated native-alarm alerts fan-out in ForwardNativeAlarm (mirrors ScriptedAlarmHostActor). _mediator = DistributedPubSub.Get(Context.System).Mediator; @@ -1728,6 +1762,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS Receive(HandleApplyWedged); Receive(HandleGetDiagnostics); Receive(ForwardBatchToMux); + Receive(ForwardProjected); + Receive(RetireProjected); Receive(OnRetiredChildTerminated); Receive(_ => HandleScriptedAlarmHostRestarted()); Receive(ForwardNativeAlarm); @@ -1806,6 +1842,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS Receive(HandleApplyWedged); Receive(HandleGetDiagnostics); Receive(ForwardBatchToMux); + Receive(ForwardProjected); + Receive(RetireProjected); Receive(OnRetiredChildTerminated); Receive(_ => HandleScriptedAlarmHostRestarted()); Receive(ForwardNativeAlarm); @@ -2901,6 +2939,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS // spawned, so none should arrive — but the orphan-replay BeginDirectApply in that same try block has // already started a pipe-back before the catch can run, so "cannot happen" rests on ordering. Explicit // drops, so a burst that does land is a logged drop rather than an Unhandled dead-letter. + Receive(m => { foreach (var batch in m.Publisher.TakeQueuedValues(Self)) batch.AbortQueued(); }); + Receive(RetireProjected); Receive(m => _log.Debug("DriverHost {Node}: dropping a {Count}-item value burst from {Id} while Stale (no address space)", _localNode, m.Items.Count, m.DriverInstanceId)); @@ -3637,7 +3677,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS _dataConnections.Apply(new(parsed.ParseDataConnectionScopeVersion(), _catalogAttempt.Revision, parsed.ParseDataConnections(_localNode.Value), mode)); } - if (snapshot is not null) _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value); + if (snapshot is not null && _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value)) + _catalogCoordinator.ProjectedMappings?.Stage(_catalogAttempt, + parsed.ParseRemoteNamespaceMappings(_localNode.Value), parsed.ParseDataConnections(_localNode.Value)); } catch (Exception ex) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs index 10641dc81..4b5632df9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Historian/ContinuousHistorizationRecorder.cs @@ -365,6 +365,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers ReceiveAsync(OnValueChangedAsync); ReceiveAsync(OnValueBatchAsync); + ReceiveAsync(wake => wake.ConsumeAsync(IngestAsync)); Receive(OnUpdateHistorizedRefs); Receive(_ => OnDrainTick()); Receive(OnDrainResult); @@ -470,11 +471,19 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers // production recorder died (Gitea #491): the throw reached supervision, the restart discarded the EMPTY-seeded ref // set, and historization stopped after the first value. The append loop holds its own captured Self. List? entries = null; + List? admissionProofs = null; for (int i = 0; i < items.Count; i++) { try { + var before = entries?.Count ?? 0; CollectEntries(items[i], ref entries); + var added = (entries?.Count ?? 0) - before; + if (added > 0) + { + admissionProofs ??= Enumerable.Repeat(null, before).ToList(); + for (var n = 0; n < added; n++) admissionProofs.Add(items[i].PublicationProof); + } } catch (Exception ex) { @@ -524,18 +533,45 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers // The gauges' source: the queue depth and the mailbox depth as this burst is accepted (the actor thread is the // only place the mailbox can be read). ContinuousHistorizationMetrics.ReportRecorder(pending, Context is ActorCell cell ? cell.NumberOfMessages : -1); - if (!_appendQueue.Writer.TryWrite(entries)) + if (admissionProofs is not null && admissionProofs.Any(x => x is not null)) { - Interlocked.Increment(ref _appendBackpressureWaits); + // For projected input, the last proof check immediately before a successful bounded + // queue write is the accepted-history boundary. A full queue never extends authority. try { - await _appendQueue.Writer.WriteAsync(entries, _lifetime.Token).ConfigureAwait(false); + while (true) + { + var admitted = new List(entries.Count); + for (var i = 0; i < entries.Count; i++) + { + var proof = admissionProofs[i]; + var valid = proof is null; + if (proof is not null) try { valid = proof.IsValid; } catch (Exception) { valid = false; } + if (valid) admitted.Add(entries[i]); + } + if (admitted.Count == 0) + { + ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); + break; + } + if (_appendQueue.Writer.TryWrite(admitted)) break; + Interlocked.Increment(ref _appendBackpressureWaits); + if (!await _appendQueue.Writer.WaitToWriteAsync(_lifetime.Token).ConfigureAwait(false)) + { + ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); + break; + } + } } catch (Exception ex) when (ex is OperationCanceledException or ChannelClosedException) - { - // Normal shutdown raced the enqueue — not a fault. - ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); - } + { ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); } + } + else if (!_appendQueue.Writer.TryWrite(entries)) + { + Interlocked.Increment(ref _appendBackpressureWaits); + try { await _appendQueue.Writer.WriteAsync(entries, _lifetime.Token).ConfigureAwait(false); } + catch (Exception ex) when (ex is OperationCanceledException or ChannelClosedException) + { ContinuousHistorizationMetrics.ReportPendingAppends(Interlocked.Decrement(ref _pendingAppends)); } } } @@ -625,6 +661,7 @@ public sealed class ContinuousHistorizationRecorder : ReceiveActor, IWithTimers // mux ref under a HistorianTagname override, and there can be MORE THAN ONE when several historized // equipment tags alias the same driver ref. (The mux already scopes to our registered refs; this is // also the defensive filter.) + if (msg.PublicationProof is { IsValid: false }) return; if (!_refMap.TryGetValue(msg.TagId, out HashSet? historianNames) || historianNames.Count == 0) { return; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs index 65b5ecba3..418fdb752 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -556,6 +556,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers Receive(HandleAttributeUpdate); Receive(HandleAttributeBatchUpdate); + Receive(HandleProjectedValues); + Receive(message => + { foreach (var batch in message.Publisher.TakeSdkValues(Self)) HandleProjectedValues(new(batch, message.DependencyMux)); }); Receive(HandleAttributeStatusBatchUpdate); Receive(HandleAlarmUpdate); Receive(HandleAlarmQualityUpdate); @@ -658,6 +661,24 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers } } + internal sealed record ProjectedValues(DataConnections.ProjectedPublicationBatch Batch, IActorRef? DependencyMux); + internal sealed record DrainProjectedValues(DataConnections.ActorProjectedValuePublisher Publisher, IActorRef? DependencyMux); + + private void HandleProjectedValues(ProjectedValues message) + { + var batch = message.Batch; + if (!batch.TryBegin()) return; + var accepted = false; + try + { + if (!batch.IsValid || _sink is not Core.Abstractions.DataConnections.IProjectedValueSink projected + || !projected.TryPublish(batch.Writes) || !batch.IsValid) return; + if (message.DependencyMux is not null && !batch.ForwardToMux(message.DependencyMux)) return; + accepted = true; + } + finally { batch.Complete(accepted); } + } + private void HandleAttributeUpdate(AttributeValueUpdate msg) { try @@ -801,7 +822,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers { if (!string.Equals(_catalogCoordinator.Serving.NodeId, _localNode.Value.Value, StringComparison.Ordinal)) return; var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value.Value); - if (snapshot is not null) _catalogCoordinator.Stage(msg.CatalogAttempt, snapshot, _localNode.Value.Value); + if (snapshot is not null && _catalogCoordinator.Stage(msg.CatalogAttempt, snapshot, _localNode.Value.Value)) + _catalogCoordinator.ProjectedMappings?.Stage(msg.CatalogAttempt, + parsed.ParseRemoteNamespaceMappings(_localNode.Value.Value), parsed.ParseDataConnections(_localNode.Value.Value)); } catch (Exception ex) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/DependencyMuxTagUpstreamSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/DependencyMuxTagUpstreamSource.cs index 5466ab493..a16ae13cd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/DependencyMuxTagUpstreamSource.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/DependencyMuxTagUpstreamSource.cs @@ -25,7 +25,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms; /// snapshot — a concurrent unsubscribe can never corrupt an in-flight fan-out. /// /// -public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource +public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource, IAlarmInputEvidenceSource { // The status an "unknown path" snapshot carries — a path nothing has ever pushed to. // @@ -46,6 +46,51 @@ public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource // ONLY through RetainOnly — the host calls it with the loaded dependency-ref union after every // (re)load, so a renamed/removed raw path (a RawTree rename is a surgical remove+add) stops // costing a boxed value + two DateTimes for the process lifetime (R02:L3). + private readonly System.Runtime.CompilerServices.ConditionalWeakTable _evidence = new(); + private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota _physicalQuota; + private sealed class ProjectedEvidence(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof proof, + DataValueSnapshot snapshot, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota quota) : IAlarmInputPhysicalEvidence + { + private readonly WeakReference _identity = new(snapshot); + public bool IsValid { get { try { return proof.IsValid; } catch (Exception) { return false; } } } + public bool TryRetainPhysical(DataValueSnapshot exactSnapshot, out IDisposable? lease) + { + lease = null; + if (!_identity.TryGetTarget(out var original) || !ReferenceEquals(original, exactSnapshot) || !IsValid) return false; + long charge; + try { charge = checked(512L + ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.Estimate(exactSnapshot.Value)); } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + if (!quota.TryAdjust(charge)) return false; + if (!ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedInputBudget.TryRetain([exactSnapshot], out var processLease) || processLease is null) + { quota.TryAdjust(-charge); return false; } + if (!IsValid) { processLease.Dispose(); quota.TryAdjust(-charge); return false; } + lease = new PhysicalLease(quota, charge, exactSnapshot, processLease); return true; + } + private sealed class PhysicalLease(ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota quota, long charge, + DataValueSnapshot snapshot, IDisposable processLease) : IDisposable + { + private DataValueSnapshot? _snapshot = snapshot; + public void Dispose() + { + if (Interlocked.Exchange(ref _snapshot, null) is null) return; + processLease.Dispose(); + quota.TryAdjust(-charge); + } + } + } + public IAlarmInputEvidence? CaptureEvidence(DataValueSnapshot exactSnapshot) + { + ArgumentNullException.ThrowIfNull(exactSnapshot); + return _evidence.TryGetValue(exactSnapshot, out var evidence) ? evidence : null; + } + /// Copies a projected input and binds evidence to that exact immutable snapshot. + public void Push(string path, DataValueSnapshot snapshot, ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof proof) + { + ArgumentNullException.ThrowIfNull(snapshot); ArgumentNullException.ThrowIfNull(proof); + var owned = snapshot with { }; + _evidence.Add(owned, new ProjectedEvidence(proof, owned, _physicalQuota)); + Push(path, owned); + } private readonly ConcurrentDictionary _cache = new(StringComparer.Ordinal); private readonly ConcurrentDictionary>> _observers @@ -60,8 +105,12 @@ public sealed class DependencyMuxTagUpstreamSource : ITagUpstreamSource /// snapshot returned for an unknown path. Defaults to , /// mirroring how takes its clock. /// - public DependencyMuxTagUpstreamSource(Func? clock = null) - => _clock = clock ?? (() => DateTime.UtcNow); + public DependencyMuxTagUpstreamSource(Func? clock = null, long maximumProjectedBytes = 16 * 1024 * 1024) + { + if (maximumProjectedBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumProjectedBytes)); + _clock = clock ?? (() => DateTime.UtcNow); + _physicalQuota = new(maximumProjectedBytes); + } /// /// Update the cached snapshot for and then notify every diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs index 60f057294..d7e6aa0c0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs @@ -314,6 +314,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor // burst. The engine upstream is fed per value, so push each item in order — the saving is the // mailbox hop, not the push. Receive(OnDependencyBatch); + Receive(wake => wake.Consume(items => OnDependencyBatch(new(items)))); Receive(OnEngineEmission); // Cluster redundancy snapshots (published on the `redundancy-state` topic, subscribed in PreStart) // cache this node's role so OnEngineEmission can gate the cluster-wide alerts publish to the Primary. @@ -512,8 +513,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor // the status code rides through verbatim. This used to convert the incoming value onto a // 3-state enum and straight back again through a pair of mutually-inverse mappers, which is where // the input's sub-code was lost before the engine ever cached it. - _upstream.Push(msg.TagId, - new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc)); + var snapshot = new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc); + if (msg.PublicationProof is { } proof) _upstream.Push(msg.TagId, snapshot, proof); + else _upstream.Push(msg.TagId, snapshot); } /// One batched mux delivery — every item already matched this host's registered interest. @@ -544,6 +546,11 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor private void OnEngineEmission(EngineEmission msg) { var e = msg.Event; + if (e.InputEvidence is { } evidence) + { + try { if (!evidence.IsValid) return; } + catch (Exception) { return; } + } // None = no meaningful change; Suppressed = shelving ate the emission. Neither should reach a // sink. (The engine already filters these out of BuildEmission, but guard defensively.) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs index ed008a444..179471ad2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ServiceCollectionExtensions.cs @@ -448,7 +448,8 @@ public static class ServiceCollectionExtensions // Dependency mux must be spawned before DriverHostActor so the host can forward // AttributeValueBatchPublished into it from the very first driver spawn. - var mux = system.ActorOf(DependencyMuxActor.Props(), DependencyMuxActorName); + var mux = system.ActorOf(DependencyMuxActor.Props(interestSink: + resolver.GetService()), DependencyMuxActorName); registry.Register(mux); // Per-cluster mesh Phase 2: the node end of the central↔node command boundary. Spawned @@ -566,6 +567,8 @@ public static class ServiceCollectionExtensions // consumers then behave as if the endpoint were listening (the pre-#762 behaviour). var endpointState = resolver.GetService(); var redundancy = resolver.GetService() ?? WarmRedundancySettings.Unset; + // Attach mapped deployment ownership before either actor can begin catalog activation. + _ = resolver.GetService(); // The same production factory selects authority, catalog and Warm publications in tests. var publishActor = system.ActorOf( DataConnectionPublisherProps.Create(resolver, addressSpaceSink, serviceLevel, @@ -671,7 +674,8 @@ public static class ServiceCollectionExtensions dataWriteRuntime: resolver.GetService(), acquisitionCapacity: resolver.GetService(), writeClock: resolver.GetService(), - dataConnections: resolver.GetService()), + dataConnections: resolver.GetService(), + projectedPublisher: resolver.GetService()), DriverHostActorName); registry.Register(driverHost); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyConsumerMuxAdapter.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyConsumerMuxAdapter.cs index b8dc818f8..e708466ac 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyConsumerMuxAdapter.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyConsumerMuxAdapter.cs @@ -1,6 +1,7 @@ using Akka.Actor; using Akka.Event; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; @@ -17,8 +18,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; /// /// This is the exact seam a VirtualTagActor uses to receive its inputs, generalised so a /// host-blind driver (the Calculation pseudo-driver) can read other tags' live values with -/// no cross-driver plumbing. The mux fans out value + timestamp only (quality is stripped at the -/// mux boundary, same as for virtual tags), so the forwarded status code is Good (0). +/// no cross-driver plumbing. The mux preserves value, original timestamp and status; projected +/// samples additionally carry live publication proof checked immediately before the callback. /// /// public sealed class DependencyConsumerMuxAdapter : ReceiveActor @@ -48,6 +49,7 @@ public sealed class DependencyConsumerMuxAdapter : ReceiveActor Receive(OnDependencyValueChanged); Receive(OnDependencyValueBatch); + Receive(wake => wake.Consume(items => OnDependencyValueBatch(new(items)))); Receive(_ => RegisterInterest()); } @@ -84,6 +86,17 @@ public sealed class DependencyConsumerMuxAdapter : ReceiveActor /// The dependency value, as the mux delivered it. private void OnDependencyValueChanged(VirtualTagActor.DependencyValueChanged msg) { + if (msg.PublicationProof is { } proof) + { + var valid = false; + try { valid = proof.IsValid; } catch (Exception) { } + if (_consumer is IProjectedDependencyConsumer projected) + projected.OnProjectedDependencyValue(msg.TagId, valid ? msg.Value : null, + valid ? msg.StatusCode : OpcUaStatus.BadNoCommunication, msg.TimestampUtc, proof); + else + _consumer.OnDependencyValue(msg.TagId, null, OpcUaStatus.BadNoCommunication, msg.TimestampUtc); + return; + } _consumer.OnDependencyValue(msg.TagId, msg.Value, msg.StatusCode, msg.TimestampUtc); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs index 9a6956eef..b47086f4b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/DependencyMuxActor.cs @@ -1,6 +1,7 @@ using Akka.Actor; using Akka.Event; using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; @@ -91,6 +92,20 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers /// never replayed. Subscriptions are untouched. /// The removed driver instance. public sealed record SourceRemoved(string DriverInstanceId); + internal sealed record ProjectedDependency(string SourceId, string Reference, ProjectedValueWrite Value); + internal sealed record ProjectedBatch(IReadOnlyList Items); + internal sealed record DrainProjectedBatch(ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox Mailbox); + internal sealed record ProjectedReferenceRetired(string SourceId, string Reference); + /// Payload-free projected delivery wake. Consume synchronously on the recipient actor. + public sealed class ProjectedDependencyWake + { + private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox _mailbox; + internal ProjectedDependencyWake(ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedCoalescingMailbox mailbox) => _mailbox = mailbox; + public void Consume(Action> accept) + { ArgumentNullException.ThrowIfNull(accept); using var batch = _mailbox.Take(); accept(batch.Items); } + public async Task ConsumeAsync(Func, Task> accept) + { ArgumentNullException.ThrowIfNull(accept); using var batch = _mailbox.Take(); await accept(batch.Items).ConfigureAwait(false); } + } /// One VirtualTag result, routed to the tags that read it (lmxopcua#791). Always retained (see the /// type remarks), so a dependent registering later is replayed the current value. @@ -129,6 +144,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers public VirtualTagActor.DependencyValueChanged? Last; public string? LastSource; + public long ProjectedCharge; /// A VirtualTag output (lmxopcua#791): retained unconditionally until /// , never put into grace. @@ -147,8 +163,13 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers private sealed record Registration(HashSet Refs, bool Replay); + private const long ProjectedBytesLimit = 16 * 1024 * 1024; + private const int ProjectedEntryLimit = 10000; + private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ProjectedByteQuota _projectedQuota = new(ProjectedBytesLimit); + private readonly Dictionary> _projectedSubscribers = new(); private readonly Dictionary _byRef = new(StringComparer.Ordinal); private readonly Dictionary _bySubscriber = new(); + private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink? _interestSink; private readonly ILoggingAdapter _log = Context.GetLogger(); /// How long a released ref's value is kept. @@ -167,34 +188,48 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers /// How long a ref's value outlives its last replay-opting subscriber; /// null ⇒ . /// The props for creating this actor. - public static Props Props(TimeSpan? retentionGrace = null) + public static Props Props(TimeSpan? retentionGrace = null, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink? interestSink = null) { var grace = retentionGrace ?? DefaultRetentionGrace; - return Akka.Actor.Props.Create(() => new DependencyMuxActor(grace)); + return Akka.Actor.Props.Create(() => new DependencyMuxActor(grace, interestSink)); } /// Initializes a new instance of the class. /// See ; non-positive ⇒ . - public DependencyMuxActor(TimeSpan retentionGrace) + public DependencyMuxActor(TimeSpan retentionGrace, ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.IProjectedDependencyInterestSink? interestSink = null) { RetentionGrace = retentionGrace > TimeSpan.Zero ? retentionGrace : DefaultRetentionGrace; + _interestSink = interestSink; Receive(OnRegister); Receive(msg => RemoveSubscriber(msg.Subscriber)); Receive(OnSourceRemoved); Receive(_ => OnSweep()); Receive(OnAttributeValueBatchPublished); + Receive(OnProjectedBatch); + Receive(message => { using var batch = message.Mailbox.Take(); OnProjectedBatch(new(batch.Items)); }); + Receive(OnProjectedReferenceRetired); Receive(OnVirtualTagOutput); Receive(OnVirtualTagOutputsRemoved); - Receive(msg => RemoveSubscriber(msg.ActorRef)); + Receive(msg => { RemoveSubscriber(msg.ActorRef); if (_projectedSubscribers.Remove(msg.ActorRef, out var mailbox)) mailbox.Dispose(); }); + } + + protected override void PostStop() + { + foreach (var pair in _byRef) if (pair.Value.Subscribers.Count > 0) NotifyInterest(pair.Key, false); + foreach (var mailbox in _projectedSubscribers.Values) mailbox.Dispose(); + _projectedSubscribers.Clear(); + base.PostStop(); } private void OnRegister(RegisterInterest msg) { // Replace any prior interest set so re-registers on actor restart don't leak old refs. Detaching first // may put a ref into grace; the re-attach below takes it straight back out. - Detach(msg.Subscriber); - var refs = new HashSet(msg.TagRefs, StringComparer.Ordinal); + var preserved = _bySubscriber.TryGetValue(msg.Subscriber, out var prior) + ? new HashSet(prior.Refs.Where(refs.Contains), StringComparer.Ordinal) : new HashSet(StringComparer.Ordinal); + Detach(msg.Subscriber, preserved); + _bySubscriber[msg.Subscriber] = new Registration(refs, msg.ReplayRetained); List? replay = null; foreach (var r in refs) @@ -204,12 +239,17 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers entry = new RefEntry(); _byRef[r] = entry; } + if (entry.Subscribers.Count == 0 && !preserved.Contains(r)) NotifyInterest(r, true); entry.Subscribers.Add(msg.Subscriber); if (!msg.ReplayRetained) continue; entry.Replayers++; entry.ReleasedAtUtc = null; if (entry.Last is { } retained) - (replay ??= []).Add(retained); + { + if (retained.PublicationProof is null) (replay ??= []).Add(retained); + else if (retained.PublicationProof.IsValid) OfferProjected(msg.Subscriber, [retained]); + else Forget(entry); + } } Context.Watch(msg.Subscriber); _log.Debug("DependencyMux: subscriber {Sub} registered for {Count} refs (replay {Replay})", @@ -224,16 +264,24 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers } } + private void NotifyInterest(string reference, bool active) + { + if (_interestSink is null || !ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ProjectedDataIds.TryParseDependencyReference(reference, out _, out _)) return; + try { _interestSink.SetInterest(reference, active); } + catch (Exception ex) { _log.Error(ex, "Projected dependency interest transition failed"); } + } + private void RemoveSubscriber(IActorRef subscriber) { if (!Detach(subscriber)) return; + if (_projectedSubscribers.TryGetValue(subscriber, out var projectedMailbox)) projectedMailbox.Clear(); Context.Unwatch(subscriber); _log.Debug("DependencyMux: subscriber {Sub} removed", subscriber); } /// Drop 's registration. A ref losing its last replay-opting /// subscriber goes into grace; a ref left with no state at all is removed. - private bool Detach(IActorRef subscriber) + private bool Detach(IActorRef subscriber, HashSet? preserved = null) { if (!_bySubscriber.Remove(subscriber, out var registration)) return false; var now = DateTime.UtcNow; @@ -242,6 +290,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers { if (!_byRef.TryGetValue(r, out var entry)) continue; entry.Subscribers.Remove(subscriber); + if (entry.Subscribers.Count == 0 && !(preserved?.Contains(r) ?? false)) NotifyInterest(r, false); if (registration.Replay && --entry.Replayers == 0 && entry.Last is not null && !entry.Pinned) { entry.ReleasedAtUtc = now; @@ -269,7 +318,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers stillInGrace = true; continue; } - entry.Forget(); + Forget(entry); if (entry.IsDead) (dead ??= []).Add(r); } if (dead is not null) @@ -285,7 +334,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers { if (entry.Last is null || !string.Equals(entry.LastSource, msg.DriverInstanceId, StringComparison.Ordinal)) continue; - entry.Forget(); + Forget(entry); evicted++; if (entry.IsDead) (dead ??= []).Add(r); } @@ -304,6 +353,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers var dep = new VirtualTagActor.DependencyValueChanged(msg.TagRef, msg.Value, msg.TimestampUtc, msg.StatusCode); entry.Pinned = true; entry.ReleasedAtUtc = null; + ReleaseProjected(entry); entry.Last = dep; entry.LastSource = VirtualTagSource; foreach (var sub in entry.Subscribers) @@ -316,11 +366,78 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers { if (!_byRef.TryGetValue(r, out var entry) || !entry.Pinned) continue; entry.Pinned = false; - entry.Forget(); + Forget(entry); if (entry.IsDead) _byRef.Remove(r); } } + private void ReleaseProjected(RefEntry entry) + { + if (entry.ProjectedCharge == 0) return; + _projectedQuota.TryAdjust(-entry.ProjectedCharge); entry.ProjectedCharge = 0; + } + private void Forget(RefEntry entry) { ReleaseProjected(entry); entry.Forget(); } + private bool TryRetainProjected(RefEntry entry, VirtualTagActor.DependencyValueChanged value, string source) + { + long charge; + try { charge = checked(512L + 2L * value.TagId.Length + ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.Estimate(value.Value)); } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + if (!_projectedQuota.TryAdjust(charge - entry.ProjectedCharge)) return false; + entry.ProjectedCharge = charge; entry.Last = value; entry.LastSource = source; return true; + } + private bool OfferProjected(IActorRef subscriber, IReadOnlyList values) + { + if (!_projectedSubscribers.TryGetValue(subscriber, out var mailbox)) + { + if (_projectedSubscribers.Count >= ProjectedEntryLimit) return false; + mailbox = new(subscriber, queue => new ProjectedDependencyWake(queue), ProjectedBytesLimit, ProjectedEntryLimit, _projectedQuota, retainDelivered: true); + _projectedSubscribers.Add(subscriber, mailbox); + } + try + { + var entries = values.Select(value => (value.TagId, value, + checked(512L + 2L * value.TagId.Length + ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.Estimate(value.Value)))).ToArray(); + return mailbox.TryOffer(entries); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; } + } + + private void OnProjectedReferenceRetired(ProjectedReferenceRetired message) + { + if (!_byRef.TryGetValue(message.Reference, out var entry) || entry.Last is not { } previous + || entry.LastSource != message.SourceId && previous.PublicationProof is not { IsValid: false }) return; + Forget(entry); + var bad = new VirtualTagActor.DependencyValueChanged(message.Reference, null, DateTime.MinValue, + ZB.MOM.WW.OtOpcUa.Commons.OpcUa.OpcUaStatus.BadNoCommunication, previous.PublicationProof); + foreach (var subscriber in entry.Subscribers) OfferProjected(subscriber, [bad]); + if (entry.IsDead) _byRef.Remove(message.Reference); + } + + private void OnProjectedBatch(ProjectedBatch message) + { + var perSubscriber = new Dictionary>(); + foreach (var item in message.Items) + { + var value = item.Value; + if (!value.Proof.IsValid || !_byRef.TryGetValue(item.Reference, out var entry)) continue; + var dependency = new VirtualTagActor.DependencyValueChanged(item.Reference, value.Snapshot.Value, + value.Snapshot.SourceTimestampUtc ?? value.Snapshot.ServerTimestampUtc ?? DateTime.MinValue, + value.Snapshot.StatusCode, value.Proof); + if (entry.Retains && !TryRetainProjected(entry, dependency, item.SourceId)) { value.Proof.Invalidate(); continue; } + foreach (var subscriber in entry.Subscribers) + { + if (!perSubscriber.TryGetValue(subscriber, out var list)) perSubscriber[subscriber] = list = []; + list.Add(dependency); + } + } + foreach (var pair in perSubscriber) + { + var current = pair.Value.Where(item => item.PublicationProof!.IsValid).ToArray(); + if (current.Length != 0 && !OfferProjected(pair.Key, current)) + foreach (var item in current) item.PublicationProof?.Invalidate(); + } + } + private void OnAttributeValueBatchPublished(DriverInstanceActor.AttributeValueBatchPublished msg) { // Nothing registered and nothing retained — skip the whole burst rather than probing an empty map per item. @@ -340,6 +457,7 @@ public sealed class DependencyMuxActor : ReceiveActor, IWithTimers var dep = new VirtualTagActor.DependencyValueChanged(item.FullReference, item.Value, item.TimestampUtc, item.StatusCode); if (entry.Retains) { + ReleaseProjected(entry); entry.Last = dep; entry.LastSource = msg.DriverInstanceId; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs index a5ced545a..6c520c5a7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagActor.cs @@ -79,7 +79,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash /// now holds evaluation while any declared input is Bad and inherits the worst input's status /// otherwise. The Calculation driver reads it through the same mux. public sealed record DependencyValueChanged( - string TagId, object? Value, DateTime TimestampUtc, uint StatusCode = OpcUaStatus.Good); + string TagId, object? Value, DateTime TimestampUtc, uint StatusCode = OpcUaStatus.Good, + Core.Abstractions.DataConnections.IProjectedSamplePublicationProof? PublicationProof = null); /// /// One subscriber's slice of one upstream burst: every item in this batch matched @@ -132,6 +133,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash // comms-lost input from a genuine Good null, and it is what the script reads through // ctx.GetTag(path).StatusCode. private readonly Dictionary _dependencies = new(StringComparer.Ordinal); + private readonly Dictionary _projectedDependencyProofs = new(StringComparer.Ordinal); private bool _hasLastValue; private object? _lastValue; @@ -231,6 +233,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash Receive(OnDependencyChanged); Receive(OnDependencyBatch); + Receive(wake => wake.Consume(items => OnDependencyBatch(new(items)))); Receive(_ => OnReassertValue()); Receive(_ => RetrySource()); Receive(_ => Evaluate(DateTime.UtcNow)); @@ -315,6 +318,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash private void OnReassertValue() { if (!_hasLastValue && !_hasPublished) return; + if (!ProjectedProofsValid()) + { OnInputsBad(OpcUaStatus.BadNoCommunication, DateTime.UtcNow); return; } // The status LAST PUBLISHED, not a guess (02/S14). A VT whose input is comms-lost re-asserts // BadNoCommunication onto the freshly-materialised node; re-asserting Good here would put the // stale-Good lie back at every deploy. @@ -324,6 +329,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash private void OnDependencyChanged(DependencyValueChanged msg) { + SetDependencyProof(msg); _dependencies[msg.TagId] = new DataValueSnapshot(msg.Value, msg.StatusCode, msg.TimestampUtc, msg.TimestampUtc); if (_changeTriggered) Evaluate(msg.TimestampUtc); } @@ -348,6 +354,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash for (var i = 0; i < count; i++) { var item = items[i]; + SetDependencyProof(item); _dependencies[item.TagId] = new DataValueSnapshot(item.Value, item.StatusCode, item.TimestampUtc, item.TimestampUtc); } @@ -361,6 +368,8 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash /// The triggering dependency change's timestamp, stamped on the result. private void Evaluate(DateTime timestampUtc) { + if (!ProjectedProofsValid()) + { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; } // Worst-of-input FIRST (02/S14), before the evaluator is even considered. // // Over the deps that have ARRIVED, deliberately — a never-pushed dep is cold start, not a fault, @@ -380,7 +389,21 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash Task evaluation; try { - evaluation = _evaluator.EvaluateAsync(_virtualTagId, _expression, _dependencies); + if (_projectedDependencyProofs.Count == 0) + evaluation = _evaluator.EvaluateAsync(_virtualTagId, _expression, _dependencies); + else + { + if (_evaluator is not IProjectedVirtualTagEvaluator projected || + !Core.Abstractions.DataConnections.ProjectedInputBudget.TryRetain( + _projectedDependencyProofs.Keys.Select(key => _dependencies[key]), out var lease) || lease is null) + { + OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); + return; + } + var captured = new Dictionary(_dependencies, StringComparer.Ordinal); + try { evaluation = projected.EvaluateProjectedAsync(_virtualTagId, _expression, captured, lease); } + catch { lease.Dispose(); throw; } + } } catch (Exception ex) { @@ -464,8 +487,26 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash /// The completed evaluation task. /// The worst input status at the trigger. /// The trigger's timestamp. + private bool ProjectedProofsValid() + { + foreach (var proof in _projectedDependencyProofs.Values) + { + try { if (!proof.IsValid) return false; } + catch (Exception) { return false; } + } + return true; + } + + private void SetDependencyProof(DependencyValueChanged item) + { + if (item.PublicationProof is { } proof) _projectedDependencyProofs[item.TagId] = proof; + else _projectedDependencyProofs.Remove(item.TagId); + } + private void ApplyEvaluation(Task evaluation, uint worst, DateTime timestampUtc) { + if (!ProjectedProofsValid()) + { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; } if (!evaluation.IsCompletedSuccessfully) { var ex = evaluation.Exception?.GetBaseException() @@ -494,7 +535,9 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash // A completed evaluation is a fresh acquisition even when the legacy SDK value is unchanged. // Publish before the SDK dedup so a quiet equal value can recover an invalidated cache. + if (!ProjectedProofsValid()) { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; } PublishSource(result.Value, worst, timestampUtc); + if (!ProjectedProofsValid()) { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; } // Dedup on (value, STATUS) — 02/S14 generalising 02/S13's recover-from-Bad bypass. Keying on // value alone swallows every recovery whose value is unchanged, which is what a device coming @@ -513,6 +556,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash _lastPublishedStatus = worst; OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair("outcome", "ok")); var evalResult = new EvaluationResult(_virtualTagId, result.Value, timestampUtc, CorrelationId.NewId(), worst, SourceHandled: _sourcePublisher is not null); + if (!ProjectedProofsValid()) { OnInputsBad(OpcUaStatus.BadNoCommunication, timestampUtc); return; } Context.Parent.Tell(evalResult); } @@ -600,6 +644,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash { if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation || !_sourcePublisher.TryCaptureVirtual(_virtualTagId, incarnation, out var ticket)) return; + if (!ProjectedProofsValid()) return; _sourcePublisher.TryPublish(ticket, new DataValueSnapshot(value, status, timestamp, timestamp)); } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs index 1ccd8b7d5..514422142 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataCodecTests.cs @@ -248,6 +248,9 @@ public sealed class GrpcDataCodecTests ) .ShouldBe(hash); DataProtoMapper.WritePayloadHash(item with { Value = other }).ShouldNotBe(hash); + DataProtoMapper.WritePayloadHash(item with { ExpectedServingGeneration = 1 }).ShouldNotBe(hash); + DataProtoMapper.WritePayloadHash(item with { ExpectedServingGeneration = 2 }).ShouldNotBe( + DataProtoMapper.WritePayloadHash(item with { ExpectedServingGeneration = 1 })); DataProtoMapper .WritePayloadHash(item with { ExpectedCatalogRevision = 2 }) .ShouldNotBe(hash); @@ -261,6 +264,24 @@ public sealed class GrpcDataCodecTests .ShouldNotBe(hash); } + [Fact] + public void Write_generation_preserves_presence_and_rejects_nonpositive_values() + { + var view = new DataView(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject"); + using var value = DataValue.FromScalar(DataValueKind.Int32, 5); + var item = new WriteItem("one", "op", view, value, 1, "inc", TimeSpan.FromSeconds(1)); + var budget = new DataBudget(TimeSpan.FromSeconds(1), 1, 10000); + var absent = DataProtoMapper.EncodeWriteRequest(new([item], budget)); + absent.Items[0].HasExpectedServingGeneration.ShouldBeFalse(); + var wire = DataProtoMapper.EncodeWriteRequest(new([item with { ExpectedServingGeneration = 9 }], budget)); + wire.Items[0].HasExpectedServingGeneration.ShouldBeTrue(); + var decoded = DataProtoMapper.DecodeWriteRequest(wire, 1, 10000); + decoded.Items[0].ExpectedServingGeneration.ShouldBe(9); + decoded.Items[0].Value.Dispose(); + wire.Items[0].ExpectedServingGeneration = 0; + Should.Throw(() => DataProtoMapper.DecodeWriteRequest(wire, 1, 10000)); + } + [Fact] public void Timestamp_ticks_round_trip_and_subtick_precision_is_rejected() { diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs index d971483d8..5f67e8270 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataResponseServingTests.cs @@ -31,6 +31,8 @@ public sealed class GrpcDataResponseServingTests public void Response_identity_support_is_explicit_and_defaults_to_false_for_older_peers() { var legacy = new W.CapabilitiesResponse(); + legacy.WriteServingGenerationEnforced.ShouldBeFalse(); + W.CapabilitiesResponse.Parser.ParseFrom(new W.CapabilitiesResponse { WriteServingGenerationEnforced = true }.ToByteArray()).WriteServingGenerationEnforced.ShouldBeTrue(); legacy.ResponseServingIdentity.ShouldBeFalse(); var decoded = W.CapabilitiesResponse.Parser.ParseFrom(new W.CapabilitiesResponse { ResponseServingIdentity = true }.ToByteArray()); decoded.ResponseServingIdentity.ShouldBeTrue(); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/OpcUa/DeferredAddressSpaceSinkTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/OpcUa/DeferredAddressSpaceSinkTests.cs index 36a0ed58f..3f3a7505b 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/OpcUa/DeferredAddressSpaceSinkTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/OpcUa/DeferredAddressSpaceSinkTests.cs @@ -1,6 +1,7 @@ using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.OpcUa; @@ -12,6 +13,25 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.OpcUa; /// public class DeferredAddressSpaceSinkTests { + [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Projected_publication_preserves_the_typed_batch_and_actual_sink_result() + { + var deferred = new DeferredAddressSpaceSink(); + var projected = deferred.ShouldBeAssignableTo(); + IReadOnlyList batch = Array.Empty(); + projected.TryPublish(batch).ShouldBeFalse(); + deferred.GetCapability().ShouldBeNull(); + var inner = new SpySink(); + deferred.SetSink(inner); + deferred.GetCapability().ShouldBeSameAs(inner); + projected.TryPublish(batch).ShouldBeTrue(); + inner.ProjectedBatch.ShouldBeSameAs(batch); + inner.ProjectedResult = false; + projected.TryPublish(batch).ShouldBeFalse(); + deferred.SetSink(null); + deferred.GetCapability().ShouldBeNull(); + projected.TryPublish(batch).ShouldBeFalse(); + } // ---------- before SetSink — all calls are safe no-ops ---------- [Fact] @@ -200,8 +220,12 @@ public class DeferredAddressSpaceSinkTests // ---- test doubles ---- - private sealed class SpySink : IOpcUaAddressSpaceSink + private sealed class SpySink : IOpcUaAddressSpaceSink, IProjectedValueSink { + public IReadOnlyList? ProjectedBatch { get; private set; } + public bool ProjectedResult { get; set; } = true; + public bool TryPublish(IReadOnlyList values) + { ProjectedBatch = values; return ProjectedResult; } public bool WriteValueCalled { get; private set; } public bool RebuildCalled { get; private set; } public (string AlarmNodeId, AddressSpaceRealm AlarmRealm, IReadOnlyList Folders, AddressSpaceRealm FolderRealm)? WireAlarmNotifiersArgs { get; private set; } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataProjectedIdentityTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataProjectedIdentityTests.cs new file mode 100644 index 000000000..36f229a62 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/GrpcDataProjectedIdentityTests.cs @@ -0,0 +1,56 @@ +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", "P08")] +public sealed class GrpcDataProjectedIdentityTests +{ + [Fact] + public void Script_dependency_references_preserve_realm_and_do_not_alias_local_raw_paths() + { + var origin = new DataAddress("cluster-b", "urn:source", "string", "Plant/Tag"); + var id = ProjectedDataIds.Identifier("mapping", origin); + var raw = ProjectedDataIds.DependencyReference(DataRealm.Raw, id); + var uns = ProjectedDataIds.DependencyReference(DataRealm.Uns, id); + raw.ShouldNotBe(uns); + raw.ShouldNotBe(origin.Identifier); + ProjectedDataIds.TryParseDependencyReference(raw, out var realm, out var decoded).ShouldBeTrue(); + realm.ShouldBe(DataRealm.Raw); + decoded.ShouldBe(id); + ProjectedDataIds.TryParseDependencyReference(origin.Identifier, out _, out _).ShouldBeFalse(); + } + + [Fact] + public void Projected_namespaces_are_disjoint_from_legacy_raw_and_uns_identifiers() + { + ProjectedDataIds.RawNamespaceUri.ShouldNotBe("https://zb.com/otopcua/raw"); + ProjectedDataIds.UnsNamespaceUri.ShouldNotBe("https://zb.com/otopcua/uns"); + ProjectedDataIds.NamespaceUri(DataRealm.Raw).ShouldNotBe(ProjectedDataIds.NamespaceUri(DataRealm.Uns)); + ProjectedDataIds.IsMappedNamespace(ProjectedDataIds.RawNamespaceUri).ShouldBeTrue(); + ProjectedDataIds.IsMappedNamespace(ProjectedDataIds.UnsNamespaceUri).ShouldBeTrue(); + ProjectedDataIds.IsMappedNamespace("https://zb.com/otopcua/raw").ShouldBeFalse(); + ProjectedDataIds.IsMappedNamespace("https://zb.com/otopcua/uns").ShouldBeFalse(); + } + + [Fact] + public void Opaque_identity_preserves_exact_origin_and_mapping_without_separator_collisions() + { + var origin = new DataAddress("cluster-b", "urn:source/raw", "string", "Plant/Line/Tag"); + var identifier = ProjectedDataIds.Identifier("mapping-a", origin); + identifier.ShouldNotBe(ProjectedDataIds.Identifier("mapping-b", origin)); + identifier.ShouldNotBe(ProjectedDataIds.Identifier("mapping-a", origin with { NamespaceUri = "urn:source/uns" })); + ProjectedDataIds.TryDecodeIdentifier(identifier, out var mapping, out var decoded).ShouldBeTrue(); + mapping.ShouldBe("mapping-a"); + decoded.ShouldBe(origin); + ProjectedDataIds.Identifier(mapping, decoded!).ShouldBe(identifier); + } + + [Theory] + [InlineData("")] + [InlineData("not-a-projection")] + [InlineData("../mapping/origin")] + public void Invalid_identifiers_do_not_resolve_to_an_origin(string identifier) => + ProjectedDataIds.TryDecodeIdentifier(identifier, out _, out _).ShouldBeFalse(); +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs new file mode 100644 index 000000000..2e943d24a --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/DataConnections/ProjectedInputBudgetTests.cs @@ -0,0 +1,65 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections; + +public sealed class ProjectedInputBudgetTests +{ + [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Leases_bound_retained_bytes_across_owners_and_release_once() + { + var now = DateTime.UtcNow; + var snapshot = new DataValueSnapshot(new byte[3 * 1024 * 1024], 0, now, now); + var leases = new List(); + try + { + for (var i = 0; i < 5; i++) + { + ProjectedInputBudget.TryRetain([snapshot], out var lease).ShouldBeTrue(); + lease.ShouldNotBeNull(); + leases.Add(lease); + } + ProjectedInputBudget.TryRetain([snapshot], out var rejected).ShouldBeFalse(); + rejected.ShouldBeNull(); + leases[0].Dispose(); + leases[0].Dispose(); + ProjectedInputBudget.TryRetain([snapshot], out var replacement).ShouldBeTrue(); + replacement.ShouldNotBeNull(); + leases.Add(replacement); + ProjectedInputBudget.TryRetain([snapshot], out rejected).ShouldBeFalse("double disposal cannot create extra capacity"); + rejected.ShouldBeNull(); + } + finally { foreach (var lease in leases) lease.Dispose(); } + ProjectedInputBudget.TryRetain([snapshot], out var afterRetirement).ShouldBeTrue(); + afterRetirement.ShouldNotBeNull().Dispose(); + } + + [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Unsupported_mutable_values_fail_closed() + { + var now = DateTime.UtcNow; + var snapshot = new DataValueSnapshot(new object[] { new byte[8] }, 0, now, now); + ProjectedInputBudget.TryRetain([snapshot], out var lease).ShouldBeFalse(); + lease.ShouldBeNull(); + } + + [Fact, Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Snapshot_enumeration_stops_at_the_entry_limit() + { + var seen = 0; + IEnumerable Inputs() + { + var now = DateTime.UtcNow; + while (seen++ < 100_001) yield return new DataValueSnapshot(null, 0, now, now); + } + var accepted = ProjectedInputBudget.TryRetain(Inputs(), out var lease); + try + { + accepted.ShouldBeFalse(); + seen.ShouldBeLessThanOrEqualTo(10_001); + } + finally { lease?.Dispose(); } + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/GrpcDataAlarmEvidenceTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/GrpcDataAlarmEvidenceTests.cs new file mode 100644 index 000000000..844e1e7d3 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/GrpcDataAlarmEvidenceTests.cs @@ -0,0 +1,210 @@ +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataAlarmEvidenceTests +{ + private static ScriptedAlarmDefinition Definition() => new("alarm", "Plant", "alarm", AlarmKind.AlarmCondition, + AlarmSeverity.High, "condition", "return (int)ctx.GetTag(\"Temp\").Value > 100;"); + + [Fact(Timeout = 20000)] + public async Task A_later_authorized_input_cannot_authorize_an_older_async_evaluation() + { + var source = new Source(); var original = new Evidence(); + source.Set(150, original); + var runner = new Runner { Hold = true }; + using var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), + new ScriptLoggerFactory(logger), logger, scriptRunner: runner); + var events = new ConcurrentQueue(); + engine.OnEvent += (_, value) => events.Enqueue(value); + Task? loading = null; + try + { + loading = engine.LoadAsync([Definition()], TestContext.Current.CancellationToken); + await runner.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original.Valid = false; + source.Set(0, new Evidence()); + runner.Release.TrySetResult(ScriptRunOutcome.Ok(true)); + await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Inactive); + events.ShouldNotContain(value => value.Emission == EmissionKind.Activated && value.WorstInputStatusCode == 0); + } + finally + { + runner.Release.TrySetResult(ScriptRunOutcome.Ok(false)); + if (loading is not null) await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + } + + [Fact(Timeout = 20000)] + public async Task An_emission_keeps_its_original_evidence_after_the_cache_is_replaced() + { + var source = new Source(); var original = new Evidence(); source.Set(150, original); + using var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), + new ScriptLoggerFactory(logger), logger, scriptRunner: new Runner()); + var events = new ConcurrentQueue(); engine.OnEvent += (_, value) => events.Enqueue(value); + await engine.LoadAsync([Definition()], TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var emitted = events.Single(value => value.Emission == EmissionKind.Activated); + emitted.InputEvidence.ShouldNotBeNull().IsValid.ShouldBeTrue(); + original.Valid = false; source.Set(0, new Evidence()); + emitted.InputEvidence.IsValid.ShouldBeFalse(); + } + + [Fact(Timeout = 20000)] + public async Task Physical_input_charge_survives_cache_replacement_until_runner_completion() + { + var source = new Source(); var original = new PhysicalEvidence(); source.Set(150, original); + var runner = new Runner { Hold = true }; + using var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), + new ScriptLoggerFactory(logger), logger, scriptRunner: runner); + var loading = engine.LoadAsync([Definition()], TestContext.Current.CancellationToken); + try + { + await runner.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original.Active.ShouldBe(1); + original.Valid = false; source.Set(0, new Evidence()); + original.Active.ShouldBe(1); + runner.Release.TrySetResult(ScriptRunOutcome.Ok(true)); + await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original.Active.ShouldBe(0); + engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Inactive); + } + finally + { + runner.Release.TrySetResult(ScriptRunOutcome.Ok(false)); + await loading.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + } + + [Fact(Timeout = 20000)] + public async Task Physical_input_is_not_dispatched_to_a_runner_without_lifetime_ownership() + { + var source = new Source(); var original = new PhysicalEvidence(); source.Set(150, original); + var inner = new Runner(); + using var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), + new ScriptLoggerFactory(logger), logger, scriptRunner: new UnownedRunner(inner)); + await engine.LoadAsync([Definition()], TestContext.Current.CancellationToken) + .WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + inner.Entered.Task.IsCompleted.ShouldBeFalse(); + original.Active.ShouldBe(0); + engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Inactive); + } + + [Fact(Timeout = 20000)] + public async Task Recovery_and_ack_preserve_condition_but_redact_transient_projected_values() + { + var source = new Source(); var original = new Evidence(); source.Set(150, original); + using var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), + new ScriptLoggerFactory(logger), logger, scriptRunner: new Runner()); + var events = new ConcurrentQueue(); engine.OnEvent += (_, value) => events.Enqueue(value); + await engine.LoadAsync([Definition() with { MessageTemplate = "Temp={Temp}" }], TestContext.Current.CancellationToken); + original.Valid = false; + var projection = engine.GetProjections().Single(); + projection.Message.ShouldBe("Temp={?}"); + (projection.WorstInputStatusCode & 0x80000000u).ShouldNotBe(0u); + await engine.AcknowledgeAsync("alarm", "operator", "accepted", TestContext.Current.CancellationToken); + var acknowledgement = events.Single(value => value.Emission == EmissionKind.Acknowledged); + acknowledgement.Message.ShouldBe("Temp={?}"); + acknowledgement.Condition.Active.ShouldBe(AlarmActiveState.Active); + } + + [Theory(Timeout = 20000)] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task Shadow_copies_only_local_inputs_including_template_only_snapshots(bool projected, bool templateOnly) + { + var source = new Source(); + if (projected) source.Set(150, new Evidence()); else source.SetLocal(150); + var shadow = new Shadow(); + using var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(source, new InMemoryAlarmStateStore(), + new ScriptLoggerFactory(logger), logger, scriptTimeout: TimeSpan.FromSeconds(5), scriptRunner: shadow); + var definition = Definition() with { MessageTemplate = "Temp={Temp}", + PredicateScriptSource = templateOnly ? "return true;" : Definition().PredicateScriptSource }; + await engine.LoadAsync([definition], TestContext.Current.CancellationToken); + shadow.Mirrors.ShouldBe(projected ? 0 : 1); + engine.GetState("alarm").ShouldNotBeNull().Active.ShouldBe(AlarmActiveState.Active); + } + + private sealed class Shadow : IScriptRunner, IScriptShadow + { + public int Mirrors; + public void Mirror(ScriptInvocation invocation, ScriptRunOutcome published) => Mirrors++; + public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) => throw new InvalidOperationException(); + public void Reset(ScriptContextKind kind) { } + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + + private sealed class PhysicalEvidence : Evidence, IAlarmInputPhysicalEvidence + { + public int Active; + public bool TryRetainPhysical(DataValueSnapshot snapshot, out IDisposable? lease) + { + Interlocked.Increment(ref Active); + lease = new ReleaseLease(this); return true; + } + private sealed class ReleaseLease(PhysicalEvidence owner) : IDisposable + { + private PhysicalEvidence? _owner = owner; + public void Dispose() + { + if (Interlocked.Exchange(ref _owner, null) is { } held) Interlocked.Decrement(ref held.Active); + } + } + } + + private sealed class UnownedRunner(Runner inner) : IScriptRunner + { + public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) => inner.RunAsync(invocation, ct); + public void Reset(ScriptContextKind kind) { } + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + + private class Evidence : IAlarmInputEvidence + { + public volatile bool Valid = true; + public bool IsValid => Valid; + } + private sealed class Source : ITagUpstreamSource, IAlarmInputEvidenceSource + { + private readonly ConditionalWeakTable _evidence = new(); + private DataValueSnapshot _snapshot = new(null, 0x80320000, null, null); + internal void Set(int value, Evidence evidence) + { var next = new DataValueSnapshot(value, 0, null, null); _evidence.Add(next, evidence); Volatile.Write(ref _snapshot, next); } + internal void SetLocal(int value) => Volatile.Write(ref _snapshot, new DataValueSnapshot(value, 0, null, null)); + public DataValueSnapshot ReadTag(string path) => Volatile.Read(ref _snapshot); + public IAlarmInputEvidence? CaptureEvidence(DataValueSnapshot snapshot) => _evidence.TryGetValue(snapshot, out var evidence) ? evidence : null; + public IDisposable SubscribeTag(string path, Action observer) => new Empty(); + private sealed class Empty : IDisposable { public void Dispose() { } } + } + private sealed class Runner : IPhysicalScriptRunner + { + public bool Hold; + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public async Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) + { + Entered.TrySetResult(); + try { return Hold ? await Release.Task : ScriptRunOutcome.Ok(true); } + finally { invocation.PhysicalLease?.Dispose(); } + } + public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default) => + invocations.Select(invocation => RunAsync(invocation, ct)).ToArray(); + public void Reset(ScriptContextKind kind) { } + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs index b1c264511..99ae422ec 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs @@ -47,6 +47,35 @@ public sealed class ScriptRunGuardTests ScriptEvaluator evaluator, TimeSpan? timeout = null, CancellationToken ct = default, FakeScriptContext? context = null) => guard.RunAsync(key, source, evaluator, context ?? new FakeScriptContext(), timeout ?? TimeSpan.FromSeconds(5), ct); + [Fact] + public async Task Physical_lease_stays_held_after_observer_timeout_until_evaluator_really_finishes() + { + var guard = new ScriptRunGuard(); using var evaluator = Compile(BriefSpinScript); + var context = new FakeScriptContext(); var held = new PhysicalLease(); + try + { + await Should.ThrowAsync(() => guard.RunAsync("physical", BriefSpinScript, evaluator, + context, ShortTimeout, TestContext.Current.CancellationToken, physicalLease: held)); + held.Disposals.ShouldBe(0); + var refused = new PhysicalLease(); + await Should.ThrowAsync(() => guard.RunAsync("physical", BriefSpinScript, evaluator, + new FakeScriptContext(), ShortTimeout, TestContext.Current.CancellationToken, physicalLease: refused)); + refused.Disposals.ShouldBe(1); held.Disposals.ShouldBe(0); + } + finally { context.Released = true; } + await SpinWaitAsync(() => held.Disposals == 1); + } + private static async Task SpinWaitAsync(Func done) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + while (!done()) await Task.Delay(10, timeout.Token); + } + private sealed class PhysicalLease : IDisposable + { + private int _disposals; public int Disposals => Volatile.Read(ref _disposals); + public void Dispose() => Interlocked.Increment(ref _disposals); + } + [Fact] public async Task Completed_run_returns_the_value_and_releases_the_in_flight_slot() { diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs new file mode 100644 index 000000000..471e8ce2f --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests/GrpcDataCalculationOwnershipTests.cs @@ -0,0 +1,211 @@ +using System.Collections.Concurrent; +using Serilog; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation.Tests; + +public sealed class GrpcDataCalculationOwnershipTests +{ + private sealed class Proof : IProjectedSamplePublicationProof + { + public volatile bool Valid = true; + public bool IsValid => Valid; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => Valid = false; + } + + private sealed class HeldRunner : IPhysicalScriptRunner + { + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ConcurrentQueue Invocations { get; } = new(); + public void Release() => _release.TrySetResult(); + public async Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) + { + Invocations.Enqueue(invocation); + try { await _release.Task; return ScriptRunOutcome.Ok(invocation.Inputs["src/a"].Value); } + finally { invocation.PhysicalLease?.Dispose(); } + } + public void Reset(ScriptContextKind kind) { } + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + + [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public async Task Large_projected_fanout_replaces_pending_entries_with_linear_queue_work() + { + const int tagCount = 200; + const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;"; + var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}"; + var runner = new HeldRunner(); + using var driver = new CalculationDriver(new CalculationDriverOptions + { + RawTags = Enumerable.Range(0, tagCount).Select(i => new RawTagEntry($"calc/{i}", json, WriteIdempotent: false)).ToArray(), + ScriptRunner = runner + }, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger())); + try + { + await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); + var consumer = (IProjectedDependencyConsumer)(object)driver; + var proof = new Proof(); + consumer.OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, proof); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (runner.Invocations.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken); + runner.Invocations.ShouldNotBeEmpty(); + var before = driver.ProjectedQueueVisitsForTest; + consumer.OnProjectedDependencyValue("src/a", 2, 0, DateTime.UtcNow, proof); + var visits = driver.ProjectedQueueVisitsForTest - before; + visits.ShouldBeLessThanOrEqualTo(tagCount * 4L, + "replacing one projected entry per dependent should not scan the other queued tags"); + } + finally { runner.Release(); } + } + + [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public async Task Pending_input_remains_charged_after_the_runner_finishes_while_output_is_blocked() + { + const string source = "return ctx.GetTag(\"src/a\").Value ?? 0;"; + var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}"; + var runner = new HeldRunner(); + using var driver = new CalculationDriver(new CalculationDriverOptions + { + RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner + }, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger())); + var callbackEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var unblock = new ManualResetEventSlim(); + driver.OnDataChange += (_, e) => + { + if (e.Snapshot.StatusCode != 0) return; + callbackEntered.TrySetResult(); + unblock.Wait(TimeSpan.FromSeconds(10)); + }; + try + { + await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); + var bytes = new byte[1024 * 1024]; + ((IProjectedDependencyConsumer)(object)driver).OnProjectedDependencyValue("src/a", bytes, 0, DateTime.UtcNow, new Proof()); + runner.Release(); + await callbackEntered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + // The cache and the pending output each still retain the input; the runner has already released its lease. + ProjectedInputBudget.RetainedBytes.ShouldBeGreaterThanOrEqualTo(2 * bytes.Length); + } + finally { unblock.Set(); runner.Release(); } + } + + [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public async Task Revocation_during_an_output_callback_is_checked_before_the_next_acceptance() + { + const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;"; + var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}"; + var runner = new HeldRunner(); + using var driver = new CalculationDriver(new CalculationDriverOptions + { + RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner + }, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger())); + var firstCallback = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var unblock = new ManualResetEventSlim(); + var downstream = new ConcurrentQueue(); + driver.OnDataChange += (_, e) => + { + if (e.Snapshot.StatusCode != 0) return; + firstCallback.TrySetResult(); + unblock.Wait(TimeSpan.FromSeconds(10)); + }; + driver.OnDataChange += (_, e) => downstream.Enqueue(e); + var proof = new Proof(); + try + { + await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); + ((IProjectedDependencyConsumer)(object)driver).OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, proof); + runner.Release(); + await firstCallback.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + proof.Valid = false; + unblock.Set(); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!driver.IsEvaluationIdle && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken); + driver.IsEvaluationIdle.ShouldBeTrue(); + downstream.ShouldNotContain(e => e.Snapshot.StatusCode == 0); + } + finally { unblock.Set(); runner.Release(); } + } + + [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public async Task Rejected_projected_values_coalesce_while_the_pump_is_blocked() + { + const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;"; + var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}"; + var runner = new HeldRunner(); + using var driver = new CalculationDriver(new CalculationDriverOptions + { + RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner + }, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger())); + var budgetLeases = new List(); + try + { + await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); + var consumer = (IProjectedDependencyConsumer)(object)driver; + consumer.OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, new Proof()); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (runner.Invocations.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken); + runner.Invocations.ShouldHaveSingleItem(); + var now = DateTime.UtcNow; + var charged = new DataValueSnapshot(new byte[3 * 1024 * 1024], 0, now, now); + for (var i = 0; i < 5; i++) + { + ProjectedInputBudget.TryRetain([charged], out var lease).ShouldBeTrue(); + budgetLeases.Add(lease.ShouldNotBeNull()); + } + var payload = new byte[2 * 1024 * 1024]; + var proof = new Proof(); + for (var i = 0; i < 100; i++) consumer.OnProjectedDependencyValue("src/a", payload, 0, now, proof); + var field = typeof(CalculationDriver).GetField("_pending", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var pending = (System.Collections.ICollection)field!.GetValue(driver)!; + pending.Count.ShouldBeLessThanOrEqualTo(1); + } + finally + { + foreach (var lease in budgetLeases) lease.Dispose(); + runner.Release(); + } + } + + [Theory(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [InlineData(true)] + [InlineData(false)] + public async Task Blocked_pump_coalesces_projected_triggers_and_rechecks_captured_source(bool revokeOldProof) + { + const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;"; + var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}"; + var runner = new HeldRunner(); + using var driver = new CalculationDriver(new CalculationDriverOptions + { + RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner + }, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger())); + var output = new ConcurrentQueue(); + driver.OnDataChange += (_, e) => output.Enqueue(e); + await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); + var consumer = (IProjectedDependencyConsumer)(object)driver; + var oldProof = new Proof(); + try + { + consumer.OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, oldProof); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (runner.Invocations.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken); + runner.Invocations.ShouldHaveSingleItem().PhysicalLease.ShouldNotBeNull(); + if (revokeOldProof) oldProof.Valid = false; + var latest = new Proof(); + for (var i = 2; i <= 100; i++) + consumer.OnProjectedDependencyValue("src/a", i, 0, DateTime.UtcNow, latest); + runner.Release(); + deadline = DateTime.UtcNow.AddSeconds(10); + while (!driver.IsEvaluationIdle && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken); + driver.IsEvaluationIdle.ShouldBeTrue(); + runner.Invocations.Count.ShouldBeLessThanOrEqualTo(2); + output.ShouldNotContain(e => e.Snapshot.StatusCode == 0 && Equals(e.Snapshot.Value, 1)); + output.ShouldContain(e => e.Snapshot.StatusCode == 0 && Equals(e.Snapshot.Value, 100)); + } + finally { runner.Release(); } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/RoslynVirtualTagEvaluatorRunGuardTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/RoslynVirtualTagEvaluatorRunGuardTests.cs index cd18ae5ee..e6bc14ba0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/RoslynVirtualTagEvaluatorRunGuardTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/RoslynVirtualTagEvaluatorRunGuardTests.cs @@ -3,6 +3,8 @@ using Serilog; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Scripting; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; using ZB.MOM.WW.OtOpcUa.Host.Engines; namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests; @@ -15,6 +17,31 @@ namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests; /// public sealed class RoslynVirtualTagEvaluatorRunGuardTests { + private sealed class TrackedLease : IDisposable + { + public int Disposals; + public void Dispose() => Interlocked.Increment(ref Disposals); + } + + [Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public async Task Projected_in_process_timeout_holds_lease_until_script_really_finishes() + { + using var sut = new RoslynVirtualTagEvaluator( + NullLogger.Instance, NoOpScriptRoot(), TimeSpan.FromMilliseconds(60)); + var lease = new TrackedLease(); + var now = DateTime.UtcNow; + var inputs = new Dictionary { ["a"] = new(12, 0, now, now) }; + const string script = "var end = System.DateTime.UtcNow.AddSeconds(2); while (System.DateTime.UtcNow < end) { } return ctx.GetTag(\"a\").Value;"; + var result = await ((IProjectedVirtualTagEvaluator)sut).EvaluateProjectedAsync("vt-physical", script, inputs, lease); + result.Success.ShouldBeFalse(); + result.Reason!.ShouldContain("timed out"); + lease.Disposals.ShouldBe(0); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (Volatile.Read(ref lease.Disposals) == 0 && DateTime.UtcNow < deadline) + await Task.Delay(10, TestContext.Current.CancellationToken); + lease.Disposals.ShouldBe(1); + } + private static ScriptRootLogger NoOpScriptRoot() => new(new LoggerConfiguration().CreateLogger()); private const string SpinScript = diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs new file mode 100644 index 000000000..cea6e5221 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataProjectionRoutingTests.cs @@ -0,0 +1,420 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Akka.Configuration; +using Akka.TestKit.Xunit; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataProjectionRoutingTests : TestKit +{ + public GrpcDataProjectionRoutingTests() : base(ConfigurationFactory.ParseString(""" + akka.actor.provider = cluster + akka.remote.dot-netty.tcp.hostname = "127.0.0.1" + akka.remote.dot-netty.tcp.port = 0 + akka.loglevel = WARNING + """)) { } + + private static ProjectedValueRoute Route(string mapping = "mapping", string originIdentifier = "Plant/Value") + { + var id = ProjectedDataIds.Identifier(mapping, new("source", "urn:source/raw", "string", originIdentifier)); + return new("grpc-data:connection", ProjectedDataIds.DependencyReference(DataRealm.Raw, id), DataRealm.Raw, + id, 1, new("origin", "boot", "Primary", 1, 1, 1), Guid.NewGuid()); + } + + private IActorRef Start(RecordingSink sink, IActorRef? mux = null, ActorProjectedValuePublisher? projectedPublisher = null) + { + var publisher = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink: sink)); + var acknowledgments = CreateTestProbe(); + var fetcher = new EmptyArtifact(); + var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: NodeId.Parse("node-a"), + localRoles: new HashSet { "driver" }, dependencyMux: mux, opcUaPublishActor: publisher, + ackRouter: acknowledgments.Ref, fetchAndCacheMode: true, artifactFetcher: fetcher, + projectedPublisher: projectedPublisher)); + var revision = RevisionHash.Parse(Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(fetcher.Bytes))); + host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId())); + acknowledgments.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(ApplyAckOutcome.Applied); + return host; + } + + private static ProjectedValueUpdate Update(ProjectedValueRoute route, Gate proof, object value) => + new(route, new(value, 0, null, null), new(TimeSpan.FromSeconds(3), null), proof.Clock.GetTimestamp(), proof); + + [Fact(Timeout = 20000)] + public async Task Real_host_routes_immutable_typed_samples_to_sdk_and_exact_dependency_key() + { + var sink = new RecordingSink(); + var mux = Sys.ActorOf(DependencyMuxActor.Props()); + var subscriber = CreateTestProbe(); + var route = Route(); + mux.Tell(new DependencyMuxActor.RegisterInterest([route.DependencyReference, + ProjectedDataIds.DependencyReference(DataRealm.Uns, route.LocalIdentifier), "Plant/Value"], subscriber.Ref)); + await mux.Ask(new Identify("registered"), TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + IActorRef? host = null; + IActorRef StartOnce() => host ??= Start(sink, mux); + using var broker = new ActorProjectedValuePublisher(() => StartOnce(), _ => true, 8, 1_000_000, TimeProvider.System); + var proof = new Gate(); + var bytes = new byte[] { 1, 2 }; + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, bytes) with { IsCompleteSnapshot = true }]).ShouldBeTrue(); + bytes[0] = 99; + await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var stored = sink.Writes.ShouldHaveSingleItem(); + stored.Snapshot.Value.ShouldBeOfType().ShouldBe(new byte[] { 1, 2 }); + stored.OriginAgeBounds.Lower.ShouldBe(TimeSpan.FromSeconds(3)); + stored.IsCompleteSnapshot.ShouldBeTrue(); + stored.Proof.IsValid.ShouldBeTrue(); + VirtualTagActor.DependencyValueChanged? dependency = null; + subscriber.ExpectMsg(TimeSpan.FromSeconds(5), + cancellationToken: TestContext.Current.CancellationToken).Consume(items => dependency = items.ShouldHaveSingleItem()); + dependency.ShouldNotBeNull().TagId.ShouldBe(route.DependencyReference); + proof.Invalidate(); + stored.Proof.IsValid.ShouldBeFalse(); + AwaitAssert(() => broker.PendingBytes.ShouldBe(0), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 20000)] + public async Task Replacing_a_live_source_fences_old_witnesses_without_retiring_the_new_source() + { + var sink = new RecordingSink(); var host = Start(sink); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); var original = new Gate(); var replacement = new Gate(); + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, original, 1)]).ShouldBeTrue(); + AwaitAssert(() => sink.Writes.Count.ShouldBe(1), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + var old = sink.Writes.Single().Proof; + broker.TryPublish([Update(route, replacement, 2) with { IsCompleteSnapshot = true }]).ShouldBeTrue(); + AwaitAssert(() => sink.Writes.Count.ShouldBe(2), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + var current = sink.Writes.Last().Proof; + original.IsValid.ShouldBeTrue("replacement does not rely on invalidating an external source"); + old.IsSourceValid.ShouldBeFalse(); + old.IsValid.ShouldBeFalse(); + current.IsValid.ShouldBeTrue(); + old.Invalidate(); + current.IsValid.ShouldBeTrue("retiring the old witness cannot retire its replacement"); + } + + [Theory(Timeout = 20000)] + [InlineData(false)] + [InlineData(true)] + public void Completed_slot_reuse_cannot_deliver_newer_samples_before_older_queued_samples(bool sdkStage) + { + var host = CreateTestProbe(); var sdk = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); var proof = new Gate(); broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, 1)]).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, 2)]).ShouldBeTrue(); + object oldest; + if (sdkStage) + { + var queued = ((Array)Invoke(broker, "TakeQueuedValues", host.Ref)!).Cast().ToArray(); + oldest = queued.Single(batch => Value(batch) == 1); + foreach (var batch in queued) Invoke(broker, "EnqueueForSdk", batch, sdk.Ref, null); + } + else + { + var pending = (System.Collections.IEnumerable)typeof(ActorProjectedValuePublisher) + .GetField("_pending", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(broker)!; + oldest = pending.Cast().Single(batch => Value(batch) == 1); + } + Invoke(oldest, "TryBegin").ShouldBe(true); + Invoke(oldest, "Complete", true); + broker.TryPublish([Update(route, proof, 3)]).ShouldBeTrue(); + var remaining = ((Array)Invoke(broker, "TakeQueuedValues", host.Ref)!).Cast().ToArray(); + if (sdkStage) + { + foreach (var batch in remaining) Invoke(broker, "EnqueueForSdk", batch, sdk.Ref, null); + remaining = ((Array)Invoke(broker, "TakeSdkValues", sdk.Ref)!).Cast().ToArray(); + } + remaining.Select(Value).ShouldBe(new[] { 2, 3 }); + + static object? Invoke(object target, string name, params object?[] arguments) => target.GetType() + .GetMethod(name, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.Invoke(target, arguments); + static int Value(object batch) => (int)((IReadOnlyList)batch.GetType() + .GetProperty("Writes", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.GetValue(batch)!)[0].Snapshot.Value!; + } + + [Fact(Timeout = 20000)] + public void Paused_host_has_bounded_payload_free_wakeups_after_repeated_cancellations() + { + var host = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); + var sweep = typeof(ActorProjectedValuePublisher).GetMethod("SweepQueued", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).ShouldNotBeNull(); + for (var i = 0; i < 40; i++) + { + var proof = new Gate(); + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, new byte[16_384])]).ShouldBeTrue(); + proof.Invalidate(); + sweep.Invoke(broker, null); + broker.PendingBytes.ShouldBe(0); + } + // One value wake plus one independently coalesced retirement wake at most. + host.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + host.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + host.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 20000)] + public async Task Paused_mux_receives_bounded_wakes_while_sdk_accepts_many_projected_values() + { + var sink = new RecordingSink(); var mux = CreateTestProbe(); var host = Start(sink, mux.Ref); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); var proof = new Gate(); broker.TryBind(route).ShouldBeTrue(); + for (var i = 0; i < 20; i++) + { + broker.TryPublish([Update(route, proof, new byte[1024])]).ShouldBeTrue(); + var expected = i + 1; + AwaitAssert(() => sink.Writes.Count.ShouldBe(expected), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + } + await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + mux.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + mux.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 20000)] + public async Task Paused_subscriber_receives_bounded_wakes_after_projected_mux_fanout() + { + var sink = new RecordingSink(); var mux = Sys.ActorOf(DependencyMuxActor.Props()); var subscriber = CreateTestProbe(); + var route = Route(); + mux.Tell(new DependencyMuxActor.RegisterInterest([route.DependencyReference], subscriber.Ref)); + await mux.Ask(new Identify("registered"), TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var host = Start(sink, mux); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System); + var proof = new Gate(); broker.TryBind(route).ShouldBeTrue(); + for (var i = 0; i < 20; i++) + { + broker.TryPublish([Update(route, proof, new byte[1024])]).ShouldBeTrue(); + var expected = i + 1; + AwaitAssert(() => sink.Writes.Count.ShouldBe(expected), TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + } + await mux.Ask(new Identify("drained"), TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + subscriber.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 20000)] + public async Task Retiring_an_old_stream_owner_cannot_remove_its_replacement() + { + var sink = new RecordingSink(); + var host = Start(sink); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System); + var old = Route(); var current = old with { PublicationId = Guid.NewGuid() }; + broker.TryBind(old).ShouldBeTrue(); broker.TryBind(current).ShouldBeTrue(); + broker.Retire(old); + broker.TryPublish([Update(old, new Gate(), 1)]).ShouldBeFalse(); + broker.TryPublish([Update(current, new Gate(), 2)]).ShouldBeTrue(); + await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + sink.Writes.ShouldHaveSingleItem().Snapshot.Value.ShouldBe(2); + } + + [Fact(Timeout = 20000)] + public async Task Disposal_keeps_physical_sink_work_charged_until_it_returns() + { + using var release = new ManualResetEventSlim(); + var sink = new RecordingSink { BeforePublish = () => release.Wait(TimeSpan.FromSeconds(10)) }; + var host = Start(sink); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); + var proof = new Gate(); + try + { + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, 42)]).ShouldBeTrue(); + await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var held = broker.PendingBytes; + held.ShouldBeGreaterThan(0); + broker.Dispose(); + broker.PendingBytes.ShouldBe(held); + release.Set(); + AwaitAssert(() => broker.PendingBytes.ShouldBe(0), TimeSpan.FromSeconds(5), + cancellationToken: TestContext.Current.CancellationToken); + sink.Writes.ShouldBeEmpty(); + } + finally { release.Set(); } + } + + [Fact(Timeout = 15000)] + public void Retiring_repeated_owners_of_one_view_coalesces_the_host_wakeup() + { + var host = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 2, 1_000_000, TimeProvider.System); + var first = Route(); + for (var i = 0; i < 100; i++) + { + var route = first with { PublicationId = Guid.NewGuid() }; + broker.TryBind(route).ShouldBeTrue(); + broker.Retire(route); + } + host.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + host.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 20000)] + public void New_host_activation_drains_retained_retirement_and_restores_admission() + { + var oldHost = CreateTestProbe(); + IActorRef host = oldHost.Ref; + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 1, 1_000_000, TimeProvider.System); + var old = Route(); + broker.TryBind(old).ShouldBeTrue(); + broker.Retire(old); + oldHost.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + var next = Route("next-mapping"); + broker.TryBind(next).ShouldBeFalse(); + host = Start(new RecordingSink(), projectedPublisher: broker); + AwaitAssert(() => broker.TryBind(next).ShouldBeTrue(), TimeSpan.FromSeconds(5), + cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public void Route_and_retirement_residency_respects_a_byte_limit_independently_of_route_count() + { + var host = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, + TimeProvider.System, maximumControlBytes: 8192); + var large = Route(originIdentifier: new string('x', 8192)); + large.DependencyReference.Length.ShouldBeGreaterThan(8192); + broker.TryBind(large).ShouldBeFalse(); + broker.TryBind(Route()).ShouldBeTrue(); + } + + [Fact(Timeout = 20000)] + public async Task Ordinary_deltas_keep_the_same_live_source_witness_at_the_sdk_boundary() + { + var sink = new RecordingSink(); + var host = Start(sink); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); + var proof = new Gate(); + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, proof, 1)]).ShouldBeTrue(); + await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + broker.TryPublish([Update(route, proof, 2)]).ShouldBeTrue(); + AwaitAssert(() => sink.Writes.Count.ShouldBe(2), TimeSpan.FromSeconds(5), + cancellationToken: TestContext.Current.CancellationToken); + var values = sink.Writes.ToArray(); + values[0].Proof.SourceIdentity.ShouldBeSameAs(values[1].Proof.SourceIdentity); + proof.Invalidate(); + values.ShouldAllBe(value => !value.Proof.IsValid); + } + + [Fact(Timeout = 20000)] + public async Task A_new_sample_cannot_freshen_an_older_queued_sample_from_the_same_source() + { + var clock = new TestClock(); + var sink = new RecordingSink(); + var host = Start(sink); + using var broker = new ActorProjectedValuePublisher(() => host, _ => true, 8, 1_000_000, clock); + var route = Route(); + var proof = new Gate(clock); + ProjectedValueUpdate Sample(int value) => new(route, new(value, 0, null, null), + new(TimeSpan.Zero, TimeSpan.Zero), clock.GetTimestamp(), proof, MaximumSampleAge: TimeSpan.FromSeconds(5)); + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Sample(1)]).ShouldBeTrue(); + await sink.Completed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var old = sink.Writes.ShouldHaveSingleItem(); + clock.Advance(TimeSpan.FromSeconds(6)); + old.Proof.IsSourceValid.ShouldBeTrue(); + old.Proof.IsValid.ShouldBeFalse(); + broker.TryPublish([Sample(2)]).ShouldBeTrue(); + AwaitAssert(() => sink.Writes.Count.ShouldBe(2), TimeSpan.FromSeconds(5), + cancellationToken: TestContext.Current.CancellationToken); + var current = sink.Writes.Last(); + current.Proof.SourceIdentity.ShouldBeSameAs(old.Proof.SourceIdentity); + current.Proof.IsValid.ShouldBeTrue(); + old.Proof.IsValid.ShouldBeFalse(); + } + + [Fact] + public void An_unknown_upper_age_bound_cannot_prove_finite_freshness() + { + var host = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, TimeProvider.System); + var route = Route(); + broker.TryBind(route).ShouldBeTrue(); + broker.TryPublish([Update(route, new Gate(), 1) with + { + OriginAgeBounds = new(TimeSpan.Zero, null), MaximumSampleAge = TimeSpan.FromSeconds(5) + }]).ShouldBeFalse(); + } + + [Fact] + public void Larger_replacement_route_metadata_cannot_bypass_its_control_byte_limit() + { + var host = CreateTestProbe(); + using var broker = new ActorProjectedValuePublisher(() => host.Ref, _ => true, 8, 1_000_000, + TimeProvider.System, maximumControlBytes: 8192); + var route = Route(); + broker.TryBind(route).ShouldBeTrue(); + var held = broker.RetainedControlBytes; + var replacement = route with { PublicationId = Guid.NewGuid(), + Serving = route.Serving with { Incarnation = new string('x', 100_000) } }; + broker.TryBind(replacement).ShouldBeFalse(); + broker.RetainedControlBytes.ShouldBe(held); + } + + private sealed class Gate(TimeProvider? clock = null) : IProjectedSamplePublicationProof + { + private int _valid = 1; + public bool IsValid => Volatile.Read(ref _valid) != 0; + public TimeProvider Clock => clock ?? TimeProvider.System; + public void Invalidate() => Interlocked.Exchange(ref _valid, 0); + } + + private sealed class TestClock : TimeProvider + { + private long _ticks; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => Volatile.Read(ref _ticks); + public override DateTimeOffset GetUtcNow() => DateTimeOffset.UnixEpoch.AddTicks(GetTimestamp()); + internal void Advance(TimeSpan elapsed) => Interlocked.Add(ref _ticks, elapsed.Ticks); + } + + private sealed class EmptyArtifact : IDeploymentArtifactFetcher + { + internal readonly byte[] Bytes = System.Text.Encoding.UTF8.GetBytes("{\"DriverInstances\":[]}"); + public Task FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken cancellationToken) => + Task.FromResult(Bytes); + } + + private sealed class RecordingSink : IOpcUaAddressSpaceSink, IProjectedValueSink + { + internal readonly ConcurrentQueue Writes = new(); + internal readonly TaskCompletionSource Completed = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal Action? BeforePublish { get; init; } + public bool TryPublish(IReadOnlyList values) + { + Entered.TrySetResult(); + BeforePublish?.Invoke(); + if (values.Any(value => !value.Proof.IsValid)) return false; + foreach (var value in values) Writes.Enqueue(value); + Completed.TrySetResult(); return true; + } + public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { } + public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { } + public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { } + public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { } + public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { } + public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { } + public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { } + public void RebuildAddressSpace() { } + public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { } + public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs index bd2b80ed9..04bceeea2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/DataConnections/GrpcDataRuntimeRegistrationTests.cs @@ -22,6 +22,7 @@ using Microsoft.Extensions.Hosting; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; using ZB.MOM.WW.OtOpcUa.Host.Configuration; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; @@ -29,6 +30,32 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")] public sealed class GrpcDataRuntimeRegistrationTests { + [Fact, Trait("Phase", "P08")] + public async Task Projection_services_share_the_live_deployed_connection_and_catalog_graph() + { + var services = new ServiceCollection(); + services.AddSingleton(new LocalRole()); + services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService())); + services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService())); + services.AddSingleton(sp => new TriePermissionEvaluator(sp.GetRequiredService().Tries)); + services.AddSingleton(new GrpcDataSecretProvisioningTests.MemoryStore()); + services.AddSingleton(new GrpcDataSecretProvisioningTests.TestCipher()); + services.AddSingleton(new GrpcDataSecretProvisioningTests.NoopInvalidator()); + services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true); + await using var provider = services.BuildServiceProvider(); + var resolver = provider.GetRequiredService(); + provider.GetRequiredService().ShouldBeSameAs(resolver); + provider.GetRequiredService() + .ShouldBeSameAs(provider.GetRequiredService()); + provider.GetRequiredService().Active.ShouldBeEmpty(); + provider.GetRequiredService() + .ShouldBeSameAs(provider.GetRequiredService()); + provider.GetRequiredService().ShouldNotBeNull(); + provider.GetRequiredService().ShouldNotBeNull(); + provider.GetRequiredService() + .ShouldBeSameAs(provider.GetRequiredService()); + } + [Fact] public void Disabled_registration_requires_no_driver_or_secret_store_and_exposes_no_facade() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/RoslynVirtualTagEvaluatorScriptRunnerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/RoslynVirtualTagEvaluatorScriptRunnerTests.cs index 32a370681..06cecfe84 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/RoslynVirtualTagEvaluatorScriptRunnerTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Engines/RoslynVirtualTagEvaluatorScriptRunnerTests.cs @@ -4,6 +4,7 @@ using Serilog; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Engines; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Scripting; using ZB.MOM.WW.OtOpcUa.Host.Engines; @@ -34,6 +35,48 @@ public sealed class RoslynVirtualTagEvaluatorScriptRunnerTests public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => ["vt-q"]; } + private sealed class RetainedLease : IDisposable + { + public int Disposed; + public void Dispose() => Interlocked.Increment(ref Disposed); + } + + private sealed class PhysicalRunner : IPhysicalScriptRunner + { + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ScriptInvocation? Invocation; + public void Release() => _release.TrySetResult(); + public async Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) + { + Invocation = invocation; + try { await _release.Task; return ScriptRunOutcome.Ok(42); } + finally { invocation.PhysicalLease?.Dispose(); } + } + public void Reset(ScriptContextKind kind) { } + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public async Task Projected_run_transfers_physical_lease_to_the_worker_until_completion() + { + var runner = new PhysicalRunner(); + using var sut = Build(runner); + var lease = new RetainedLease(); + try + { + var run = ((IProjectedVirtualTagEvaluator)(object)sut).EvaluateProjectedAsync("vt", "return (int)ctx.GetTag(\"a\").Value + 1;", Deps(41), lease); + var deadline = DateTime.UtcNow.AddSeconds(5); + while (runner.Invocation is null && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken); + runner.Invocation.ShouldNotBeNull(); + runner.Invocation.PhysicalLease.ShouldNotBeNull(); + lease.Disposed.ShouldBe(0); + runner.Release(); + (await run).Value.ShouldBe(42); + lease.Disposed.ShouldBe(1); + } + finally { runner.Release(); } + } + private static RoslynVirtualTagEvaluator Build(IScriptRunner? runner) => new(NullLogger.Instance, new ScriptRootLogger(new LoggerConfiguration().CreateLogger()), runTimeout: TimeSpan.FromMilliseconds(1500), scriptRunner: runner); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs new file mode 100644 index 000000000..88275739c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkBrowseWireTests.cs @@ -0,0 +1,209 @@ +using Opc.Ua; +using Opc.Ua.Client; +using Opc.Ua.Server; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkBrowseWireTests +{ + [Fact(Timeout = 90000)] + public async Task BrowseNext_is_session_bound_and_rechecks_page_authority_before_each_child() + { + var ct = Deadline(); + await using var rig = await StartModeAsync("ProjectedBrowseCursor", "None", ct); + rig.Server.SetProjectedBrowseLimits(maxCursors: 1, maxBytes: 8 * 1024 * 1024); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var root = new DataAddress("origin", "urn:raw", "string", "root"); + var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), + parent, "Remote", "Plant/Remote", "mapping", 1, () => true); + rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); + var children = new List(); + foreach (var name in new[] { "First", "Second", "Third" }) + { + var origin = root with { Identifier = name }; + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Remote/" + name); + var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, + DataOperations.Browse | DataOperations.Read, 1, null, null, false); + rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), anchor!.Value, + metadata, 1, () => true), out var child).ShouldBeTrue(); + children.Add(child!.Value); + } + var pages = new BrowsePages(children); + rig.Nm.ProjectedBrowseAccess = pages; + var access = new BrowseOnlyAccess(); + rig.Nm.ProjectedDataAccess = access; + using var first = await rig.ConnectAsync(anonymous: false, ct); + using var second = await rig.ConnectAsync(anonymous: false, ct); + var firstClient = (SessionClient)first; + var secondClient = (SessionClient)second; + var result = await firstClient.BrowseAsync(H(), null, 1, [new BrowseDescription + { + NodeId = anchor!.Value, BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true, + ResultMask = (uint)BrowseResultMask.All, + }], ct); + StatusCode.IsGood(result.Results[0].StatusCode).ShouldBeTrue(); + result.Results[0].References.Count.ShouldBe(1); + var cursor = result.Results[0].ContinuationPoint; + cursor.IsEmpty.ShouldBeFalse(); + var stolen = await secondClient.BrowseNextAsync(H(), false, [cursor], ct); + stolen.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); + var next = await firstClient.BrowseNextAsync(H(), false, [cursor], ct); + StatusCode.IsGood(next.Results[0].StatusCode).ShouldBeTrue(); + next.Results[0].References.Count.ShouldBe(1); + var replacement = next.Results[0].ContinuationPoint; + replacement.IsEmpty.ShouldBeFalse("the claimed cursor must reuse its reservation at the configured count limit"); + access.OnAcquire = () => pages.Valid = false; + var resumed = await firstClient.BrowseNextAsync(H(), false, [replacement], ct); + StatusCode.IsBad(resumed.Results[0].StatusCode).ShouldBeTrue(); + resumed.Results[0].References.Count.ShouldBe(0); + } + + [Fact(Timeout = 90000)] + public async Task Mapped_browse_honors_direction_class_mask_and_result_mask() + { + var ct = Deadline(); + await using var rig = await StartModeAsync("ProjectedBrowseFilters", "None", ct); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:raw", "string", "root"); + var definition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent, + "Remote", "Plant/Remote", "mapping", 1, () => true); + rig.Nm.TryEnsureProjectedAnchor(definition, out var anchor).ShouldBeTrue(); + var childOrigin = origin with { Identifier = "child" }; + var childView = new DataView(childOrigin, DataRealm.Raw, "mapping", 1, "Plant/Remote/Child"); + var metadata = new DataMetadata(childView, "Child", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false); + rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", childOrigin), anchor!.Value, + metadata, 1, () => true), out var child).ShouldBeTrue(); + rig.Nm.ProjectedBrowseAccess = new BrowsePages([child!.Value]); + rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess(); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + async Task Browse(BrowseDirection direction, NodeId referenceType, uint classMask, uint resultMask) + { + var reply = await client.BrowseAsync(H(), null, 10, [new BrowseDescription { NodeId = anchor.Value, + BrowseDirection = direction, ReferenceTypeId = referenceType, IncludeSubtypes = true, + NodeClassMask = classMask, ResultMask = resultMask }], ct); + return reply.Results[0]; + } + var objects = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, (uint)NodeClass.Object, (uint)BrowseResultMask.All); + StatusCode.IsGood(objects.StatusCode).ShouldBeTrue(); + objects.References.Count.ShouldBe(0); + var variables = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, (uint)NodeClass.Variable, 0); + StatusCode.IsGood(variables.StatusCode).ShouldBeTrue(); + variables.References.Count.ShouldBe(1); + variables.References[0].BrowseName.IsNull.ShouldBeTrue(); + variables.References[0].NodeClass.ShouldBe(NodeClass.Unspecified); + var inverse = await Browse(BrowseDirection.Inverse, ReferenceTypeIds.Organizes, 0, (uint)BrowseResultMask.All); + StatusCode.IsGood(inverse.StatusCode).ShouldBeTrue(); + inverse.References.ToArray()!.ShouldContain(reference => reference.NodeId == new ExpandedNodeId(parent) && !reference.IsForward); + var noMatch = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HasTypeDefinition, 0, (uint)BrowseResultMask.All); + StatusCode.IsGood(noMatch.StatusCode).ShouldBeTrue(); + noMatch.References.Count.ShouldBe(0); + } + + [Fact(Timeout = 90000)] + public async Task Cursor_expiring_during_a_remote_fetch_cannot_publish_or_be_replaced() + { + var ct = Deadline(); + await using var rig = await StartModeAsync("ProjectedCursorExpiry", "None", ct); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var root = new DataAddress("origin", "urn:raw", "string", "root"); + var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), parent, + "Remote", "Plant/Remote", "mapping", 1, () => true); + rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); + var children = new List(); + foreach (var name in new[] { "First", "Second" }) + { + var origin = root with { Identifier = name }; + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Remote/" + name); + var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false); + rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), anchor!.Value, + metadata, 1, () => true), out var child).ShouldBeTrue(); + children.Add(child!.Value); + } + var clock = new TestMonotonicClock(); + var pages = new BlockingPages(children); + rig.Nm.ProjectedBrowseClock = clock; + rig.Nm.ProjectedBrowseAccess = pages; + rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess(); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var first = await client.BrowseAsync(H(), null, 1, [new BrowseDescription { NodeId = anchor!.Value, + BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct); + var token = first.Results[0].ContinuationPoint; + token.IsEmpty.ShouldBeFalse(); + var next = client.BrowseNextAsync(H(), false, [token], ct).AsTask(); + try + { + await pages.FetchEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + clock.Advance(TimeSpan.FromSeconds(61)); + } + finally { pages.Release.TrySetResult(); } + var result = await next.WaitAsync(TimeSpan.FromSeconds(10), ct); + StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue(); + result.Results[0].References.Count.ShouldBe(0); + result.Results[0].ContinuationPoint.IsEmpty.ShouldBeTrue(); + var retry = await client.BrowseNextAsync(H(), false, [token], ct); + retry.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); + } + + private sealed class TestMonotonicClock : TimeProvider + { + private long _ticks; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => Interlocked.Read(ref _ticks); + public void Advance(TimeSpan value) => Interlocked.Add(ref _ticks, value.Ticks); + } + private sealed class BlockingPages(IReadOnlyList children) : IProjectedBrowseAccess + { + public TaskCompletionSource FetchEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) => ProjectedBrowseReadiness.Ready; + public async Task WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken) + { + if (request.Cursor is null) return new(ProjectedBrowseReadiness.Ready, [children[0]], "next", false, () => true); + FetchEntered.TrySetResult(); + await Release.Task.WaitAsync(cancellationToken); + return new(ProjectedBrowseReadiness.Ready, [children[1]], null, true, () => true); + } + } + + private sealed class BrowsePages(IReadOnlyList children) : IProjectedBrowseAccess + { + public bool Valid = true; + public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) => ProjectedBrowseReadiness.Ready; + public ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest request) => + new(ProjectedBrowseReadiness.Ready, children, null, true, () => Valid); + } + private sealed class BrowseOnlyAccess : IProjectedDataAccess + { + public Action? OnAcquire; + public TimeProvider Clock => TimeProvider.System; + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) + { OnAcquire?.Invoke(); demand = new BrowseDemand(); return operation == DataOperations.Browse; } + public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) => false; + public Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException(); + public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => false; + } + private sealed class BrowseDemand : IProjectedDemandLease + { + public DataView OriginView { get; } = new(new("origin", "urn:raw", "string", "root"), DataRealm.Raw, null, 0, "root"); + public DataRealm Realm => DataRealm.Raw; + public string LocalIdentifier => "unused"; + public long ProjectionGeneration => 1; + public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5); + public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1); + public CancellationToken CancellationToken => CancellationToken.None; + public bool IsValid => true; + public void Dispose() { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs new file mode 100644 index 000000000..927273da3 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/GrpcDataSdkDeliveryWireTests.cs @@ -0,0 +1,449 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkDeliveryWireTests +{ + [Theory(Timeout = 90000)] + [InlineData("None", false)] + [InlineData("Warm", false)] + [InlineData("None", true)] + [InlineData("Warm", true)] + public async Task Queued_sample_revoked_before_delivery_is_denied_on_publish_and_republish(string mode, bool rotateSource) + { + var ct = Deadline(); + await using var rig = await StartModeAsync("GrpcProjected" + mode, mode, ct); + if (mode == "Warm") Promote(rig.Server.CreateStandbyProjection()!); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:source", "string", "speed"); + var localView = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed"); + var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1); + var metadata = new DataMetadata(localView, "Speed", "Tag", DataValueKind.Int32, -1, [], false, + DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, Serving: serving); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out var projected).ShouldBeTrue(); + var access = new FakeAccess(localView with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" }, serving); + rig.Nm.ProjectedDataAccess = access; + var proof = new SampleProof(); + var sink = (IProjectedValueSink)rig.Sink; + bool Push(int number) => sink.TryPublish([new(DataRealm.Raw, identifier, 1, serving, + new DataValueSnapshot(number, StatusCodes.Good.Code, null, null), new(TimeSpan.Zero, TimeSpan.Zero), + TimeProvider.System.GetTimestamp(), proof)]); + Push(1).ShouldBeTrue(); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var node = new NodeId(identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var itemId = await AddItemAsync(client, sub, node, 7, 10, ct); + DataChanges((await PublishDataAsync(client, ct)).NotificationMessage).ShouldContain(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.Good); + await client.SetPublishingModeAsync(H(), false, [sub], ct); + Push(42).ShouldBeTrue(); + await client.ModifyMonitoredItemsAsync(H(), sub, TimestampsToReturn.Both, [new MonitoredItemModifyRequest + { + MonitoredItemId = itemId, RequestedParameters = new MonitoringParameters { ClientHandle = 9, SamplingInterval = 0, QueueSize = 10, DiscardOldest = true } + }], ct); + if (rotateSource) + { + proof.Invalidate(); + proof = new SampleProof(); + Push(43).ShouldBeTrue(); + } + else access.Valid = false; + await client.SetPublishingModeAsync(H(), true, [sub], ct); + var delivered = await PublishDataAsync(client, ct); + var values = DataChanges(delivered.NotificationMessage); + values.ShouldNotBeEmpty(); + values.ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull); + var replay = await client.RepublishAsync(H(), sub, delivered.NotificationMessage.SequenceNumber, ct); + DataChanges(replay.NotificationMessage).ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull); + } + + [Theory(Timeout = 90000)] + [InlineData("None")] + [InlineData("Warm")] + public async Task Deleted_item_with_reused_client_handle_never_reauthorizes_old_republish(string mode) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("Reuse" + mode, mode, ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var oldItem = await AddItemAsync(client, sub, node, 7, 10, ct); + var first = await PublishDataAsync(client, ct); + DataChanges(first.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good); + await client.DeleteMonitoredItemsAsync(H(), sub, [oldItem], ct); + await AddItemAsync(client, sub, node, 7, 10, ct); + var replay = await client.RepublishAsync(H(), sub, first.NotificationMessage.SequenceNumber, ct); + DataChanges(replay.NotificationMessage).ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull); + } + + [Theory(Timeout = 90000)] + [InlineData("None")] + [InlineData("Warm")] + public async Task Same_item_recovers_after_fresh_snapshot_but_old_republish_remains_denied(string mode) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("Recover" + mode, mode, ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 10, ct); + var old = await PublishDataAsync(client, ct); + DataChanges(old.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good); + fixture.Proof.Invalidate(); + fixture.Proof = new SampleProof(); + fixture.Push(43, completeSnapshot: true).ShouldBeTrue(); + var next = await PublishDataAsync(client, ct); + DataChanges(next.NotificationMessage).ShouldContain(x => x.Handle == 7 && x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43)); + var oldReplay = await client.RepublishAsync(H(), sub, old.NotificationMessage.SequenceNumber, ct); + DataChanges(oldReplay.NotificationMessage).ShouldAllBe(x => x.Value.StatusCode == StatusCodes.BadUserAccessDenied && x.Value.WrappedValue.IsNull); + } + + [Theory(Timeout = 90000)] + [InlineData("None")] + [InlineData("Warm")] + public async Task A_newer_sample_cannot_refresh_an_older_queued_samples_age(string mode) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("Age" + mode, mode, ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 10, ct); + await PublishDataAsync(client, ct); + await client.SetPublishingModeAsync(H(), false, [sub], ct); + fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue(); + await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + fixture.Push(43, originAge: TimeSpan.Zero).ShouldBeTrue(); + await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + await client.SetPublishingModeAsync(H(), true, [sub], ct); + var delivered = await PublishDataAsync(client, ct); + var values = DataChanges(delivered.NotificationMessage); + values.Count.ShouldBeGreaterThanOrEqualTo(2, "both queued samples must reach this delivery for the age check to be meaningful"); + values.ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + var replay = await client.RepublishAsync(H(), sub, delivered.NotificationMessage.SequenceNumber, ct); + DataChanges(replay.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + } + + [Theory(Timeout = 90000)] + [InlineData("None")] + [InlineData("Warm")] + public async Task Ambiguous_equal_samples_are_denied_then_recover_with_a_fresh_snapshot(string mode) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("Equal" + mode, mode, ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 10, ct); + await PublishDataAsync(client, ct); + await client.SetPublishingModeAsync(H(), false, [sub], ct); + fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue(); + await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + fixture.Push(42, originAge: TimeSpan.Zero).ShouldBeTrue(); + await Task.Delay(TimeSpan.FromMilliseconds(150), ct); + await client.SetPublishingModeAsync(H(), true, [sub], ct); + var ambiguous = await PublishDataAsync(client, ct); + DataChanges(ambiguous.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + fixture.Access.BaselineRequests.ShouldBeGreaterThan(0); + fixture.Push(43, completeSnapshot: true).ShouldBeTrue(); + var fresh = await PublishDataAsync(client, ct); + DataChanges(fresh.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43)); + var replay = await client.RepublishAsync(H(), sub, ambiguous.NotificationMessage.SequenceNumber, ct); + DataChanges(replay.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + } + + [Theory(Timeout = 90000)] + [InlineData("None")] + [InlineData("Warm")] + public async Task Single_slot_overwrite_delivers_only_the_fresh_sample(string mode) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("OneSlot" + mode, mode, ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 1, ct); + await PublishDataAsync(client, ct); + await client.SetPublishingModeAsync(H(), false, [sub], ct); + fixture.Push(42, originAge: TimeSpan.FromSeconds(10)).ShouldBeTrue(); + fixture.Push(43, originAge: TimeSpan.Zero).ShouldBeTrue(); + await client.SetPublishingModeAsync(H(), true, [sub], ct); + var delivered = await PublishDataAsync(client, ct); + DataChanges(delivered.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 43)); + DataChanges(delivered.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + } + + [Fact(Timeout = 90000)] + public async Task Candidate_history_capacity_requests_a_new_snapshot_without_unbounded_retention() + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("HistoryCap", "None", ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 10, ct); + await PublishDataAsync(client, ct); + await client.SetPublishingModeAsync(H(), false, [sub], ct); + for (var i = 0; i < 1100; i++) fixture.Push(i + 100).ShouldBeTrue(); + fixture.Access.BaselineRequests.ShouldBeGreaterThan(0); + fixture.Push(2000, completeSnapshot: true).ShouldBeTrue(); + await client.SetPublishingModeAsync(H(), true, [sub], ct); + var fresh = await PublishDataAsync(client, ct); + DataChanges(fresh.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 2000)); + } + + [Theory(Timeout = 90000)] + [InlineData(DataWriteState.DriverConfirmedSuccess)] + [InlineData(DataWriteState.OutcomeUnknown)] + public async Task Mapped_write_returns_rich_remote_outcome_without_optimistic_cache_mutation(DataWriteState state) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("Write" + state, "None", ct, writable: true); + fixture.Access.WriteState = state; + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var result = await client.WriteAsync(H(), [new WriteValue + { + NodeId = node, AttributeId = Attributes.Value, + Value = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good) + }], ct); + fixture.Access.Writes.ShouldBe(1); + if (state == DataWriteState.DriverConfirmedSuccess) result.Results[0].ShouldBe(StatusCodes.Good); + else result.Results[0].ShouldBe(StatusCodes.UncertainLastUsableValue); + var variable = ((Opc.Ua.Server.NodeHandle)fixture.Rig.Nm.GetManagerHandle(node)!).Node.ShouldBeOfType(); + variable.Value.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(1); + } + + [Theory(Timeout = 90000)] + [InlineData("None")] + [InlineData("Warm")] + public async Task Local_secondary_refuses_mapped_write_before_remote_dispatch(string mode) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("WriteStandby" + mode, mode, ct, writable: true, promoteWarm: false); + if (mode == "None") fixture.Rig.Nm.NativeAlarmAckPrimaryGate = () => false; + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var response = await ((SessionClient)session).WriteAsync(H(), [new WriteValue { NodeId = node, AttributeId = Attributes.Value, + Value = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good) }], ct); + response.Results[0].ShouldBe(StatusCodes.BadInvalidState); + fixture.Access.Writes.ShouldBe(0); + } + + [Theory(Timeout = 90000)] + [InlineData(true)] + [InlineData(false)] + public async Task Unsupported_status_or_timestamp_write_never_dispatches(bool customStatus) + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("WriteMetadata" + customStatus, "None", ct, writable: true); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var value = new Opc.Ua.DataValue(new Variant(42), customStatus ? StatusCodes.BadOutOfService : StatusCodes.Good, + customStatus ? DateTimeUtc.MinValue : DateTimeUtc.Now, DateTimeUtc.MinValue); + var response = await ((SessionClient)session).WriteAsync(H(), [new WriteValue { NodeId = node, AttributeId = Attributes.Value, Value = value }], ct); + response.Results[0].ShouldBe(StatusCodes.BadWriteNotSupported); + fixture.Access.Writes.ShouldBe(0); + } + + [Fact(Timeout = 90000)] + public async Task Mixed_write_preserves_legacy_result_and_projected_result_order() + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("MixedWrite", "None", ct, writable: true); + var localId = fixture.Rig.EnsureRawVariable("local-mixed", "Int32", writable: false); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var mapped = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var local = Raw(session, localId); + var response = await ((SessionClient)session).WriteAsync(H(), [ + new WriteValue { NodeId = local, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(7), StatusCodes.Good) }, + new WriteValue { NodeId = mapped, AttributeId = Attributes.Value, Value = new Opc.Ua.DataValue(new Variant(42), StatusCodes.Good) } + ], ct); + StatusCode.IsBad(response.Results[0]).ShouldBeTrue(); + response.Results[1].ShouldBe(StatusCodes.Good); + fixture.Access.Writes.ShouldBe(1); + } + + [Fact(Timeout = 90000)] + public async Task One_dimensional_byte_array_read_and_subscription_preserve_array_type_and_owned_value() + { + var ct = Deadline(); + await using var rig = await StartModeAsync("ProjectedByteArray", "None", ct); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:source", "string", "array"); + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Array"); + var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1); + var metadata = new DataMetadata(view, "Array", "Variable", DataValueKind.Array, 1, [3], false, + DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, DataValueKind.UInt8, serving); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out _).ShouldBeTrue(); + rig.Nm.ProjectedDataAccess = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Array" }, serving); + var source = new byte[] { 1, 2, 3 }; + var sample = new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, new DataValueSnapshot(source, StatusCodes.Good.Code, null, null), + new(TimeSpan.Zero, TimeSpan.Zero), TimeProvider.System.GetTimestamp(), new SampleProof(), IsCompleteSnapshot: true); + ((IProjectedValueSink)rig.Sink).TryPublish([sample]).ShouldBeTrue(); + source[0] = 99; + using var session = await rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var node = new NodeId(identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var read = await client.ReadAsync(H(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = node, AttributeId = Attributes.Value }], ct); + read.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + read.Results[0].WrappedValue.TypeInfo.BuiltInType.ShouldBe(BuiltInType.Byte); + read.Results[0].WrappedValue.TypeInfo.ValueRank.ShouldBe(ValueRanks.OneDimension); + ((byte[])read.Results[0].ClrValue()!).ShouldBe([1, 2, 3]); + var subscription = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + await AddItemAsync(client, subscription, node, 7, 10, ct); + var message = await PublishDataAsync(client, ct); + var delivered = DataChanges(message.NotificationMessage).Single(x => x.Handle == 7).Value; + delivered.StatusCode.ShouldBe(StatusCodes.Good); + delivered.WrappedValue.TypeInfo.BuiltInType.ShouldBe(BuiltInType.Byte); + delivered.WrappedValue.TypeInfo.ValueRank.ShouldBe(ValueRanks.OneDimension); + ((byte[])delivered.ClrValue()!).ShouldBe([1, 2, 3]); + } + + [Fact(Timeout = 90000)] + public async Task Revalidation_keeps_a_live_mapped_item_and_denies_it_after_demand_revocation() + { + var ct = Deadline(); + await using var fixture = await DeliveryFixture.CreateAsync("RevalidateMapped", "None", ct); + using var session = await fixture.Rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(fixture.Identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 10, ct); + await PublishDataAsync(client, ct); + var authority = new DataPlaneAuthorityState(); + fixture.Rig.Nm.Authorizer = new DataPlaneAuthorizer(authority, new TriePermissionEvaluator(authority.Tries), true, NullLogger.Instance); + fixture.Rig.Nm.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny; + fixture.Rig.Nm.RevalidateMonitoredItems(); + fixture.Push(42).ShouldBeTrue(); + var allowed = await PublishDataAsync(client, ct); + DataChanges(allowed.NotificationMessage).ShouldContain(x => x.Value.StatusCode == StatusCodes.Good && Equals(x.Value.ClrValue(), 42)); + fixture.Access.Valid = false; + fixture.Rig.Nm.RevalidateMonitoredItems(); + var denied = await PublishDataAsync(client, ct); + DataChanges(denied.NotificationMessage).ShouldNotContain(x => x.Value.StatusCode == StatusCodes.Good); + } + + [Fact(Timeout = 90000)] + public async Task Removed_mapping_retires_the_original_monitored_item_without_client_deletion() + { + var ct = Deadline(); + await using var rig = await StartModeAsync("MappingRetirement", "None", ct); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:source", "string", "leaf"); + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Leaf"); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "Leaf", "Plant/Leaf", "mapping", 1, () => true); + rig.Nm.TryEnsureProjectedAnchor(anchor, out var anchorId).ShouldBeTrue(); + var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1); + var metadata = new DataMetadata(view, "Leaf", "Variable", DataValueKind.Int32, -1, [], false, + DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, Serving: serving); + ((IProjectedNamespacePageSink)rig.Sink).TryApplyRootLeaf(anchorId!.Value, + new(DataRealm.Raw, identifier, anchorId.Value, metadata, 1, () => true), () => true).ShouldBeTrue(); + var access = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Leaf" }, serving); + rig.Nm.ProjectedDataAccess = access; + ((IProjectedValueSink)rig.Sink).TryPublish([new(DataRealm.Raw, identifier, 1, serving, + new DataValueSnapshot(1, StatusCodes.Good.Code, null, null), new(TimeSpan.Zero, TimeSpan.Zero), + TimeProvider.System.GetTimestamp(), new SampleProof()) { IsCompleteSnapshot = true }]).ShouldBeTrue(); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var client = (SessionClient)session; + var sub = (await client.CreateSubscriptionAsync(H(), 50, 300, 10, 0, true, 0, ct)).SubscriptionId; + var node = new NodeId(identifier, (ushort)session.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + await AddItemAsync(client, sub, node, 7, 10, ct); + await PublishDataAsync(client, ct); + rig.Nm.TryRemoveProjectedAnchor(anchorId.Value, anchor).ShouldBeTrue(); + access.Disposals.ShouldBeGreaterThan(0, "node removal must retire the item even while the client keeps it alive"); + } + + private sealed class DeliveryFixture(ServerEventRig rig, string identifier, ServingIdentity serving, FakeAccess access) : IAsyncDisposable + { + public ServerEventRig Rig => rig; + public string Identifier => identifier; + public FakeAccess Access => access; + public SampleProof Proof = new(); + public bool Push(int value, bool completeSnapshot = false, TimeSpan? originAge = null) => ((IProjectedValueSink)rig.Sink).TryPublish([ + new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, new DataValueSnapshot(value, StatusCodes.Good.Code, null, null), + new(originAge ?? TimeSpan.Zero, originAge ?? TimeSpan.Zero), TimeProvider.System.GetTimestamp(), Proof) { IsCompleteSnapshot = completeSnapshot } + ]); + public static async Task CreateAsync(string name, string mode, CancellationToken ct, bool writable = false, bool promoteWarm = true) + { + var rig = await StartModeAsync(name, mode, ct); + if (mode == "Warm" && promoteWarm) Promote(rig.Server.CreateStandbyProjection()!); + rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:source", "string", "speed"); + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Speed"); + var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1); + var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], writable, + DataOperations.Read | DataOperations.Subscribe | (writable ? DataOperations.Write : DataOperations.None), 1, null, null, false, Serving: serving); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out _).ShouldBeTrue(); + var access = new FakeAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" }, serving); + rig.Nm.ProjectedDataAccess = access; + var fixture = new DeliveryFixture(rig, identifier, serving, access); + fixture.Push(1, completeSnapshot: true).ShouldBeTrue(); + return fixture; + } + public ValueTask DisposeAsync() => rig.DisposeAsync(); + } + + private sealed class SampleProof : IProjectedSamplePublicationProof + { + public bool IsValid { get; private set; } = true; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => IsValid = false; + } + private sealed class FakeAccess(DataView origin, ServingIdentity serving) : IProjectedDataAccess + { + public bool Valid = true; + public int BaselineRequests; + public int Disposals; + public int Writes; + public DataWriteState WriteState = DataWriteState.DriverConfirmedSuccess; + public bool RequestFreshSnapshot(IProjectedDemandLease demand) { Interlocked.Increment(ref BaselineRequests); return true; } + public TimeProvider Clock => TimeProvider.System; + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) + { demand = new Demand(this, origin, serving, nodeId.IdentifierAsString); return Valid; } + public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) { demand.Dispose(); return true; } + public Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) + { Interlocked.Increment(ref Writes); return Task.FromResult(new DataWriteOutcome(WriteState, WriteState == DataWriteState.DriverConfirmedSuccess ? StatusCodes.Good.Code : StatusCodes.UncertainLastUsableValue.Code, null)); } + public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => true; + } + private sealed class Demand(FakeAccess owner, DataView view, ServingIdentity serving, string id) : IProjectedDemandLease + { + private bool _disposed; + public DataView OriginView => view; + public DataRealm Realm => view.Realm; + public string LocalIdentifier => id; + public long ProjectionGeneration => 1; + public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5); + public ServingIdentity Serving => serving; + public CancellationToken CancellationToken => CancellationToken.None; + public bool IsValid => !_disposed && owner.Valid; + public void Dispose() { if (!_disposed) { _disposed = true; Interlocked.Increment(ref owner.Disposals); } } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataCandidateBudgetTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataCandidateBudgetTests.cs new file mode 100644 index 000000000..befc4beb9 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataCandidateBudgetTests.cs @@ -0,0 +1,37 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataCandidateBudgetTests +{ + [Fact] + public void Aggregate_pressure_rejects_a_second_item_until_the_first_releases_its_charge() + { + var budget = new ProjectedCandidateBudget(maxEntries: 2, maxBytes: 512); + budget.TryReserve(384, out var firstItem).ShouldBeTrue(); + budget.TryReserve(256, out var blockedSecondItem).ShouldBeFalse(); + blockedSecondItem.ShouldBeNull(); + budget.RetainedBytes.ShouldBe(384); + budget.RetainedEntries.ShouldBe(1); + firstItem!.Dispose(); + firstItem.Dispose(); + budget.RetainedBytes.ShouldBe(0); + budget.RetainedEntries.ShouldBe(0); + budget.TryReserve(256, out var secondItem).ShouldBeTrue(); + secondItem!.Dispose(); + budget.RetainedBytes.ShouldBe(0); + } + + [Fact] + public void Entry_limit_is_shared_even_for_small_values() + { + var budget = new ProjectedCandidateBudget(maxEntries: 1, maxBytes: 4096); + budget.TryReserve(1, out var first).ShouldBeTrue(); + budget.TryReserve(1, out _).ShouldBeFalse(); + first!.Dispose(); + budget.TryReserve(1, out var next).ShouldBeTrue(); + next!.Dispose(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedSubjectTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedSubjectTests.cs index cf23b0324..18420eb75 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedSubjectTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataMappedSubjectTests.cs @@ -113,6 +113,17 @@ public sealed class GrpcDataMappedSubjectTests : IDisposable finally { await host.DisposeAsync(); } } + [Fact] + public void Mapped_classifier_uses_the_actual_namespace_not_a_local_identifier_that_looks_opaque() + { + var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read); + f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny; + f.Gate.MappedNamespacePredicate = id => id.NamespaceIndex == 3; + var sameIdentifier = "p1.canonical-looking"; + f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.Read, new NodeId(sameIdentifier, 2), AddressSpaceRealm.Raw).ShouldBeNull(); + f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.Read, new NodeId(sameIdentifier, 3), AddressSpaceRealm.Raw).ShouldNotBeNull(); + } + [Fact] public void Cached_allow_rechecks_original_key_version_principal_and_expiry() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataProjectedNodeLifetimeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataProjectedNodeLifetimeTests.cs new file mode 100644 index 000000000..9c1069139 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataProjectedNodeLifetimeTests.cs @@ -0,0 +1,39 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataProjectedNodeLifetimeTests +{ + [Fact] + public void Active_pin_blocks_idle_retirement_and_forced_retirement_invalidates_it() + { + var lifetime = new ProjectedNodeLifetime(); + lifetime.TryPin(out var pin).ShouldBeTrue(); + pin.ShouldNotBeNull(); + lifetime.TryRetire().ShouldBeFalse(); + pin.IsValid.ShouldBeTrue(); + lifetime.ForceRetire(); + pin.IsValid.ShouldBeFalse(); + lifetime.TryPin(out _).ShouldBeFalse(); + pin.Dispose(); + } + + [Fact(Timeout = 15000)] + public async Task Concurrent_acquisition_and_idle_prune_have_only_one_winner() + { + for (var i = 0; i < 64; i++) + { + var lifetime = new ProjectedNodeLifetime(); + using var start = new Barrier(2); + var acquire = Task.Run(() => { start.SignalAndWait(); return lifetime.TryPin(out var pin) ? pin : null; }, TestContext.Current.CancellationToken); + var retire = Task.Run(() => { start.SignalAndWait(); return lifetime.TryRetire(); }, TestContext.Current.CancellationToken); + var pin = await acquire.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var retired = await retire.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + (pin is not null).ShouldBe(!retired); + if (pin is not null) { pin.IsValid.ShouldBeTrue(); pin.Dispose(); lifetime.TryRetire().ShouldBeTrue(); } + lifetime.TryPin(out _).ShouldBeFalse(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkBrowseReadinessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkBrowseReadinessTests.cs new file mode 100644 index 000000000..258a2540c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkBrowseReadinessTests.cs @@ -0,0 +1,103 @@ +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.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkBrowseReadinessTests : IDisposable +{ + private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projected-browse-{Guid.NewGuid():N}"); + + [Theory] + [InlineData(ProjectedBrowseReadiness.Pending)] + [InlineData(ProjectedBrowseReadiness.Unavailable)] + public async Task Actual_sdk_browse_reports_the_selected_parents_state_even_when_acl_is_off(ProjectedBrowseReadiness state) + { + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ProjectedBrowse", ApplicationUri = $"urn:ProjectedBrowse:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + manager.EnsureFolder("Plant/Mount", "Plant", "Mount", AddressSpaceRealm.Raw); + manager.EnsureFolder("Plant/Local", "Plant", "Local", AddressSpaceRealm.Raw); + var localParent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var parent = manager.TryGetFolder("Plant/Mount", AddressSpaceRealm.Raw)!.NodeId; + manager.ProjectedBrowseReadiness = id => id == parent ? state : ProjectedBrowseReadiness.Ready; + var localPoint = new ContinuationPoint { NodeToBrowse = manager.GetManagerHandle(localParent)!, BrowseDirection = BrowseDirection.Forward, + IncludeSubtypes = true, ResultMask = BrowseResultMask.All }; + var localReferences = new List(); + var context = new OperationContext(new RequestHeader(), null, RequestType.Browse, RequestLifetime.None, (IUserIdentity?)null); + manager.Browse(context, ref localPoint, localReferences); + localReferences.Select(r => r.DisplayName.Text).ShouldContain("Local"); + localReferences.Select(r => r.DisplayName.Text).ShouldContain("Mount"); + localPoint?.Dispose(); + var point = new ContinuationPoint { NodeToBrowse = manager.GetManagerHandle(parent)!, BrowseDirection = BrowseDirection.Forward, + IncludeSubtypes = true, ResultMask = BrowseResultMask.All }; + try + { + var originalPoint = point; + var error = Should.Throw(() => manager.Browse(context, ref point, new List())); + error.StatusCode.Code.ShouldBe(state == ProjectedBrowseReadiness.Pending + ? StatusCodes.BadWaitingForInitialData.Code : StatusCodes.BadNoCommunication.Code); + point.ShouldBeSameAs(originalPoint); + } + finally { point?.Dispose(); } + } + finally { await started.Host.DisposeAsync(); } + } + + [Fact] + public async Task Browse_passes_the_original_caller_and_continuation_to_the_nonblocking_projection_scheduler() + { + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ProjectedBrowseIdentity", ApplicationUri = $"urn:ProjectedBrowseIdentity:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Mount", null, "Mount", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Mount", AddressSpaceRealm.Raw)!.NodeId; + var access = new BrowseAccess(); + manager.ProjectedBrowseAccess = access; + var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "version", null); + var context = new OperationContext(new RequestHeader(), null, RequestType.Browse, RequestLifetime.None, identity); + var point = new ContinuationPoint { NodeToBrowse = manager.GetManagerHandle(parent)!, BrowseDirection = BrowseDirection.Forward, + IncludeSubtypes = true, ResultMask = BrowseResultMask.All }; + try + { + var original = point; + Should.Throw(() => manager.Browse(context, ref point, new List())); + access.Last.ShouldNotBeNull(); + access.Last.Parent.ShouldBe(parent); + access.Last.Caller.ShouldBeSameAs(identity); + access.Last.Continuation.ShouldBeSameAs(original); + point.ShouldBeSameAs(original); + } + finally { point?.Dispose(); } + } + finally { await started.Host.DisposeAsync(); } + } + + private sealed class BrowseAccess : IProjectedBrowseAccess + { + public ProjectedBrowseContext? Last; + public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) + { Last = context; return ProjectedBrowseReadiness.Pending; } + } + + public void Dispose() + { + if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkContinuationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkContinuationTests.cs new file mode 100644 index 000000000..e063e080e --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkContinuationTests.cs @@ -0,0 +1,33 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkContinuationTests +{ + [Fact] + public void Cursor_is_bound_to_original_session_caller_and_parent_and_only_advances_after_commit() + { + var parent = new NodeId("parent", 2); + var firstSession = new NodeId("session-a", 1); + var secondSession = new NodeId("session-b", 1); + var caller = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "v1", null); + var otherKey = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "v2", null); + using var state = new ProjectedBrowseContinuation(parent, firstSession, caller, "cursor-1"); + state.TryGetCursor(parent, firstSession, caller, out var original).ShouldBeTrue(); + original.ShouldBe("cursor-1"); + state.TryGetCursor(parent, secondSession, caller, out _).ShouldBeFalse(); + state.TryGetCursor(parent, firstSession, otherKey, out _).ShouldBeFalse(); + state.TryGetCursor(new NodeId("other", 2), firstSession, caller, out _).ShouldBeFalse(); + state.TryAdvance("cursor-1", "cursor-2", () => false).ShouldBeFalse(); + state.TryGetCursor(parent, firstSession, caller, out var stillOriginal).ShouldBeTrue(); + stillOriginal.ShouldBe("cursor-1"); + state.TryAdvance("cursor-1", "cursor-2", () => true).ShouldBeTrue(); + state.TryAdvance("cursor-1", "cursor-3", () => true).ShouldBeFalse(); + state.TryGetCursor(parent, firstSession, caller, out var next).ShouldBeTrue(); + next.ShouldBe("cursor-2"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs new file mode 100644 index 000000000..10346b7ae --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkHierarchyTests.cs @@ -0,0 +1,142 @@ +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("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkHierarchyTests : IDisposable +{ + private readonly string _pki = Path.Combine(Path.GetTempPath(), $"projection-hierarchy-{Guid.NewGuid():N}"); + [Theory] + [InlineData(DataRealm.Raw, AddressSpaceRealm.Raw)] + [InlineData(DataRealm.Uns, AddressSpaceRealm.Uns)] + public async Task Folder_hierarchy_and_one_dimensional_variable_preserve_parent_and_shape(DataRealm realm, AddressSpaceRealm localRealm) + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Local", null, "Local", localRealm); + var parent = manager.TryGetFolder("Local", localRealm)!.NodeId; + var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager); + foreach (var name in new[] { "Folder", "Driver", "Device", "Group" }) + { + var definition = Definition(realm, parent, name, "Folder", DataValueKind.Null, -1, [], null); + sink.TryApply(parent, [definition], () => true).ShouldBeTrue(); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), definition.LocalIdentifier, out var next).ShouldBeTrue(); + parent = next!.Value; + var folder = ((NodeHandle)manager.GetManagerHandle(parent)!).Node; + folder.ShouldBeOfType(); + } + var array = Definition(realm, parent, "Tag", "Variable", DataValueKind.Array, 1, [3], DataValueKind.Int32); + sink.TryApply(parent, [array], () => true).ShouldBeTrue(); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), array.LocalIdentifier, out var tag).ShouldBeTrue(); + var variable = ((NodeHandle)manager.GetManagerHandle(tag!.Value)!).Node.ShouldBeOfType(); + variable.ValueRank.ShouldBe(ValueRanks.OneDimension); + variable.ArrayDimensions.ToArray()!.ShouldBe([3u]); + } + finally { await started.Host.DisposeAsync(); } + } + + [Fact] + public async Task Root_leaf_promotion_is_atomic_and_keeps_anchor_node_and_local_name() + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:raw", "string", "leaf-root"); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "ConfiguredBranch", "Plant/ConfiguredBranch", "mapping", 1, () => true); + manager.TryEnsureProjectedAnchor(anchor, out var id).ShouldBeTrue(); + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/ConfiguredBranch"); + var metadata = new DataMetadata(view, "OriginName", "Variable", DataValueKind.Int32, -1, [], false, + DataOperations.Browse | DataOperations.Read, 1, null, null, false); + var definition = new ProjectedVariableDefinition(DataRealm.Raw, identifier, parent, metadata, 1, () => true); + var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager); + sink.TryApplyRootLeaf(id!.Value, definition, () => false).ShouldBeFalse(); + ((NodeHandle)manager.GetManagerHandle(id.Value)!).Node.ShouldBeOfType(); + sink.TryApplyRootLeaf(id.Value, definition with { Parent = id.Value }, () => true).ShouldBeTrue(); + var node = ((NodeHandle)manager.GetManagerHandle(id.Value)!).Node.ShouldBeOfType(); + node.NodeId.ShouldBe(id.Value); + node.DisplayName.Text.ShouldBe("ConfiguredBranch"); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var resolved).ShouldBeTrue(); + resolved!.Metadata.BrowseName.ShouldBe("OriginName"); + resolved.Parent.ShouldBe(parent); + var oldGuard = resolved.AuthorityIsCurrent; + var refreshed = definition with { Parent = id.Value, AuthorityIsCurrent = () => true }; + sink.TryApplyRootLeaf(id.Value, refreshed, () => false).ShouldBeFalse(); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var afterAbort).ShouldBeTrue(); + afterAbort.ShouldBeSameAs(resolved); + sink.TryApplyRootLeaf(id.Value, refreshed, () => true).ShouldBeTrue(); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var renewed).ShouldBeTrue(); + renewed!.Parent.ShouldBe(parent); + renewed.Lifetime.ShouldBeSameAs(resolved.Lifetime); + renewed.AuthorityIsCurrent.ShouldNotBeSameAs(oldGuard); + ((NodeHandle)manager.GetManagerHandle(id.Value)!).Node.ShouldBeSameAs(node); + } + finally { await started.Host.DisposeAsync(); } + } + + [Fact] + public async Task Removed_root_leaf_remains_charged_until_its_physical_pin_drains() + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.ConfigureProjectedNodeLimits(maxNodes: 4, maxBytes: 3000); + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var origin = new DataAddress("origin", "urn:raw", "string", "leaf-root"); + var identifier = ProjectedDataIds.Identifier("mapping", origin); + var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, identifier, parent, "Branch", "Plant/Branch", "mapping", 1, () => true); + manager.TryEnsureProjectedAnchor(anchor, out var id).ShouldBeTrue(); + var metadata = new DataMetadata(new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Branch"), "Leaf", "Variable", + DataValueKind.Int32, -1, [], false, DataOperations.Browse | DataOperations.Read, 1, null, null, false); + var definition = new ProjectedVariableDefinition(DataRealm.Raw, identifier, id!.Value, metadata, 1, () => true); + var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager); + sink.TryApplyRootLeaf(id.Value, definition, () => true).ShouldBeTrue(); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(id.Value, out var installed).ShouldBeTrue(); + installed!.Lifetime.TryPin(out var physicalPin).ShouldBeTrue(); + manager.TryRemoveProjectedAnchor(id.Value, anchor).ShouldBeTrue(); + physicalPin!.IsValid.ShouldBeFalse(); + var otherOrigin = new DataAddress("origin", "urn:raw", "string", "other-root"); + var other = new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("other", otherOrigin), parent, + "Other", "Plant/Other", "other", 1, () => true); + manager.TryEnsureProjectedAnchor(other, out _).ShouldBeFalse(); + using var drained = new ManualResetEventSlim(); + var lockRace = other with { AuthorityIsCurrent = () => + { + _ = Task.Run(() => { physicalPin.Dispose(); drained.Set(); }); + return drained.Wait(TimeSpan.FromSeconds(2)); + } }; + manager.TryEnsureProjectedAnchor(lockRace, out _).ShouldBeTrue("pin disposal must not wait for the SDK lock"); + } + finally { await started.Host.DisposeAsync(); } + } + + private static ProjectedVariableDefinition Definition(DataRealm realm, NodeId parent, string name, string kind, + DataValueKind valueKind, int rank, IReadOnlyList dimensions, DataValueKind? elementKind) + { + var origin = new DataAddress("origin", "urn:raw", "string", name); + var view = new DataView(origin, realm, "mapping", 1, "Local/" + name); + var metadata = new DataMetadata(view, name, kind, valueKind, rank, dimensions, false, DataOperations.Browse | DataOperations.Read, + 1, null, null, false, elementKind); + return new(realm, ProjectedDataIds.Identifier("mapping", origin), parent, metadata, 1, () => true); + } + private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> StartAsync() => + await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ProjectionHierarchy", ApplicationUri = $"urn:ProjectionHierarchy:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + public void Dispose() { if (Directory.Exists(_pki)) try { Directory.Delete(_pki, true); } catch (IOException) { } } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs new file mode 100644 index 000000000..552d15b95 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkMappedAccessTests.cs @@ -0,0 +1,45 @@ +using Opc.Ua; +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkMappedAccessTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Queued_value_is_denied_after_its_original_proof_is_revoked_on_publish_and_republish(bool republish) + { + var valid = true; + var value = new DataValue(new Variant(42), StatusCodes.Good); + var item = new MonitoredItemNotification { ClientHandle = 7, Value = value }; + item.Message = new ProjectedNotificationMarker(7, value, () => valid); + var message = Message(item); + valid = false; + var output = ProjectedNotificationRewriter.Project(message, republish); + output.NotificationData[0].TryGetValue(out var data).ShouldBeTrue(); + data!.MonitoredItems[0].Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + item.Value.StatusCode.ShouldBe(StatusCodes.Good); + } + + [Fact] + public void A_reused_handle_does_not_turn_an_old_item_proof_into_a_new_authorization() + { + var oldValue = new DataValue(new Variant(42), StatusCodes.Good); + var newValue = new DataValue(new Variant(43), StatusCodes.Good); + var item = new MonitoredItemNotification { ClientHandle = 7, Value = newValue }; + item.Message = new ProjectedNotificationMarker(7, oldValue, () => true); + var output = ProjectedNotificationRewriter.Project(Message(item), false); + output.NotificationData[0].TryGetValue(out var data).ShouldBeTrue(); + data!.MonitoredItems[0].Value.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied); + } + + private static NotificationMessage Message(MonitoredItemNotification item) => new() + { + SequenceNumber = 1, + PublishTime = DateTimeUtc.Now, + NotificationData = new List { new(new DataChangeNotification { MonitoredItems = [item] }) }, + }; +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs new file mode 100644 index 000000000..aec3846ee --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionLifetimeTests.cs @@ -0,0 +1,120 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkProjectionLifetimeTests : IDisposable +{ + private readonly string _pki = Path.Combine(Path.GetTempPath(), $"projection-lifetime-{Guid.NewGuid():N}"); + + [Fact] + public async Task Cumulative_limit_reclaims_only_expired_nodes_without_live_demand() + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.ConfigureProjectedNodeLimits(maxNodes: 1, maxBytes: 4096); + var demand = new DemandStatus(); + manager.ProjectedDataAccess = demand; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var live = true; + var first = Definition(parent, "first", () => live); + var second = Definition(parent, "second", () => true); + manager.TryEnsureProjectedVariable(first, out var oldId).ShouldBeTrue(); + manager.TryEnsureProjectedVariable(second, out _).ShouldBeFalse(); + first.Lifetime.TryPin(out var pin).ShouldBeTrue(); + live = false; + manager.TryEnsureProjectedVariable(second, out _).ShouldBeFalse("expired nodes with live physical demand remain charged"); + pin!.Dispose(); + manager.TryEnsureProjectedVariable(second, out _).ShouldBeTrue(); + ((IProjectedNodeLookup)new SdkAddressSpaceSink(manager)).TryResolve(oldId!.Value, out _).ShouldBeFalse(); + } + finally { await started.Host.DisposeAsync(); } + } + + [Fact] + public async Task Retained_authority_is_charged_against_the_node_byte_limit() + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.ConfigureProjectedNodeLimits(maxNodes: 2, maxBytes: 4096); + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var large = new RetainedGuard(4096); + var small = new RetainedGuard(1); + manager.TryEnsureProjectedVariable(Definition(parent, "large", large.IsCurrent), out _).ShouldBeFalse(); + manager.TryEnsureProjectedVariable(Definition(parent, "small", small.IsCurrent), out _).ShouldBeTrue(); + } + finally { await started.Host.DisposeAsync(); } + } + + [Fact] + public async Task Same_placement_renewal_commits_a_fresh_guard_without_resurrecting_the_old_one() + { + var started = await StartAsync(); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var oldValid = true; + var oldDefinition = Definition(parent, "same", () => oldValid); + var sink = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager); + sink.TryApply(parent, [oldDefinition], () => true).ShouldBeTrue(); + var id = new NodeId(oldDefinition.LocalIdentifier, + (ushort)started.Server.CurrentInstance.NamespaceUris.GetIndex(ProjectedDataIds.RawNamespaceUri)); + var lookup = (IProjectedNodeLookup)new SdkAddressSpaceSink(manager); + lookup.TryResolve(id, out var original).ShouldBeTrue(); + var replacement = oldDefinition with { Metadata = oldDefinition.Metadata with { Dimensions = Array.Empty() }, AuthorityIsCurrent = () => true }; + sink.TryApply(parent, [replacement], () => false).ShouldBeFalse(); + lookup.TryResolve(id, out var afterAbort).ShouldBeTrue(); + afterAbort.ShouldBeSameAs(original); + oldValid = false; + sink.TryApply(parent, [replacement], () => true).ShouldBeTrue(); + lookup.TryResolve(id, out var afterCommit).ShouldBeTrue(); + afterCommit.ShouldBeSameAs(replacement); + original!.AuthorityIsCurrent().ShouldBeFalse(); + manager.GetManagerHandle(id).ShouldNotBeNull(); + } + finally { await started.Host.DisposeAsync(); } + } + + private static ProjectedVariableDefinition Definition(NodeId parent, string name, Func guard) + { + var origin = new DataAddress("origin", "urn:raw", "string", name); + var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/" + name); + var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Read, 1, null, null, false); + return new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent, metadata, 1, guard); + } + private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> StartAsync() => + await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ProjectionLifetime", ApplicationUri = $"urn:ProjectionLifetime:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + private sealed class RetainedGuard(long retainedBytes) : IProjectedRetainedAuthority + { + public long RetainedBytes => retainedBytes; + public bool IsCurrent() => true; + } + private sealed class DemandStatus : IProjectedDataAccess + { + public TimeProvider Clock => TimeProvider.System; + public bool HasLiveDemand(DataRealm realm, string localIdentifier) => false; + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { demand = null; return false; } + public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) => false; + public Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException(); + public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => false; + } + public void Dispose() { if (Directory.Exists(_pki)) try { Directory.Delete(_pki, true); } catch (IOException) { } } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs new file mode 100644 index 000000000..93fe84da3 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/GrpcDataSdkProjectionTests.cs @@ -0,0 +1,163 @@ +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; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataSdkProjectionTests : IDisposable +{ + private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-projection-{Guid.NewGuid():N}"); + + [Fact] + public async Task Materialization_requires_the_exact_parent_and_rejects_unsupported_shape() + { + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ProjectedNode", ApplicationUri = $"urn:ProjectedNode:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + try + { + var manager = started.Server.NodeManager!; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = manager.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var anchorOrigin = new DataAddress("origin", "urn:source", "string", "root"); + var anchorIdentifier = ProjectedDataIds.Identifier("mapping", anchorOrigin); + var anchorDefinition = new ProjectedAnchorDefinition(DataRealm.Raw, anchorIdentifier, parent, "Mount", "Plant/Mount", "mapping", 1, () => true); + manager.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); + anchor.ShouldNotBeNull(); + var missingAnchorParent = new NodeId("does-not-exist", parent.NamespaceIndex); + manager.TryEnsureProjectedAnchor(anchorDefinition with { Parent = missingAnchorParent }, out _).ShouldBeFalse(); + var anchorSink = (IProjectedAnchorSink)new SdkAddressSpaceSink(manager); + anchorSink.TryRemoveProjectedAnchor(anchor.Value, anchorDefinition).ShouldBeTrue(); + var replacementAnchor = anchorDefinition with { Lifetime = new ProjectedNodeLifetime() }; + anchorSink.TryEnsureProjectedAnchor(replacementAnchor, out var sameAnchorId).ShouldBeTrue(); + sameAnchorId.ShouldBe(anchor); + anchorSink.TryRemoveProjectedAnchor(anchor.Value, anchorDefinition).ShouldBeFalse(); + var origin = new DataAddress("origin", "urn:source", "string", "Device/Speed"); + var view = new DataView(origin, DataRealm.Raw, "map", 1, "Plant/Speed"); + var metadata = new DataMetadata(view, "Speed", "Tag", DataValueKind.Int32, -1, [], false, + DataOperations.Browse | DataOperations.Read, 1, null, null, false); + var identifier = ProjectedDataIds.Identifier("map", origin); + var missingParent = new NodeId("missing", parent.NamespaceIndex); + manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, missingParent, metadata, 1, () => true), out _).ShouldBeFalse(); + manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata with { ValueKind = DataValueKind.Array, ArrayElementKind = DataValueKind.Int32, ValueRank = 2, Dimensions = [2, 2] }, 1, () => true), out _).ShouldBeFalse(); + manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, parent, metadata, 1, () => true), out var node).ShouldBeTrue(); + node.ShouldNotBeNull(); + started.Server.CurrentInstance.NamespaceUris.GetString(node.Value.NamespaceIndex).ShouldBe(ProjectedDataIds.RawNamespaceUri); + manager.EnsureVariable(identifier, "Plant", "LocalCollision", "Int32", false, AddressSpaceRealm.Raw); + var localCollision = manager.TryGetVariable(identifier, AddressSpaceRealm.Raw)!.NodeId; + var readContext = new OperationContext(new RequestHeader(), null, RequestType.Read, RequestLifetime.None, (IUserIdentity?)null); + var reads = new List { new() { NodeId = localCollision, AttributeId = Attributes.Value }, new() { NodeId = node.Value, AttributeId = Attributes.Value } }; + var readValues = new List { new(), new() }; + var readErrors = new List { null!, null! }; + manager.Read(readContext, 0, reads, readValues, readErrors); + readErrors[0]?.StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code); + readErrors[1].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + var access = new ReadOnlyAccess(view with { MappingId = null, MappingRevision = 0, Subject = "origin/Speed" }); + manager.ProjectedDataAccess = access; + var caller = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "reader" }, [], "reader", "key", "version", null); + var callerContext = new OperationContext(new RequestHeader(), null, RequestType.Read, RequestLifetime.None, caller); + var projectedRead = new List { new() { NodeId = node.Value, AttributeId = Attributes.Value } }; + var projectedValues = new List { new() }; + var projectedErrors = new List { null! }; + manager.Read(callerContext, 0, projectedRead, projectedValues, projectedErrors); + access.LastOperation.ShouldBe(DataOperations.Read); + access.ReadSchedules.ShouldBe(1); + projectedValues[0].StatusCode.ShouldBe(StatusCodes.BadWaitingForInitialData); + manager.TryEnsureProjectedVariable(new(DataRealm.Raw, identifier, missingParent, metadata, 1, () => true), out _).ShouldBeFalse(); + + var otherOrigin = origin with { Identifier = "Device/Temperature" }; + var otherId = ProjectedDataIds.Identifier("map", otherOrigin); + var otherMetadata = metadata with { View = view with { Address = otherOrigin, Subject = "Plant/Temperature" }, BrowseName = "Temperature" }; + var definition = new ProjectedVariableDefinition(DataRealm.Raw, otherId, parent, otherMetadata, 1, () => true); + var deferred = new DeferredAddressSpaceSink(); + var pageSink = new DeferredProjectedNamespacePageSink(deferred); + pageSink.TryApply(parent, [definition], () => true).ShouldBeFalse(); + deferred.SetSink(new SdkAddressSpaceSink(manager)); + var pageNode = new NodeId(otherId, node.Value.NamespaceIndex); + pageSink.TryApply(parent, [definition], () => false).ShouldBeFalse(); + manager.GetManagerHandle(pageNode).ShouldBeNull("an aborted cursor must roll back all new SDK nodes"); + var commits = 0; + pageSink.TryApply(parent, [definition], () => { commits++; return true; }).ShouldBeTrue(); + commits.ShouldBe(1); + manager.GetManagerHandle(pageNode).ShouldNotBeNull(); + var lookup = (IProjectedNodeLookup)new SdkAddressSpaceSink(manager); + lookup.TryGetNodeId(ProjectedDataIds.RawNamespaceUri, otherId, out var translated).ShouldBeTrue(); + translated.ShouldBe(pageNode); + lookup.TryResolve(pageNode, out var originalDefinition).ShouldBeTrue(); + var removable = (IProjectedNamespacePageSink)new SdkAddressSpaceSink(manager); + removable.TryRemove(pageNode, originalDefinition!).ShouldBeTrue(); + lookup.TryResolve(pageNode, out _).ShouldBeFalse(); + var replacementDefinition = definition with { Lifetime = new ProjectedNodeLifetime() }; + removable.TryApply(parent, [replacementDefinition], () => true).ShouldBeTrue(); + lookup.TryResolve(pageNode, out var currentDefinition).ShouldBeTrue(); + currentDefinition.ShouldNotBeSameAs(originalDefinition); + removable.TryRemove(pageNode, originalDefinition!).ShouldBeFalse(); + deferred.SetSink(null); + pageSink.TryApply(parent, [definition], () => true).ShouldBeFalse(); + + var proof = new SampleProof(); + var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1); + var update = new ProjectedValueWrite(DataRealm.Raw, identifier, 1, serving, + new DataValueSnapshot(42, StatusCodes.Good.Code, null, null), new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)), + TimeProvider.System.GetTimestamp(), proof); + var sink = (IProjectedValueSink)new SdkAddressSpaceSink(manager); + sink.TryPublish([update]).ShouldBeTrue(); + var variable = ((NodeHandle)manager.GetManagerHandle(node.Value)!).Node.ShouldBeOfType(); + variable.StatusCode.ShouldBe(StatusCodes.Good); + proof.Invalidate(); + sink.TryPublish([update]).ShouldBeFalse(); + StatusCode.IsBad(variable.StatusCode).ShouldBeTrue("a rejected stale sample must not leave a Good value visible"); + lookup.TryResolve(pageNode, out _).ShouldBeTrue(); + manager.RebuildAddressSpace(); + lookup.TryResolve(pageNode, out _).ShouldBeFalse("a rebuilt address space must retire old projected identities"); + manager.GetManagerHandle(pageNode).ShouldBeNull(); + } + finally { await started.Host.DisposeAsync(); } + } + + private sealed class ReadOnlyAccess(DataView view) : IProjectedDataAccess + { + public TimeProvider Clock => TimeProvider.System; + public DataOperations LastOperation; + public int ReadSchedules; + public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) + { LastOperation = operation; demand = new ReadDemand(view); return operation == DataOperations.Read; } + public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) { ReadSchedules++; return true; } + public Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException(); + public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => throw new InvalidOperationException("A read must not require subscribe permission."); + } + private sealed class ReadDemand(DataView view) : IProjectedDemandLease + { + public DataView OriginView => view; + public DataRealm Realm => view.Realm; + public string LocalIdentifier => "unused"; + public long ProjectionGeneration => 1; + public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5); + public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1); + public CancellationToken CancellationToken => CancellationToken.None; + public bool IsValid => true; + public void Dispose() { } + } + + private sealed class SampleProof : IProjectedSamplePublicationProof + { + private bool _valid = true; + public bool IsValid => _valid; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => _valid = false; + } + + public void Dispose() + { + if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs new file mode 100644 index 000000000..f4c151bc0 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataAdapterLifecycleTests.cs @@ -0,0 +1,205 @@ +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Shouldly; +using Xunit; +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; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataAdapterLifecycleTests +{ + private static readonly ServingIdentity Serving = new("remote", "boot", "Primary", 3, 4, 1); + private static readonly DataView View = new(new("remote-cluster", "urn:raw", "string", "Device/Speed"), DataRealm.Raw, null, 0, "Device/Speed"); + private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], true, + DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, 3, null, null, false); + private static readonly string Ref = ProjectedDataIds.DependencyReference(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", View.Address)); + private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)); + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task Unknown_remote_write_is_not_replayed_or_published_as_a_value() + { + var source = new FakeConnectionSource(); + var routes = new FakeRoutes(); + var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, routes); + var publications = 0; + adapter.OnDataChange += (_, _) => Interlocked.Increment(ref publications); + await adapter.InitializeAsync("{}", Ct); + var outcomes = await adapter.WriteWithOutcomesAsync([new WriteRequest(Ref, 42)], Ct); + outcomes.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.OutcomeUnknown); + source.Connection.WriteCount.ShouldBe(1); + publications.ShouldBe(0); + await adapter.ShutdownAsync(Ct); + } + + [Fact] + public async Task Stream_lease_is_retained_until_actual_stream_disposal_completes() + { + var source = new FakeConnectionSource(); + var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, new FakeRoutes()); + await adapter.InitializeAsync("{}", Ct); +#pragma warning disable OTOPCUA0001 // This test exercises the adapter lifetime directly. + var handle = await adapter.SubscribeAsync([Ref], TimeSpan.FromSeconds(1), Ct); + var closing = adapter.UnsubscribeAsync(handle, Ct); +#pragma warning restore OTOPCUA0001 + try + { + await source.Connection.Stream.DisposeEntered.Task.WaitAsync(Ct); + source.LastLease.ShouldNotBeNull(); + source.LastLease.Disposed.ShouldBeFalse(); + } + finally { source.Connection.Stream.ReleaseDispose.TrySetResult(); } + await closing.WaitAsync(Ct); + source.LastLease!.Disposed.ShouldBeTrue(); + await adapter.ShutdownAsync(Ct); + } + + [Theory(Timeout = 15000)] + [InlineData(false)] + [InlineData(true)] + public async Task Initial_snapshot_is_atomic_and_typed_publication_keeps_origin_age(bool rejectPublication) + { + var source = new FakeConnectionSource(); + source.Connection.Stream.HoldSnapshotEnd = true; + var publisher = new FakePublisher { Reject = rejectPublication }; + var adapter = new GrpcDataDriverAdapter("mapped-driver", "connection", source, new FakeRoutes(), publisher); + await adapter.InitializeAsync("{}", Ct); +#pragma warning disable OTOPCUA0001 // Exercise the adapter's stream lifetime directly. + var handle = await adapter.SubscribeAsync([Ref], TimeSpan.FromSeconds(1), Ct); +#pragma warning restore OTOPCUA0001 + try + { + await source.Connection.Stream.SnapshotValueConsumed.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct); + publisher.Updates.ShouldBeEmpty(); + source.Connection.Stream.FinishSnapshot(); + await publisher.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), Ct); + var update = publisher.Updates.ShouldHaveSingleItem(); + update.OriginAgeBounds.ShouldBe(new DataAgeBounds(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(4))); + if (rejectPublication) + SpinWait.SpinUntil(() => !update.SourceProof.IsValid, TimeSpan.FromSeconds(2)).ShouldBeTrue(); + else update.SourceProof.IsValid.ShouldBeTrue(); + update.Route.PublicationId.ShouldNotBe(Guid.Empty); + } + finally + { + source.Connection.Stream.ReleaseDispose.TrySetResult(); +#pragma warning disable OTOPCUA0001 // Exercise the adapter's stream lifetime directly. + await adapter.UnsubscribeAsync(handle, Ct); +#pragma warning restore OTOPCUA0001 + } + await adapter.ShutdownAsync(Ct); + } + + private sealed class FakePublisher : IProjectedValuePublisher + { + public bool Reject { get; init; } + public List Updates { get; } = []; + public TaskCompletionSource Published { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public bool TryBind(ProjectedValueRoute route) => true; + public bool TryPublish(IReadOnlyList updates) + { Updates.AddRange(updates); Published.TrySetResult(); return !Reject; } + public void Retire(ProjectedValueRoute route) { } + } + + private sealed class FakeRoutes : IGrpcDataAdapterRouteSource + { + private readonly FakeLease _lease = new(); + public bool TryResolve(string fullReference, out GrpcDataAdapterRoute? route) + { + route = fullReference == Ref ? new GrpcDataAdapterRoute(Ref, View, Metadata, Serving, _lease, 1) : null; + return route is not null; + } + } + private sealed class FakeLease : IDataAuthorizationLease + { + public bool IsValid => true; + public ServingIdentity Serving => GrpcDataAdapterLifecycleTests.Serving; + } + private sealed class FakeConnectionSource : IGrpcDataAdapterConnectionSource + { + public FakeConnection Connection { get; } = new(); + public FakeConnectionLease? LastLease { get; private set; } + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + LastLease = new FakeConnectionLease(Connection); + return ValueTask.FromResult(LastLease); + } + } + private sealed class FakeConnectionLease(FakeConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public bool Disposed { get; private set; } + public ValueTask DisposeAsync() { Disposed = true; return ValueTask.CompletedTask; } + } + private sealed class FakeConnection : IDataConnection + { + public int WriteCount { get; private set; } + public FakeSubscription Stream { get; } = new(); + public DataTarget Target { get; } = new(DataTargetMode.Cluster, "remote-cluster", null); + public TimeProvider Clock => TimeProvider.System; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => + Task.FromResult(new DataCapabilities(1, 2, Serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, new HashSet { DataValueKind.Int32 }, Limits, false, 0, "remote-cluster", true, true)); + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + { + WriteCount++; + return Task.FromResult>(request.Items.Select(x => new WriteItemResult(x.CorrelationId, + new(DataWriteState.OutcomeUnknown, 0x800A0000u, "uncertain"))).ToArray()); + } + public Task SubscribeAsync(CancellationToken cancellationToken) => Task.FromResult(Stream); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + private sealed class FakeSubscription : IDataSubscription, IDataSubscriptionProvenance + { + private readonly Channel _frames = Channel.CreateUnbounded(); + private string? _subscriptionId; + private long _streamEpoch; + public bool HoldSnapshotEnd { get; set; } + public TaskCompletionSource SnapshotValueConsumed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ServingIdentity Serving => GrpcDataAdapterLifecycleTests.Serving; + public TaskCompletionSource DisposeEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource ReleaseDispose { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + if (command is OpenSubscription open) + { + _subscriptionId = open.SubscriptionId; + _streamEpoch = open.StreamEpoch; + var settings = open.Items[0].Settings; + _frames.Writer.TryWrite(new DataSubscriptionAck(open.SubscriptionId, open.StreamEpoch, 1, open.CommandId, + [new(open.Items[0].ClientItemId, DataItemStatus.Good, new(open.SubscriptionId, open.StreamEpoch, 1, 1), settings, null)])); + _frames.Writer.TryWrite(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 2, DataStreamControlKind.SnapshotBegin, [], 3, 4, null)); + if (HoldSnapshotEnd) + _frames.Writer.TryWrite(new DataSubscriptionValues(open.SubscriptionId, open.StreamEpoch, 3, true, + [new(new(open.SubscriptionId, open.StreamEpoch, 1, 1), new(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, 1), + new(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(4)), DataReadiness.Ready)])); + else _frames.Writer.TryWrite(new DataSubscriptionControl(open.SubscriptionId, open.StreamEpoch, 3, DataStreamControlKind.SnapshotEnd, [], 3, 4, null)); + } + return Task.CompletedTask; + } + public void FinishSnapshot() => _frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _streamEpoch, 4, + DataStreamControlKind.SnapshotEnd, [], 3, 4, null)); + public async IAsyncEnumerable ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var frame in _frames.Reader.ReadAllAsync(cancellationToken)) + { + yield return frame; + if (frame is DataSubscriptionValues) SnapshotValueConsumed.TrySetResult(); + } + } + public async ValueTask DisposeAsync() + { + DisposeEntered.TrySetResult(); + await ReleaseDispose.Task; + _frames.Writer.TryComplete(); + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs index 1b13f9505..edfcc2ab4 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataCatalogStagingTests.cs @@ -36,6 +36,516 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase private static readonly ServingIdentity BootIdentity = new("node-a", "process-1", "Primary", 0, 0); private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000); + [Fact] + public void Mappings_activate_only_with_the_exact_completed_catalog_and_close_on_next_attempt() + { + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, Artifact()); + var mapping = TestMapping(); + runtime.Stage(attempt, [mapping], [TestConnection()]); + runtime.Active.ShouldBeEmpty(); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var placement = runtime.Active.ShouldHaveSingleItem(); + var parent = coordinator.Current!.Nodes.Single(x => x.EntityKind == "RawFolder" && x.EntityId == "folder"); + placement.Parent.ShouldBe(parent.Metadata.View); + placement.Scope.Segments.ShouldBe(parent.Scope.Segments.Concat(["Remote"])); + placement.Anchor.Address.OriginClusterId.ShouldBe("remote-cluster"); + placement.Authority.IsActive.ShouldBeTrue(); + runtime.TryGetConnectionId("map", out var connectionId).ShouldBeTrue(); + connectionId.ShouldBe("link"); + var next = coordinator.BeginAttempt("next"); + placement.Authority.IsActive.ShouldBeFalse(); + runtime.Active.ShouldBeEmpty(); + runtime.TryGetConnectionId("map", out _).ShouldBeFalse(); + coordinator.Complete(attempt, true).ShouldBeFalse(); + runtime.Active.ShouldBeEmpty(); + coordinator.Complete(next, false).ShouldBeFalse(); + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Configured_capability_is_minted_only_from_live_authorized_placement_and_expires_with_attempt() + { + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, Artifact()); + var mapping = TestMapping(); + runtime.Stage(attempt, [mapping], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out _, out _).ShouldBeFalse("Subscribe is required"); + + var replacement = Prepare(coordinator, Artifact()); + mapping.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe; + runtime.Stage(replacement, [mapping], [TestConnection()]); + coordinator.Complete(replacement, true).ShouldBeTrue(); + runtime.TryAcquireConfiguredCapability("map", DataRealm.Uns, out _, out _).ShouldBeFalse(); + runtime.TryAcquireConfiguredCapability("missing", DataRealm.Raw, out _, out _).ShouldBeFalse(); + runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var capability, out var copy).ShouldBeTrue(); + capability.ShouldNotBeNull(); copy.ShouldNotBeNull(); + runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var shared, out var otherCopy).ShouldBeTrue(); + shared.ShouldBeSameAs(capability); + otherCopy.ShouldNotBeSameAs(copy); + var originalView = copy!.Anchor; + var originalAuthority = copy.Authority; + capability!.Matches("map", originalView, originalAuthority).ShouldBeTrue(); + copy.Mapping.Revision++; + copy.Mapping.AllowedOperations = DataOperations.None; + capability.Matches("map", originalView, originalAuthority).ShouldBeTrue("the caller cannot mutate the captured placement"); + coordinator.BeginAttempt("retire"); + capability.Matches("map", originalView, originalAuthority).ShouldBeFalse(); + } + + [Fact] + public void Retired_configured_capability_does_not_retain_unrelated_placement_graph() + { + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var (capability, unrelated) = Publish(runtime, coordinator); + coordinator.BeginAttempt("replacement"); + GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); + unrelated.IsAlive.ShouldBeFalse("one retired capability must not retain every old mapping"); + GC.KeepAlive(capability); + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + static (ConfiguredProjectionCapability Capability, WeakReference Unrelated) Publish(ProjectedMappingDeploymentRuntime runtime, LocalCatalogCoordinator coordinator) + { + var attempt = Prepare(coordinator, Artifact()); + var selected = TestMapping(); selected.AllowedOperations = DataOperations.Browse | DataOperations.Subscribe; + var other = TestMapping(); other.RemoteNamespaceMappingId = "other"; other.BranchName = "Other"; + runtime.Stage(attempt, [selected, other], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + runtime.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var capability, out _).ShouldBeTrue(); + // Observe the actual deployment-owned DTO rather than a defensive Active copy. + var fields = typeof(ProjectedMappingDeploymentRuntime).GetField("_byMapping", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + var mappings = (Dictionary)fields.GetValue(runtime)!; + return (capability!, new WeakReference(mappings["other"].Mapping)); + } + } + + [Theory] + [InlineData("missing", "Remote")] + [InlineData("folder", "Driver")] + public void Invalid_or_colliding_mapping_is_not_activated(string parent, string name) + { + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, Artifact(includeDriver: true)); + var mapping = TestMapping(); mapping.LocalParentId = parent; mapping.BranchName = name; + runtime.Stage(attempt, [mapping], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + runtime.Active.ShouldBeEmpty(); + } + + private static RemoteNamespaceMapping TestMapping() => new() { RemoteNamespaceMappingId = "map", ClusterId = "cluster", + DataConnectionId = "link", Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, + LocalParentKind = "RawFolder", LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = "remote-root", + RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "remote-root", AllowedOperations = DataOperations.Browse }; + private static DataConnection TestConnection() => new() { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "remote-cluster" }; + private sealed class MissingProjectionSource : IGrpcDataAdapterConnectionSource + { + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => ValueTask.FromResult(null); + } + + [Fact(Timeout = 15000)] + public async Task Browse_controller_mounts_real_placement_and_schedules_bounded_caller_bound_work() + { + var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var catalog = new HeldBrowseCatalog(); var sink = new BrowseControllerSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink, + (uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)), + new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 1); + var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var anchor = sink.Anchor.ShouldNotBeNull(); + anchor.Parent.IdentifierAsString.ShouldBe("Plant"); + var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity( + new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null); + var point = new Opc.Ua.Server.ContinuationPoint { MaxResultsToReturn = 3 }; + var context = new ProjectedBrowseContext(sink.AnchorId.ShouldNotBeNull(), identity, point, TimeProvider.System.GetTimestamp()); + controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Pending); + controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Pending); + await catalog.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + catalog.Calls.ShouldBe(1); + catalog.Last.ShouldNotBeNull().Caller.Principal.ShouldBe("peer"); + catalog.Last.Caller.ApiKeyId.ShouldBe("peer-key"); + catalog.Last.Parent.ShouldBe(lifecycle.Active.ShouldHaveSingleItem().Anchor); + catalog.Last.Budget.MaxItems.ShouldBe(3); + coordinator.BeginAttempt("replacement"); + sink.Removals.ShouldBe(1); + controller.GetOrSchedule(context).ShouldBe(ProjectedBrowseReadiness.Unavailable); + catalog.Release.TrySetResult(); + } + + [Fact(Timeout = 15000)] + public async Task Browse_next_schedules_the_original_cursor_and_caller_without_consuming_it_while_pending() + { + var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var catalog = new HeldBrowseCatalog(); var sink = new BrowseControllerSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink, + (uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)), + new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2); + var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity( + new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null); + var request = new ProjectedBrowsePageRequest(sink.AnchorId.ShouldNotBeNull(), identity, "opaque-wrapped-cursor", 3, TimeProvider.System.GetTimestamp()); + var first = controller.GetOrSchedulePage(request); + first.Status.ShouldBe(ProjectedBrowseReadiness.Pending); first.Children.ShouldBeEmpty(); first.NextCursor.ShouldBeNull(); + controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Pending); + await catalog.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + catalog.Calls.ShouldBe(1); catalog.Last.ShouldNotBeNull().Continuation.ShouldBe("opaque-wrapped-cursor"); + catalog.Last.Caller.Principal.ShouldBe("peer"); catalog.Last.Caller.ApiKeyId.ShouldBe("peer-key"); + request.Cursor.ShouldBe("opaque-wrapped-cursor"); + catalog.Release.TrySetResult(); + } + + [Fact] + public void Browse_page_exposes_only_live_caller_scoped_committed_nodes_and_revokes_old_proof() + { + var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var catalog = new ReadyBrowseCatalog(); var sink = new BrowseControllerSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink, + (uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)), + new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2); + var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var placement = lifecycle.Active.ShouldHaveSingleItem(); + var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1); + var lease = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(30)), + TimeProvider.System.GetTimestamp(), TimeSpan.FromSeconds(30), TimeSpan.Zero, TimeProvider.System); + var view = placement.Anchor with { Address = placement.Anchor.Address with { Identifier = "child" }, Subject = "Plant/Remote/child" }; + var metadata = new DataMetadata(view, "child", "Variable", DataValueKind.Int32, -1, [], false, + DataOperations.Browse | DataOperations.Read, 1, null, null, false, Serving: serving); + var scope = placement.Scope with { Segments = placement.Scope.Segments.Concat(["child"]).ToArray() }; + var subject = new MappedNamespaceSubject(view, scope, placement.LocalAncestry, serving, DataOperations.Browse | DataOperations.Read, false); + var mapped = new MappedSubjectResolver([subject], 1, placement.Authority); + var proof = new ProjectedNodeProof(ProjectedDataIds.Identifier("map", view.Address), metadata, subject, mapped, lease, 1, + metadata with { View = view with { MappingId = null, MappingRevision = 0 } }); + catalog.Snapshot = new(ProjectionPageStatus.Ready, [proof], false, "next-wrapped", 1, lease, placement.Authority); + var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity( + new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null); + var page = controller.GetOrSchedulePage(new(sink.AnchorId.ShouldNotBeNull(), identity, "wrapped", 3, TimeProvider.System.GetTimestamp())); + page.Status.ShouldBe(ProjectedBrowseReadiness.Ready); page.Complete.ShouldBeFalse(); page.NextCursor.ShouldBe("next-wrapped"); + page.Children.ShouldHaveSingleItem().IdentifierAsString.ShouldBe(proof.LocalIdentifier); + catalog.Last.ShouldNotBeNull().Continuation.ShouldBe("wrapped"); catalog.Last.Caller.Principal.ShouldBe("peer"); + page.IsCurrent().ShouldBeTrue(); + catalog.Revoked = true; + page.IsCurrent().ShouldBeFalse(); + } + + private sealed class TestPageGuard(Func current) : IProjectedPageGuard + { + public bool IsCurrent => current(); + public long RetainedBytes => 512; + } + private sealed class ReadyBrowseCatalog : IFederatedProjectionCatalog + { + public bool Revoked; public ProjectedParentSnapshot Snapshot = new(ProjectionPageStatus.Pending, [], false, null, 0); + public ProjectedBrowseRequest? Last; + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) + { Last = request; return Revoked ? new(ProjectionPageStatus.Unavailable, [], false, null, 0) : Snapshot; } + public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => + new TestPageGuard(() => !Revoked && ReferenceEquals(Snapshot, expected)); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new InvalidOperationException(); + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + } + + [Fact(Timeout = 15000)] + public async Task Browse_renews_expired_page_through_a_new_fetch_and_recovers() + { + var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var catalog = new RenewingBrowseCatalog(); var sink = new BrowseControllerSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink, + (uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)), + new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2); + var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + catalog.Local = lifecycle.Active.ShouldHaveSingleItem().Authority; + var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity( + new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null); + var request = new ProjectedBrowsePageRequest(sink.AnchorId.ShouldNotBeNull(), identity, null, 3, TimeProvider.System.GetTimestamp()); + var previous = controller.GetOrSchedulePage(request); + previous.Status.ShouldBe(ProjectedBrowseReadiness.Ready); previous.IsCurrent().ShouldBeTrue(); + catalog.Lease.Valid = false; + previous.IsCurrent().ShouldBeFalse(); + controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Pending); + await catalog.Committed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + catalog.Fetches.ShouldBe(1); + controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Ready); + controller.GetOrSchedulePage(request with { Cursor = "invalid" }).Status.ShouldBe(ProjectedBrowseReadiness.InvalidContinuation); + catalog.Fetches.ShouldBe(1); + } + + [Fact(Timeout = 15000)] + public void Browse_reports_invalid_cursor_found_by_remote_preparation_without_consuming_or_retrying() + { + var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var catalog = new InvalidAsyncBrowseCatalog(); var sink = new BrowseControllerSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink, + (uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)), + new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2); + var attempt = Prepare(coordinator, Artifact()); lifecycle.Stage(attempt, [TestMapping()], [TestConnection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var identity = new ZB.MOM.WW.OtOpcUa.OpcUaServer.Security.RoleCarryingUserIdentity( + new Opc.Ua.UserNameIdentityToken { UserName = "reader" }, [], "peer", "peer-key", "version", null); + var request = new ProjectedBrowsePageRequest(sink.AnchorId.ShouldNotBeNull(), identity, "bad-cursor", 3, TimeProvider.System.GetTimestamp()); + controller.GetOrSchedulePage(request).Status.ShouldBe(ProjectedBrowseReadiness.Pending); + AwaitCondition(() => controller.GetOrSchedulePage(request).Status == ProjectedBrowseReadiness.InvalidContinuation, + TimeSpan.FromSeconds(5), "invalid cursor status was lost", TestContext.Current.CancellationToken); + catalog.Fetches.ShouldBe(1); + request.Cursor.ShouldBe("bad-cursor"); + } + private sealed class InvalidAsyncBrowseCatalog : IFederatedProjectionCatalog + { + public int Fetches; + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref Fetches); return Task.FromResult(new InvalidPage()); } + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + private sealed class InvalidPage : IProjectedPreparedPage + { + public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.InvalidContinuation, [], false, null, 0); + public bool TryCommit() => throw new InvalidOperationException("Invalid cursor cannot commit."); + public void Dispose() { } + } + } + + [Fact] + public void Placement_guards_and_reconciliation_do_not_clone_all_mappings_for_every_check() + { + var authority = new DataPlaneAuthorityState(); var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(64, 128, TimeProvider.System, policy), + new BrowseContinuationRegistry(64, TimeProvider.System), new MissingProjectionSource(), policy, 64, 2); + using var lifecycle = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var catalog = new HeldBrowseCatalog(); var sink = new BrowseControllerSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + using var controller = new ProjectedBrowseAccess(lifecycle, catalog, applier, sink, + (uri, id) => new Opc.Ua.NodeId(id, (ushort)(uri == ProjectedDataIds.RawNamespaceUri ? 4 : 2)), + new DataBudget(TimeSpan.FromSeconds(5), 8, 65536), 2); + var attempt = Prepare(coordinator, Artifact()); + var mappings = Enumerable.Range(0, 12).Select(i => { var x = TestMapping(); x.RemoteNamespaceMappingId = "map" + i; x.BranchName = "Remote" + i; x.RemoteIdentifier = "root" + i; return x; }).ToArray(); + lifecycle.Stage(attempt, mappings, [TestConnection()]); coordinator.Complete(attempt, true).ShouldBeTrue(); + var placement = lifecycle.Active[0]; + var before = lifecycle.PlacementCopiesForTests; + for (var i = 0; i < 100; i++) lifecycle.IsCurrentPlacement(placement).ShouldBeTrue(); + lifecycle.PlacementCopiesForTests.ShouldBe(before); + before = lifecycle.PlacementCopiesForTests; + controller.RefreshAnchors(); + (lifecycle.PlacementCopiesForTests - before).ShouldBeLessThanOrEqualTo(mappings.Length); + } + + private sealed class RenewableLease : IDataAuthorizationLease + { + public bool Valid = true; public bool IsValid => Valid; + public ServingIdentity Serving { get; } = new("remote", "boot", "Primary", 1, 1, 1); + } + private sealed class RenewingBrowseCatalog : IFederatedProjectionCatalog + { + public RenewableLease Lease = new(); public IDataMappedCatalogAuthority Local = null!; public int Fetches; + public TaskCompletionSource Committed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => request.Continuation == "invalid" + ? new(ProjectionPageStatus.InvalidContinuation, [], false, null, 0) + : Lease.IsValid ? new(ProjectionPageStatus.Ready, [], true, null, 1, Lease, Local) + : new(ProjectionPageStatus.Unavailable, [], false, null, 0); + public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) + { + var original = Lease; + return new TestPageGuard(() => ReferenceEquals(Lease, original) && original.IsValid && Local.IsActive); + } + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref Fetches); return Task.FromResult(new RenewalPage(this)); } + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + private sealed class RenewalPage(RenewingBrowseCatalog owner) : IProjectedPreparedPage + { + private readonly RenewableLease _fresh = new(); + public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.Ready, [], true, null, 1, _fresh, owner.Local); + public bool TryCommit() { owner.Lease = _fresh; owner.Committed.TrySetResult(); return true; } + public void Dispose() { } + } + } + + private sealed class BrowseControllerSink : IProjectedNamespacePageSink, IProjectedAnchorSink + { + public ProjectedAnchorDefinition? Anchor; public Opc.Ua.NodeId? AnchorId; public int Removals; + public bool TryEnsureProjectedAnchor(ProjectedAnchorDefinition anchor, out Opc.Ua.NodeId? nodeId) + { Anchor = anchor; nodeId = AnchorId = new Opc.Ua.NodeId(anchor.LocalIdentifier, 4); return true; } + public bool TryRemoveProjectedAnchor(Opc.Ua.NodeId anchor, ProjectedAnchorDefinition expected) { Removals++; return true; } + public bool TryApply(Opc.Ua.NodeId parent, IReadOnlyList nodes, Func commit) => commit(); + public bool TryRemove(Opc.Ua.NodeId nodeId, ProjectedVariableDefinition expected) => true; + } + private sealed class HeldBrowseCatalog : IFederatedProjectionCatalog + { + public int Calls; public ProjectedBrowseRequest? Last; + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0); + public async Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref Calls); Last = request; Entered.TrySetResult(); await Release.Task.WaitAsync(cancellationToken); return new FailedBrowsePage(); } + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + } + private sealed class FailedBrowsePage : IProjectedPreparedPage + { + public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.Unavailable, [], false, null, 0); + public bool TryCommit() => false; + public void Dispose() { } + } + + [Fact] + public void Driver_host_activates_only_node_effective_mappings() + { + var bytes = MappingArtifact(); + DeploymentArtifact.ParseRemoteNamespaceMappings(bytes, "node-a").ShouldHaveSingleItem(); + DeploymentArtifact.ParseRemoteNamespaceMappings(bytes, "node-b").ShouldBeEmpty(); + foreach (var node in new[] { "node-a", "node-b" }) + { + var authority = new DataPlaneAuthorityState(); + var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, + () => BootIdentity with { NodeId = node }); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var acks = CreateTestProbe(); + var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: NodeId.Parse(node), ackRouter: acks.Ref, + localRoles: new HashSet { "driver" }, fetchAndCacheMode: true, artifactFetcher: new MutableFetcher(bytes), + catalogCoordinator: coordinator)); + host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId())); + acks.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + if (node == "node-a") runtime.Active.ShouldHaveSingleItem().Mapping.RemoteNamespaceMappingId.ShouldBe("map"); + else runtime.Active.ShouldBeEmpty(); + Sys.Stop(host); + } + } + + [Fact] + public void Standalone_publisher_applies_removal_and_failed_topology_closes_mappings() + { + var bytes = MappingArtifact(); + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var sink = NullOpcUaAddressSpaceSink.Instance; + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger.Instance), + hooks: null, localNode: Node, dataPlaneAuthority: authority, catalogCoordinator: coordinator)); + var replies = CreateTestProbe(); + void Rebuild(byte[] artifact) + { + replies.Send(actor, new OpcUaPublishActor.RebuildAddressSpace(CorrelationId.NewId(), DeploymentId.NewId(), artifact, ReportOutcome: true)); + replies.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + Rebuild(bytes); + var previous = runtime.Active.ShouldHaveSingleItem(); + Rebuild(MappingArtifact(includeMapping: false)); + runtime.Active.ShouldBeEmpty(); previous.Authority.IsActive.ShouldBeFalse(); + Rebuild(bytes); + var restored = runtime.Active.ShouldHaveSingleItem(); + Rebuild("not json"u8.ToArray()); + runtime.Active.ShouldBeEmpty(); restored.Authority.IsActive.ShouldBeFalse(); + runtime.TryGetConnectionId("map", out _).ShouldBeFalse(); + Sys.Stop(actor); + } + + [Fact(Timeout = 30000)] + public async Task Delayed_changed_notification_cannot_reopen_after_a_new_attempt() + { + var bytes = MappingArtifact(); + var authority = new DataPlaneAuthorityState(); + var coordinator = NewCoordinator(authority, new CatalogActivation()); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, TimeProvider.System), TimeProvider.System); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(8, 32, TimeProvider.System, policy), + new BrowseContinuationRegistry(8, TimeProvider.System), new MissingProjectionSource(), policy, 8, 2); + using var runtime = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); + ProjectedMappingPlacement? delayed = null; + runtime.Changed += placements => { if (placements.Count == 0) return; delayed = placements[0]; entered.Set(); release.Wait(TimeSpan.FromSeconds(10)); }; + var acks = CreateTestProbe(); var host = NewHost(bytes, coordinator, acks.Ref); + try + { + host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId())); + entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue(); + coordinator.BeginAttempt("replacement"); + runtime.Active.ShouldBeEmpty(); runtime.TryGetConnectionId("map", out _).ShouldBeFalse(); + release.Set(); + await Task.Run(() => acks.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken), TestContext.Current.CancellationToken); + delayed.ShouldNotBeNull().Authority.IsActive.ShouldBeFalse(); + runtime.Active.ShouldBeEmpty(); runtime.TryGetConnectionId("map", out _).ShouldBeFalse(); + } + finally { release.Set(); Sys.Stop(host); } + } + + private static byte[] MappingArtifact(bool includeMapping = true) + { + var root = JsonNode.Parse(Artifact())!.AsObject(); + root["Nodes"]!.AsArray().Add(JsonNode.Parse(""" + {"NodeId":"node-b","ClusterId":"cluster","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false} + """)); + root["DataConnectionScopeVersion"] = 1; + root["DataConnections"] = JsonSerializer.SerializeToNode(new[] { new DataConnection { DataConnectionId = "link", ClusterId = "cluster", + Enabled = true, ConsumerNodeIds = ["node-a", "node-b"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote-cluster", + ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster", + AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read } }); + var mapping = TestMapping(); mapping.ConsumerNodeIds = ["node-a"]; mapping.RemoteNamespaceUri = V3NodeIds.RawNamespaceUri; + root["RemoteNamespaceMappings"] = JsonSerializer.SerializeToNode(includeMapping ? new[] { mapping } : Array.Empty()); + return Encoding.UTF8.GetBytes(root.ToJsonString()); + } + [Fact] public async Task Returning_to_the_same_role_cannot_revive_a_previous_publication_permit() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs new file mode 100644 index 000000000..22fb99347 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataComposedBrowseWireTests.cs @@ -0,0 +1,276 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 90000)] + public async Task Real_sdk_browse_pages_through_nested_projection_and_preserves_array_metadata() + { + using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, nestedCatalog: true); + await WithComposedServer(origin, origin.Root, async (session, sink, _, _, _, _, anchor) => + { + var client = (SessionClient)session; + var rootReferences = await BrowseAll(client, anchor, 1); + rootReferences.Count.ShouldBe(3); + var folder = rootReferences.Single(x => x.BrowseName.Name == "Driver"); + folder.NodeClass.ShouldBe(NodeClass.Object); + var folderNode = ExpandedNodeId.ToNodeId(folder.NodeId, session.NamespaceUris); + var children = await BrowseAll(client, folderNode, 1); + children.Count.ShouldBe(2); + children.Select(x => x.BrowseName.Name).Order().ShouldBe(new[] { "Array", "Speed" }); + children.ShouldAllBe(x => x.NodeClass == NodeClass.Variable); + var arrayNode = ExpandedNodeId.ToNodeId(children.Single(x => x.BrowseName.Name == "Array").NodeId, session.NamespaceUris); + var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.ValueRank }, + new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.ArrayDimensions }, + new ReadValueId { NodeId = arrayNode, AttributeId = Attributes.DataType }], TestContext.Current.CancellationToken); + read.Results.ToArray()!.ShouldAllBe(x => StatusCode.IsGood(x.StatusCode)); + read.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(1); + ((uint[])read.Results[1].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy)!).ShouldBe(new uint[] { 3 }); + read.Results[2].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(DataTypeIds.Byte); + var id = ProjectedDataIds.Identifier("map", origin.Raw.Address with { Identifier = "Plant/Driver/Array" }); + ((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.RawNamespaceUri, id, out var indexed).ShouldBeTrue(); + indexed.ShouldNotBeNull().ShouldBe(arrayNode); + }); + } + + [Fact(Timeout = 90000)] + public async Task Uns_projection_browses_and_reads_the_origin_metadata_through_the_real_registry() + { + using var origin = new LocalDataFixture(servingGeneration: 1, nestedUnsCatalog: true); + var originRoot = origin.Uns with { Address = origin.Uns.Address with { Identifier = "Area" }, Subject = "Area" }; + await WithComposedServer(origin, originRoot, async (session, sink, _, _, _, _, anchor) => + { + var children = await BrowseAll((SessionClient)session, anchor, 1); + var child = children.ShouldHaveSingleItem(); + child.BrowseName.Name.ShouldBe("Speed"); + child.NodeClass.ShouldBe(NodeClass.Variable); + var node = ExpandedNodeId.ToNodeId(child.NodeId, session.NamespaceUris); + var expected = ProjectedDataIds.Identifier("map", origin.Uns.Address); + ((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.UnsNamespaceUri, expected, out var indexed).ShouldBeTrue(); + indexed.ShouldNotBeNull().ShouldBe(node); + var response = await ((SessionClient)session).ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = node, AttributeId = Attributes.ValueRank }, + new ReadValueId { NodeId = node, AttributeId = Attributes.DataType }], TestContext.Current.CancellationToken); + response.Results.ToArray()!.ShouldAllBe(x => StatusCode.IsGood(x.StatusCode)); + response.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(-1); + response.Results[1].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(DataTypeIds.Int32); + }); + } + + [Fact(Timeout = 90000)] + public async Task Local_browse_filters_ungranted_sibling_while_preserving_allowed_folder() + { + using var origin = new LocalDataFixture(servingGeneration: 1); + await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, _) => + { + var namespaceIndex = session.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri); + namespaceIndex.ShouldBeGreaterThan(0); + var root = new NodeId(V3NodeIds.SharedRootFolderId, (ushort)namespaceIndex); + var children = await BrowseAll((SessionClient)session, root, 10); + children.ShouldContain(x => x.DisplayName.Text == "Plant"); + children.ShouldNotContain(x => x.DisplayName.Text == "Outside"); + }, restrictToPlant: true); + } + + [Fact(Timeout = 90000)] + public async Task Mapped_value_root_is_discovered_headlessly_then_read_and_monitored_by_sdk() + { + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + origin.Publish(42); + await WithComposedServer(origin, origin.Raw, async (session, sink, resolver, applier, access, placements, anchor) => + { + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + var reference = Reference("map", DataRealm.Raw, origin.Raw.Address); + await using var lease = await discovery.ResolveAsync(reference, TestContext.Current.CancellationToken); + lease.ShouldNotBeNull(); + lease.IsValid.ShouldBeTrue(); + await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask() + .WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + ((IProjectedNodeLookup)sink).TryResolve(anchor, out var root).ShouldBeTrue(); + root.ShouldNotBeNull().Metadata.ValueKind.ShouldBe(DataValueKind.Int32); + var client = (SessionClient)session; + var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.NodeClass }], TestContext.Current.CancellationToken); + read.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + read.Results[0].WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe((int)NodeClass.Variable); + // A cold SDK read schedules a remote read; the next read can consume its published sample. + var deadline = DateTime.UtcNow.AddSeconds(10); + Opc.Ua.DataValue value; + do + { + var values = await client.ReadAsync(new RequestHeader(), 5000, TimestampsToReturn.Both, + [new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], TestContext.Current.CancellationToken); + value = values.Results[0]; + if (StatusCode.IsGood(value.StatusCode)) break; + await Task.Delay(25, TestContext.Current.CancellationToken); + } while (DateTime.UtcNow < deadline); + StatusCode.IsGood(value.StatusCode).ShouldBeTrue(); + value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42); + var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 10, 0, true, 0, + TestContext.Current.CancellationToken)).SubscriptionId; + var monitored = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both, + [new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }, + MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters + { ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], TestContext.Current.CancellationToken); + monitored.Results[0].StatusCode.ShouldBe(StatusCodes.Good); + access.HasLiveDemand(DataRealm.Raw, ProjectedDataIds.Identifier("map", origin.Raw.Address)).ShouldBeTrue(); + }); + } + + private async Task WithComposedServer(LocalDataFixture origin, DataView root, + Func exercise, + bool restrictToPlant = false) + { + var ct = TestContext.Current.CancellationToken; + var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}"); + var port = 0; + var started = await OpcUaHostStart.StartAsync(p => + { + port = p; + return new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ComposedProjection", ApplicationUri = $"urn:composed:{Guid.NewGuid():N}", + OpcUaPort = p, PublicHostname = "127.0.0.1", PkiStoreRoot = pki, + EnabledSecurityProfiles = [OpcUaSecurityProfile.None], AutoAcceptUntrustedClientCertificates = true, + }, NullLogger.Instance, new PeerAuthenticator(origin.Context)); + }, () => new OtOpcUaSdkServer(), ct); + try + { + var connections = new FakeConnections(origin); + var authority = new DataPlaneAuthorityState(); + var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, + () => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1)); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy), + new BrowseContinuationRegistry(16, origin.Clock), connections, policy, 16, 2); + using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator, restrictToPlant); + var mapping = Mapping(root); + if (root.Realm == DataRealm.Uns) + { + mapping.Realm = mapping.RemoteRealm = DataRealm.Uns; + mapping.LocalParentKind = "UnsArea"; + mapping.LocalParentId = "area"; + } + mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata; + placements.Stage(attempt, [mapping], [Connection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var manager = started.Server.NodeManager!; + manager.ProjectedBrowseClock = origin.Clock; + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + manager.EnsureFolder("Outside", null, "Outside", AddressSpaceRealm.Raw); + if (root.Realm == DataRealm.Uns) + manager.EnsureFolder("area", null, "area", AddressSpaceRealm.Uns); + manager.DataPlaneAuthority = authority; + manager.Authorizer = new DataPlaneAuthorizer(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), + enabled: true, NullLogger.Instance, origin.Clock); + manager.MappedSubjectResolver = (realm, identifier) => + resolver.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns, identifier, out var proof) && proof is not null + ? MappedNodeResolution.Mapped(proof.Metadata.View, proof.Subject, proof.Resolver, proof.Lease) + : MappedNodeResolution.Deny; + var sink = new SdkAddressSpaceSink(manager); + using var applier = new ProjectedNamespaceApplier(resolver, sink, 2); + using var access = new ProjectedDataAccess(resolver, sink, connections, + id => placements.TryGetConnectionId(id, out var connection) ? connection : null, + policy, new DirectPublisher(sink), origin.Clock, new(8, 4, 8_000_000, 2)); + using var browse = new ProjectedBrowseAccess(placements, resolver, applier, sink, + (uri, id) => manager.TryGetNodeId(uri, id, out var node) ? node : null, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + manager.ProjectedBrowseAccess = browse; + manager.ProjectedDataAccess = access; + var identifier = ProjectedDataIds.Identifier("map", root.Address); + ((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue(); + var anchor = node.ShouldNotBeNull(); + using var session = await ConnectComposed(port, pki, ct); + await exercise(session, sink, resolver, applier, access, placements, anchor); + } + finally + { + await started.Host.DisposeAsync(); + if (Directory.Exists(pki)) Directory.Delete(pki, recursive: true); + } + } + + private static async Task> BrowseAll(SessionClient client, NodeId node, uint size) + { + var ct = TestContext.Current.CancellationToken; + var response = await client.BrowseAsync(new RequestHeader(), null, size, [new BrowseDescription + { + NodeId = node, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, + IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, + }], ct); + var page = response.Results[0]; + StatusCode.IsGood(page.StatusCode).ShouldBeTrue(); + var references = new List(page.References.ToArray()!); + var cursor = page.ContinuationPoint; + while (!cursor.IsEmpty) + { + var next = await client.BrowseNextAsync(new RequestHeader(), false, [cursor], ct); + page = next.Results[0]; + StatusCode.IsGood(page.StatusCode).ShouldBeTrue(); + references.AddRange(page.References.ToArray()!); + cursor = page.ContinuationPoint; + } + return references; + } + + private static async Task ConnectComposed(int port, string pki, CancellationToken ct) + { + var clientPki = Path.Combine(pki, "client"); + var security = new SecurityConfiguration + { + ApplicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "own") }, + TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "issuer") }, + TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "trusted") }, + RejectedCertificateStore = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(clientPki, "rejected") }, + AutoAcceptUntrustedCertificates = true, + }; + var telemetry = DefaultTelemetry.Create(_ => { }); + var config = new ApplicationConfiguration(telemetry) + { + ApplicationName = "ComposedClient", ApplicationUri = $"urn:composed-client:{Guid.NewGuid():N}", + ApplicationType = ApplicationType.Client, SecurityConfiguration = security, + ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60_000 }, + }; + await config.ValidateAsync(ApplicationType.Client, ct); + var endpoint = await CoreClientUtils.SelectEndpointAsync(config, $"opc.tcp://127.0.0.1:{port}/OtOpcUa", false, telemetry, ct); + return await new DefaultSessionFactory(telemetry).CreateAsync(config, + new ConfiguredEndpoint(null, endpoint!, EndpointConfiguration.Create(config)), false, false, "ComposedClient", 60_000, + new UserIdentity("apikey", System.Text.Encoding.UTF8.GetBytes("test-secret")), default, ct); + } + + private sealed class DirectPublisher(SdkAddressSpaceSink sink) : IProjectedValuePublisher + { + public bool TryBind(ProjectedValueRoute route) => true; + public bool TryPublish(IReadOnlyList updates) => ((IProjectedValueSink)sink).TryPublish( + updates.Select(x => new ProjectedValueWrite(x.Route.Realm, x.Route.LocalIdentifier, x.Route.ProjectionGeneration, + x.Route.Serving, x.Snapshot, x.OriginAgeBounds, x.ReceivedTimestamp, x.SourceProof, x.IsCompleteSnapshot)).ToArray()); + public void Retire(ProjectedValueRoute route) { } + } + + private sealed class PeerAuthenticator(DataAuthenticatedContext context) : IOpcUaUserAuthenticator + { + public Task AuthenticateUserNameAsync(string username, string password, CancellationToken ct) => + Task.FromResult(username == "apikey" && password == "test-secret" + ? OpcUaUserAuthResult.AllowKey(context.PrincipalId, [], context.ApiKeyId) with + { CredentialVersion = context.CredentialVersion, CredentialExpiresUtc = context.CredentialExpiresUtc } + : OpcUaUserAuthResult.Deny("Invalid key")); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredAcquisitionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredAcquisitionTests.cs new file mode 100644 index 000000000..043eb415c --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredAcquisitionTests.cs @@ -0,0 +1,77 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataConfiguredAcquisitionTests +{ + [Fact(Timeout = 30000)] + public async Task Configured_interest_owns_one_scoped_acquisition_until_last_interest_is_removed() + { + var reference = ProjectedDataIds.DependencyReference(DataRealm.Raw, + ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/tag"))); + var discovery = new Discovery(); + await using var owner = new ConfiguredProjectedInterestOwner(discovery, 2); + owner.SetInterest(reference, true); + var token = TestContext.Current.CancellationToken; + await discovery.Started.Task.WaitAsync(TimeSpan.FromSeconds(5), token); + owner.SetInterest(reference, true); + discovery.Calls.ShouldBe(1); + owner.SetInterest(reference, false); + await discovery.Lease.Closed.Task.WaitAsync(TimeSpan.FromSeconds(5), token); + discovery.Lease.Valid.ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Many_interests_share_a_fixed_acquisition_worker_limit() + { + var discovery = new BlockingDiscovery(); + await using var owner = new ConfiguredProjectedInterestOwner(discovery, 16, maxConcurrentCalls: 2); + try + { + for (var i = 0; i < 12; i++) + owner.SetInterest(ProjectedDataIds.DependencyReference(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/" + i))), true); + await discovery.TwoEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + discovery.Maximum.ShouldBe(2); + discovery.Calls.ShouldBe(2); + } + finally { discovery.Release.TrySetResult(); } + } + + private sealed class BlockingDiscovery : IConfiguredProjectionDiscovery + { + private int _running; public int Calls, Maximum; + public readonly TaskCompletionSource TwoEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + public readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously); + public async Task ResolveAsync(string reference, CancellationToken cancellationToken) + { + var count = Interlocked.Increment(ref _running); Interlocked.Increment(ref Calls); + if (count > Maximum) Maximum = count; + if (count == 2) TwoEntered.TrySetResult(); + try { await Release.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); return new ScopedLease(); } + finally { Interlocked.Decrement(ref _running); } + } + } + + private sealed class Discovery : IConfiguredProjectionDiscovery + { + public int Calls; + public readonly TaskCompletionSource Started = new(TaskCreationOptions.RunContinuationsAsynchronously); + public readonly ScopedLease Lease = new(); + public Task ResolveAsync(string reference, CancellationToken cancellationToken) + { + Interlocked.Increment(ref Calls); Started.TrySetResult(); + return Task.FromResult(Lease); + } + } + private sealed class ScopedLease : IConfiguredProjectionLease + { + public bool Valid = true; + public bool IsValid => Valid; + public readonly TaskCompletionSource Closed = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask DisposeAsync() { Valid = false; Closed.TrySetResult(); return ValueTask.CompletedTask; } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs new file mode 100644 index 000000000..ac4310f70 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredDiscoveryWireTests.cs @@ -0,0 +1,261 @@ +using System.Security.Cryptography; +using System.Text; +using System.Threading.Channels; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using DataBrowseRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest; +using DataReadRequest = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest; +using DataReadResult = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08Wire")] +public sealed partial class GrpcDataConfiguredDiscoveryWireTests +{ + [Fact(Timeout = 15000)] + public void Mint_reuses_one_mapping_capability_until_the_published_attempt_changes() + { + using var origin = new LocalDataFixture(servingGeneration: 1); + var authority = new DataPlaneAuthorityState(); + var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, + () => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1)); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy), + new BrowseContinuationRegistry(16, origin.Clock), new FakeConnections(origin), policy, 16, 2); + using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator); + var mapping = Mapping(origin.Root); + placements.Stage(attempt, [mapping], [Connection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var first, out var firstPlacement).ShouldBeTrue(); + placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var second, out var secondPlacement).ShouldBeTrue(); + first.ShouldNotBeNull(); firstPlacement.ShouldNotBeNull(); secondPlacement.ShouldNotBeNull(); + second.ShouldBeSameAs(first); + firstPlacement!.Mapping.Revision++; + secondPlacement!.Mapping.Revision.ShouldBe(1); + var replacement = Prepare(coordinator); + placements.Stage(replacement, [mapping], [Connection()]); + coordinator.Complete(replacement, true).ShouldBeTrue(); + placements.TryAcquireConfiguredCapability("map", DataRealm.Raw, out var fresh, out var freshPlacement).ShouldBeTrue(); + fresh.ShouldNotBeNull().ShouldNotBeSameAs(first); + first!.Matches("map", freshPlacement!.Anchor, freshPlacement!.Authority).ShouldBeFalse(); + } + + [Fact(Timeout = 90000)] + public async Task Configured_interest_browses_and_subscribes_without_an_sdk_caller_and_retires_on_removal_and_deployment() + { + var pki = Path.Combine(Path.GetTempPath(), $"configured-projection-{Guid.NewGuid():N}"); + var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions + { + ApplicationName = "ConfiguredProjection", ApplicationUri = $"urn:configured:{Guid.NewGuid():N}", + OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = pki, + }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); + try + { + LocalDataFixture? peer = null; + var subscriptions = new FakeSubscriptions(() => peer!.Serving); + using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions); + peer = origin; + var connections = new FakeConnections(origin); + var authority = new DataPlaneAuthorityState(); + var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, + () => new ServingIdentity("node-a", "boot", "Primary", 0, 0, 1)); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, origin.Clock), origin.Clock); + using var resolver = new RemoteNamespaceResolver(new ProjectedCatalogCache(16, 128, origin.Clock, policy), + new BrowseContinuationRegistry(16, origin.Clock), connections, policy, 16, 2); + using var placements = new ProjectedMappingDeploymentRuntime(coordinator, resolver); + var attempt = Prepare(coordinator); + var mapping = Mapping(origin.Root); + placements.Stage(attempt, [mapping], [Connection()]); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var placement = placements.Active.ShouldHaveSingleItem(); + + var manager = started.Server.NodeManager!; + manager.ShouldNotBeNull(); + manager.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + manager.TryGetNodeId(V3NodeIds.RawNamespaceUri, "Plant", out var parentId).ShouldBeTrue(); + var parent = parentId.ShouldNotBeNull(); + var sink = new SdkAddressSpaceSink(manager); + var anchorId = ProjectedDataIds.Identifier("map", placement.Anchor.Address); + var anchor = new ProjectedAnchorDefinition(DataRealm.Raw, anchorId, parent, "Remote", "Plant/Remote", "map", 1, + () => placement.Authority.IsActive); + ((IProjectedAnchorSink)sink).TryEnsureProjectedAnchor(anchor, out _).ShouldBeTrue(); + using var applier = new ProjectedNamespaceApplier(resolver, sink, 2); + using var access = new ProjectedDataAccess(resolver, sink, connections, + id => placements.TryGetConnectionId(id, out var connection) ? connection : null, + policy, new Publisher(), origin.Clock, new(8, 4, 2_000_000, 2)); + var discovery = new ConfiguredProjectionDiscovery(placements, resolver, applier, sink, access, + new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8); + var reference = Reference("map", DataRealm.Raw, origin.Raw.Address); + var identifier = ProjectedDataIds.Identifier("map", origin.Raw.Address); + + await using (var owner = new ConfiguredProjectedInterestOwner(discovery, 8)) + { + owner.SetInterest(reference, true); + await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + connections.BrowseCalls.ShouldBeGreaterThan(0); + ((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.RawNamespaceUri, identifier, out var node).ShouldBeTrue(); + node.ShouldNotBeNull(); + ((IProjectedNodeLookup)sink).TryResolve(node!.Value, out var materialized).ShouldBeTrue(); + materialized.ShouldNotBeNull(); + access.HasLiveDemand(DataRealm.Raw, identifier).ShouldBeTrue(); + + var wrongMap = Reference("unconfigured", DataRealm.Raw, origin.Raw.Address); + var wrongRealm = Reference("map", DataRealm.Uns, origin.Raw.Address); + (await discovery.ResolveAsync(wrongMap, TestContext.Current.CancellationToken)).ShouldBeNull(); + (await discovery.ResolveAsync(wrongRealm, TestContext.Current.CancellationToken)).ShouldBeNull(); + var forged = origin.Raw.Address with { Identifier = "outside-the-exported-page" }; + (await discovery.ResolveAsync(Reference("map", DataRealm.Raw, forged), TestContext.Current.CancellationToken)).ShouldBeNull(); + subscriptions.Opens.ShouldBe(1, "decoded addresses must not create a subscription without a verified page"); + + var browsesBeforeExpiry = connections.BrowseCalls; + origin.Clock.Advance(TimeSpan.FromSeconds(16)); + await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + connections.BrowseCalls.ShouldBeGreaterThan(browsesBeforeExpiry, "expired metadata must be renewed from the peer"); + access.HasLiveDemand(DataRealm.Raw, identifier).ShouldBeTrue(); + + owner.SetInterest(reference, false); + await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + } + + await using (var owner = new ConfiguredProjectedInterestOwner(discovery, 8)) + { + owner.SetInterest(reference, true); + await subscriptions.Opened.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + var replacement = Prepare(coordinator); + await subscriptions.Closed.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + mapping.Enabled = false; + placements.Stage(replacement, [mapping], [Connection()]); + coordinator.Complete(replacement, true).ShouldBeTrue(); + (await discovery.ResolveAsync(reference, TestContext.Current.CancellationToken)).ShouldBeNull(); + } + } + finally + { + await started.Host.DisposeAsync(); + if (Directory.Exists(pki)) Directory.Delete(pki, recursive: true); + } + } + + private static string Reference(string mapping, DataRealm realm, DataAddress address) => + ProjectedDataIds.DependencyReference(realm, ProjectedDataIds.Identifier(mapping, address)); + + private static RemoteNamespaceMapping Mapping(DataView root) => new() + { + RemoteNamespaceMappingId = "map", ClusterId = "cluster", DataConnectionId = "link", Revision = 1, + Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, LocalParentKind = "RawFolder", + LocalParentId = "folder", BranchName = "Remote", RemoteRootEntityId = root.Subject, + RemoteNamespaceUri = root.Address.NamespaceUri, RemoteIdentifierKind = root.Address.IdentifierKind, + RemoteIdentifier = root.Address.Identifier, AllowedOperations = DataOperations.Browse | DataOperations.Subscribe, + MetadataLeaseMilliseconds = 15000, StaleTimeoutMilliseconds = 30000, + }; + + private static DataConnection Connection() => new() + { DataConnectionId = "link", ClusterId = "cluster", Enabled = true, ExpectedClusterId = "cluster" }; + + private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, bool restrictToPlant = false) + { + 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":7}], + "RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}], + "DriverInstances":[],"Devices":[],"TagGroups":[],"Tags":[],"UnsAreas":[{"UnsAreaId":"area","ClusterId":"cluster","Name":"area"}],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[], + "DataConnections":[],"RemoteNamespaceMappings":[], + "DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":7}]} + """); + if (restrictToPlant) + bytes = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(bytes).Replace( + "\"ScopeKind\":0,\"PermissionFlags\":7", "\"ScopeKind\":7,\"ScopeId\":\"folder\",\"PermissionFlags\":7", StringComparison.Ordinal)); + var attempt = coordinator.BeginAttempt(Convert.ToHexStringLower(SHA256.HashData(bytes))); + coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue(); + using var parsed = DeploymentArtifact.Open(bytes); + coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!).ShouldBeTrue(); + return attempt; + } + + private sealed class Publisher : IProjectedValuePublisher + { + public bool TryBind(ProjectedValueRoute route) => true; + public bool TryPublish(IReadOnlyList updates) => true; + public void Retire(ProjectedValueRoute route) { } + } + + private sealed class FakeConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource + { + private int _browseCalls; + public int BrowseCalls => Volatile.Read(ref _browseCalls); + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + ValueTask.FromResult(connectionId == "link" ? new Lease(new Connection(peer.Connection(), this)) : null); + private sealed class Lease(IDataConnection connection) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() => connection.DisposeAsync(); + } + private sealed class Connection(IDataConnection inner, FakeConnections owner) : IDataConnection + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(DataBrowseRequest request, CancellationToken cancellationToken) + { Interlocked.Increment(ref owner._browseCalls); return inner.BrowseAsync(request, cancellationToken); } + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); + public Task> ReadAsync(DataReadRequest request, CancellationToken cancellationToken) => inner.ReadAsync(request, cancellationToken); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => inner.WriteAsync(request, cancellationToken); + public Task SubscribeAsync(CancellationToken cancellationToken) => inner.SubscribeAsync(cancellationToken); + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + } + + private sealed class FakeSubscriptions(Func serving) : IDataSubscriptionService + { + public readonly Channel Opened = Channel.CreateUnbounded(); + public readonly Channel Closed = Channel.CreateUnbounded(); + private int _opens; + public int Opens => Volatile.Read(ref _opens); + public Task SubscribeAsync(CancellationToken cancellationToken) + { + var number = Interlocked.Increment(ref _opens); + return Task.FromResult(new Stream(this, serving(), number)); + } + private sealed class Stream(FakeSubscriptions owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance + { + private readonly Channel _frames = Channel.CreateUnbounded(); + private readonly Dictionary _ids = new(); + private long _sequence; + private ulong _handle; + public ServingIdentity Serving => serving; + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + IReadOnlyList items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] }; + var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, + new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray(); + foreach (var ack in acks) if (ack.Handle is not null) _ids[ack.Handle] = ack.ClientItemId; + if (command is RemoveSubscriptionItems remove) + acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray(); + _frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks)); + if (items.Count > 0) + { + owner.Opened.Writer.TryWrite(number); + _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + } + return Task.CompletedTask; + } + public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); + public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.Closed.Writer.TryWrite(number); return ValueTask.CompletedTask; } + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredInterestTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredInterestTests.cs new file mode 100644 index 000000000..62b060cd7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConfiguredInterestTests.cs @@ -0,0 +1,37 @@ +using Akka.Actor; +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; +using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataConfiguredInterestTests : RuntimeActorTestBase +{ + [Fact(Timeout = 30000)] + public void Mux_notifies_only_first_and_last_configured_projected_interest() + { + var events = CreateTestProbe(); var first = CreateTestProbe(); var second = CreateTestProbe(); + var sink = new Sink(events.Ref); + var mux = Sys.ActorOf(DependencyMuxActor.Props(interestSink: sink)); + var id = ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/tag")); + var reference = ProjectedDataIds.DependencyReference(DataRealm.Raw, id); + mux.Tell(new DependencyMuxActor.RegisterInterest([reference, "ordinary"], first.Ref)); + events.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken).ShouldBe(new Transition(reference, true)); + mux.Tell(new DependencyMuxActor.RegisterInterest([reference], second.Ref)); + mux.Tell(new DependencyMuxActor.RegisterInterest([reference], first.Ref)); + mux.Tell(new DependencyMuxActor.UnregisterInterest(first.Ref)); + events.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken); + mux.Tell(new DependencyMuxActor.UnregisterInterest(second.Ref)); + events.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken).ShouldBe(new Transition(reference, false)); + } + + private sealed record Transition(string Reference, bool Active); + private sealed class Sink(IActorRef target) : IProjectedDependencyInterestSink + { + public void SetInterest(string projectedReference, bool active) => target.Tell(new Transition(projectedReference, active)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs index d40517244..f177d3721 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConnectionClientTests.cs @@ -82,6 +82,132 @@ public sealed class GrpcDataConnectionClientTests await Should.ThrowAsync(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken)); } + [Fact] + public async Task Strict_generation_mismatch_is_rejected_without_dispatch_or_rebinding() + { + var first = new FailoverHandler("a", true); + var second = new FailoverHandler("b", false); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), + 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); + using var value = DataValue.FromScalar(DataValueKind.Int32, 1); + var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + first.WrittenIds.ShouldBeEmpty(); second.WrittenIds.ShouldBeEmpty(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Strict_discovery_skips_unavailable_or_mismatching_peer_before_first_dispatch(bool unavailable) + { + var first = new FailoverHandler("a", false, generation: 1, unavailable: unavailable); + var second = new FailoverHandler("b", false, generation: 2); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), + 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); + using var value = DataValue.FromScalar(DataValueKind.Int32, 1); + var result = await connection.WriteAsync(new([new("item", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + first.WrittenIds.ShouldBeEmpty(); second.WrittenIds.ShouldBe(new[] { "item" }); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Failed_legacy_metadata_does_not_block_strict_item_on_matching_endpoint(bool malformed) + { + var first = new FailoverHandler("a", true, generation: 1); + var second = new FailoverHandler("b", false, generation: 2, metadataFailure: !malformed, badMetadata: malformed); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), + 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); + using var legacy = DataValue.FromScalar(DataValueKind.Int32, 1); + using var strict = DataValue.FromScalar(DataValueKind.Int32, 2); + var result = await connection.WriteAsync(new([ + new("retry", "legacy", View, legacy, 1, "boot", TimeSpan.FromSeconds(4)), + new("strict", "strict", View, strict, 1, "boot", TimeSpan.FromSeconds(4), 2)], Budget), TestContext.Current.CancellationToken); + result.Select(x => x.Outcome.State).ShouldBe([DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedSuccess]); + first.WrittenIds.ShouldBe(new[] { "retry" }); + second.WrittenIds.ShouldBe(new[] { "strict" }); + } + + [Fact] + public async Task Failed_legacy_metadata_preserves_strict_item_for_a_later_matching_endpoint() + { + var first = new FailoverHandler("a", true, generation: 1); + var second = new FailoverHandler("b", false, generation: 2, metadataFailure: true); + var third = new FailoverHandler("c", false, generation: 3, metadataFailure: true); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test"), new Uri("https://c.test")], new TripleSecurity(first, second, third), manager.Acquire("link"), + 65536, 3, eligibleNodeIds: new HashSet { "a", "b", "c" }); + using var legacy = DataValue.FromScalar(DataValueKind.Int32, 1); + using var strict = DataValue.FromScalar(DataValueKind.Int32, 2); + var result = await connection.WriteAsync(new([ + new("retry", "legacy", View, legacy, 1, "boot", TimeSpan.FromSeconds(4)), + new("strict", "strict", View, strict, 1, "boot", TimeSpan.FromSeconds(4), 3)], Budget), TestContext.Current.CancellationToken); + result.Select(x => x.Outcome.State).ShouldBe([DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedSuccess]); + first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBeEmpty(); + third.WrittenIds.ShouldBe(new[] { "strict" }); + } + + [Fact] + public async Task Strict_generation_rejection_is_not_rebound_to_another_primary() + { + var first = new FailoverHandler("a", true); + var second = new FailoverHandler("b", false); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"), + 65536, 2, eligibleNodeIds: new HashSet { "a", "b" }); + using var value = DataValue.FromScalar(DataValueKind.Int32, 1); + var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + first.WrittenIds.ShouldBe(new[] { "retry" }); second.WrittenIds.ShouldBeEmpty(); + } + + [Fact] + public async Task Legacy_peer_remains_readable_but_does_not_advertise_writable_metadata() + { + var handler = new WireHandler { NoWriteGenerationEnforcement = true }; + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + var caps = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); + (caps.Operations & DataOperations.Read).ShouldBe(DataOperations.Read); + (caps.Operations & DataOperations.Write).ShouldBe(DataOperations.None); + var branch = await connection.BrowseAsync(new(View, null, null, Budget), TestContext.Current.CancellationToken); + branch.Items.ShouldHaveSingleItem().Writable.ShouldBeFalse(); + (branch.Items[0].AllowedOperations & DataOperations.Write).ShouldBe(DataOperations.None); + var metadata = await connection.GetMetadataAsync(new([View], Budget), TestContext.Current.CancellationToken); + metadata.ShouldHaveSingleItem().Value!.Writable.ShouldBeFalse(); + (metadata[0].Value!.AllowedOperations & DataOperations.Write).ShouldBe(DataOperations.None); + } + + [Fact] + public async Task Peer_without_generation_enforcement_is_never_sent_a_write() + { + var handler = new WireHandler { NoWriteGenerationEnforcement = true, LoseWrite = true }; + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"), + [new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var result = await connection.WriteAsync(new([new("item", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + handler.WriteCalls.ShouldBe(0); + } + [Fact] public async Task Lost_write_reply_is_unknown_and_is_not_resent() { @@ -207,25 +333,35 @@ public sealed class GrpcDataConnectionClientTests public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("v1", "ca1", "key", () => endpoint.Host == "a.test" ? first : second)); } - private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null) : HttpMessageHandler + private sealed class TripleSecurity(FailoverHandler first, FailoverHandler second, FailoverHandler third) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca1", "key", () => endpoint.Host switch + { "a.test" => first, "b.test" => second, _ => third })); + } + private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null, + long generation = 1, bool unavailable = false, bool metadataFailure = false, bool badMetadata = false) : HttpMessageHandler { public List WrittenIds { get; } = []; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, 1); + var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, generation); IMessage message; if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) { onCapabilities?.Invoke(); - message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, serving, DataReadiness.Ready, + if (unavailable) throw new HttpRequestException("unavailable"); + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, serving, DataReadiness.Ready, DataOperations.Read | DataOperations.Write | DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, - Limits, false, 0, "c", false, true)); + Limits, false, 0, "c", false, true, true)); } else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) { onMetadata?.Invoke(); + if (metadataFailure) throw new HttpRequestException("metadata unavailable"); var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write, - 2, null, null, false); + badMetadata ? 2 : 1, null, null, false); var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]); wire.Serving = DataProtoMapper.EncodeServing(serving); message = wire; } @@ -751,6 +887,7 @@ public sealed class GrpcDataConnectionClientTests private sealed class WireHandler : HttpMessageHandler { public bool LoseWrite { get; init; } + public bool NoWriteGenerationEnforcement { get; init; } public bool WrongReadServing { get; init; } public bool ZeroServingGeneration { get; init; } public bool BadBrowseLease { get; init; } @@ -759,9 +896,9 @@ public sealed class GrpcDataConnectionClientTests { IMessage message; if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) - message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready, - DataOperations.Read | DataOperations.Write, new HashSet { DataValueKind.Int32 }, Limits, - false, 0, "c", false, true)); + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, NoWriteGenerationEnforcement ? 2 : 3, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Write | DataOperations.Browse | DataOperations.Metadata, new HashSet { DataValueKind.Int32 }, Limits, + false, 0, "c", false, true, !NoWriteGenerationEnforcement)); else if (request.RequestUri.AbsolutePath.EndsWith("/Write", StringComparison.Ordinal)) { WriteCalls++; @@ -770,10 +907,17 @@ public sealed class GrpcDataConnectionClientTests } else if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal)) { - var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, [], true, null, + var children = NoWriteGenerationEnforcement ? new[] { new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false) } : []; + var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, children, true, null, new MetadataLease(Serving.CatalogEpoch, BadBrowseLease ? Serving.AuthorityEpoch + 1 : Serving.AuthorityEpoch, TimeSpan.FromSeconds(1)))); browse.Serving = DataProtoMapper.EncodeServing(Serving); message = browse; } + else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) + { + var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Read | DataOperations.Write, 1, null, null, false); + var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]); + wire.Serving = DataProtoMapper.EncodeServing(Serving); message = wire; + } else if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal)) message = new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(WrongReadServing ? Serving with { Incarnation = "other" } : Serving) }; else throw new InvalidOperationException("Unexpected call."); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataContinuationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataContinuationTests.cs new file mode 100644 index 000000000..956690bce --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataContinuationTests.cs @@ -0,0 +1,56 @@ +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("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataContinuationTests +{ + [Fact] + public void Cursor_is_bound_to_caller_mapping_parent_filter_and_full_remote_generation() + { + var clock = new ManualTimeProvider(); var registry = new BrowseContinuationRegistry(4, clock); + var binding = Binding(); var token = registry.Issue(binding, "peer-secret-cursor", TimeSpan.FromSeconds(15)); + token.ShouldNotContain("peer-secret-cursor"); + registry.TryPrepare(token, binding with { PrincipalId = "other" }, out _).ShouldBeFalse(); + registry.TryPrepare(token, binding with { Filter = "different" }, out _).ShouldBeFalse(); + registry.TryPrepare(token, binding with { MappingRevision = 2 }, out _).ShouldBeFalse(); + registry.TryPrepare(token, binding with { RemoteServing = binding.RemoteServing with { ServingGeneration = 2 } }, out _).ShouldBeFalse(); + registry.TryPrepare(token, binding, out var prepared).ShouldBeTrue(); + prepared.ShouldNotBeNull().RemoteCursor.ShouldBe("peer-secret-cursor"); + prepared.Dispose(); + registry.TryPrepare(token, binding, out var retry).ShouldBeTrue(); + retry.ShouldNotBeNull().TryCommit(nextPeerCursor: null, out _).ShouldBeTrue(); + registry.TryPrepare(token, binding, out _).ShouldBeFalse(); + } + + [Fact] + public void Expired_or_capacity_exhausted_handles_fail_closed() + { + var clock = new ManualTimeProvider(); var registry = new BrowseContinuationRegistry(1, clock); + var binding = Binding(); var token = registry.Issue(binding, "cursor", TimeSpan.FromSeconds(1)); + Should.Throw(() => registry.Issue(binding, "second", TimeSpan.FromSeconds(1))); + clock.Advance(TimeSpan.FromSeconds(2)); + registry.TryPrepare(token, binding, out _).ShouldBeFalse(); + registry.Issue(binding, "replacement", TimeSpan.FromSeconds(1)).ShouldNotBeNullOrWhiteSpace(); + } + + [Fact] + public void Invalidation_between_prepare_and_commit_cannot_publish_a_stale_cursor() + { + var registry = new BrowseContinuationRegistry(1, new ManualTimeProvider()); + var binding = Binding(); var token = registry.Issue(binding, "old", TimeSpan.FromSeconds(10)); + registry.TryPrepare(token, binding, out var prepared).ShouldBeTrue(); + registry.InvalidateMapping(binding.MappingId); + prepared!.TryCommit("new", out var next).ShouldBeFalse(); + next.ShouldBeNull(); + registry.TryPrepare(token, binding, out _).ShouldBeFalse(); + } + + private static BrowseContinuationBinding Binding() => new("peer", "key", "credential", "mapping", 1, + new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"), + null, 4, new ServingIdentity("node", "boot", "Primary", 8, 9, 1)); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs new file mode 100644 index 000000000..d492cfba2 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataFederatedBrowseTests.cs @@ -0,0 +1,583 @@ +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using Shouldly; +using Xunit; +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.Tests.Harness; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataFederatedBrowseTests +{ + [Fact] + public void Missing_or_unavailable_parent_is_not_reported_as_a_successful_empty_branch() + { + var clock = new ManualTimeProvider(); var cache = new ProjectedCatalogCache(4, 8, clock); + var request = Request(clock); + var pending = cache.TryGetParent(request); + pending.Status.ShouldBe(ProjectionPageStatus.Pending); + pending.Complete.ShouldBeFalse(); + cache.MarkUnavailable(request.MappingId, request.Parent); + var unavailable = cache.TryGetParent(request); + unavailable.Status.ShouldBe(ProjectionPageStatus.Unavailable); + unavailable.Complete.ShouldBeFalse(); + } + + [Fact] + public void Unknown_projected_identity_fails_closed_instead_of_becoming_local() + { + var clock = new ManualTimeProvider(); var cache = new ProjectedCatalogCache(4, 8, clock); + cache.TryResolveProjected(DataRealm.Raw, "unknown", out var proof).ShouldBeFalse(); + proof.ShouldBeNull(); + } + + [Fact] + public void Empty_complete_page_expires_with_its_authority_lease() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; + cache.CaptureGeneration(request.MappingId).ShouldBe(1); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), + fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); + var local = fixture.Activation.CaptureAuthority(); + var page = new ProjectedParentSnapshot(ProjectionPageStatus.Ready, [], true, null, 1, + Lease: lease, LocalAuthority: local, ParentProof: ParentProof(fixture, request, lease, local)); + cache.TryPublish(request, page).ShouldBeTrue(); + cache.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Ready); + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + cache.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Unavailable); + } + + [Fact] + public void Invalidated_pinned_metadata_stays_charged_until_last_pin_is_released() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 1, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; + cache.CaptureGeneration(request.MappingId).ShouldBe(1); + var local = fixture.Activation.CaptureAuthority(); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, fixture.Clock); + ProjectedNodeProof Proof(string id, string identifier, long generation = 1) + { + var view = new DataView(new DataAddress("origin", "urn:raw", "string", identifier), DataRealm.Raw, "mapping", 1, "Plant/branch/" + id); + var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch", id] }; + var subject = new MappedNamespaceSubject(view, scope, ["folder"], lease.Serving, DataOperations.Browse); + var resolver = new MappedSubjectResolver([subject], fixture.Serving.CatalogEpoch, local); + var metadata = new DataMetadata(view, id, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving); + var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/" + id } }; + return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin); + } + var first = Proof("first", "first"); + first.OriginMetadata.View.Subject.ShouldBe("origin/first"); + first.OriginMetadata.View.MappingId.ShouldBeNull(); + first.Metadata.View.MappingId.ShouldBe("mapping"); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [first], true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeTrue(); + cache.TryPinProjected(DataRealm.Raw, first.LocalIdentifier, out var pin).ShouldBeTrue(); + cache.MarkUnavailable(request.MappingId, request.Parent); + cache.TryResolveProjected(DataRealm.Raw, first.LocalIdentifier, out _).ShouldBeFalse(); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [Proof("second", "second", 2)], true, null, 2, lease, local, ParentProof(fixture, request, lease, local, 2))).ShouldBeFalse(); + pin!.Dispose(); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [Proof("second", "second", 2)], true, null, 2, lease, local, ParentProof(fixture, request, lease, local, 2))).ShouldBeTrue(); + } + + [Fact] + public void Empty_page_still_consumes_the_aggregate_metadata_byte_budget() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 128); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; + cache.CaptureGeneration(request.MappingId); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); + var local = fixture.Activation.CaptureAuthority(); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, ParentProof(fixture, request, lease, local))).ShouldBeFalse(); + } + + [Fact] + public void Empty_page_cannot_bypass_local_parent_browse_authorization() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); + var local = fixture.Activation.CaptureAuthority(); + var denied = ParentProof(fixture, request, lease, local, forbidden: true); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, denied)).ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Prepared_remote_page_keeps_origin_subject_and_publishes_only_after_commit() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); + var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + using var resolver = new RemoteNamespaceResolver(cache, new BrowseContinuationRegistry(8, fixture.Clock), source, policy, 4, 8); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; + var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection", + Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, BranchName = "branch", RemoteRootEntityId = "root", + RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "plant", AllowedOperations = DataOperations.Browse }; + resolver.ApplyMappings([new ProjectedMappingBinding(mapping, request.Parent, + new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch"] }, + ["folder"], fixture.Activation.CaptureAuthority(), (_, _) => false)]); + using var prepared = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + prepared.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + resolver.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Pending); + var item = prepared.Snapshot.Items.ShouldHaveSingleItem(); + item.OriginMetadata.View.Subject.ShouldBe("origin/child"); + item.OriginMetadata.View.MappingId.ShouldBeNull(); + item.Metadata.View.MappingId.ShouldBe("mapping"); + prepared.TryCommit().ShouldBeTrue(); + resolver.TryGetParent(request).Status.ShouldBe(ProjectionPageStatus.Ready); + resolver.TryResolveProjected(DataRealm.Raw, item.LocalIdentifier, out var live).ShouldBeTrue(); + live.ShouldNotBeNull().OriginMetadata.View.Subject.ShouldBe("origin/child"); + } + + [Fact(Timeout = 30000)] + public async Task Concurrent_identical_browse_waiters_share_one_bounded_origin_fetch() + { + using var fixture = new LocalDataFixture(); + var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true; + using var resolver = CreateResolver(fixture, source, out var request); + var ct = TestContext.Current.CancellationToken; + using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct); + Task? firstTask = null, secondTask = null; + try + { + firstTask = resolver.PreparePageAsync(request, stop.Token); + await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + secondTask = resolver.PreparePageAsync(request, stop.Token); + source.Connection.ReleaseBrowse.TrySetResult(); + using var first = await firstTask.WaitAsync(TimeSpan.FromSeconds(5), ct); + using var second = await secondTask.WaitAsync(TimeSpan.FromSeconds(5), ct); + first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + second.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + source.Connection.BrowseCalls.ShouldBe(1); + first.TryCommit().ShouldBeTrue(); + second.TryCommit().ShouldBeTrue(); + } + finally + { + source.Connection.ReleaseBrowse.TrySetResult(); stop.Cancel(); + await DrainAsync(firstTask); await DrainAsync(secondTask); + } + } + + [Fact(Timeout = 30000)] + public async Task Retiring_mapping_before_commit_fences_the_prepared_page() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + using var resolver = CreateResolver(fixture, source, out var request); + using var prepared = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + prepared.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + resolver.ApplyMappings([]); + prepared.TryCommit().ShouldBeFalse(); + resolver.TryResolveProjected(DataRealm.Raw, prepared.Snapshot.Items[0].LocalIdentifier, out _).ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Cancelling_one_shared_waiter_does_not_cancel_the_other() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); source.Connection.BlockBrowse = true; + using var resolver = CreateResolver(fixture, source, out var request); + using var cancelFirst = new CancellationTokenSource(); var ct = TestContext.Current.CancellationToken; + Task? first = null, second = null; + try + { + first = resolver.PreparePageAsync(request, cancelFirst.Token); + await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + second = resolver.PreparePageAsync(request, ct); + cancelFirst.Cancel(); + await Assert.ThrowsAnyAsync(async () => await first.WaitAsync(TimeSpan.FromSeconds(5), ct)); + source.Connection.ReleaseBrowse.TrySetResult(); + using var result = await second.WaitAsync(TimeSpan.FromSeconds(5), ct); + result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + source.Connection.BrowseCalls.ShouldBe(1); + } + finally { source.Connection.ReleaseBrowse.TrySetResult(); cancelFirst.Cancel(); await DrainAsync(first); await DrainAsync(second); } + } + + [Fact(Timeout = 30000)] + public async Task Last_cancelled_waiter_keeps_physical_capacity_until_peer_finishes() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + source.Connection.BlockBrowse = true; source.Connection.IgnoreCancellation = true; + using var resolver = CreateResolver(fixture, source, out var request); + using var cancel = new CancellationTokenSource(); var ct = TestContext.Current.CancellationToken; + Task? first = null; + try + { + first = resolver.PreparePageAsync(request, cancel.Token); + await source.Connection.BrowseEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + cancel.Cancel(); + await Assert.ThrowsAnyAsync(async () => await first.WaitAsync(TimeSpan.FromSeconds(5), ct)); + using (var blocked = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct)) + blocked.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable); + source.Connection.BrowseCalls.ShouldBe(1); + source.Connection.ReleaseBrowse.TrySetResult(); + await source.LeaseDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); + using var after = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + after.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + } + finally { source.Connection.ReleaseBrowse.TrySetResult(); cancel.Cancel(); await DrainAsync(first); } + } + + [Fact(Timeout = 30000)] + public async Task Duplicate_sibling_across_pages_is_rejected_without_consuming_the_cursor() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + source.Connection.DuplicateSecondPage = true; + using var resolver = CreateResolver(fixture, source, out var request); var ct = TestContext.Current.CancellationToken; + using var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + first.Snapshot.Complete.ShouldBeFalse(); first.TryCommit().ShouldBeTrue(); + var next = first.Snapshot.Continuation.ShouldNotBeNull(); + var followup = request with { Continuation = next }; + using var second = await resolver.PreparePageAsync(followup, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + second.TryCommit().ShouldBeFalse(); + using var retry = await resolver.PreparePageAsync(followup, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + retry.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + } + + [Fact(Timeout = 30000)] + public async Task Unversioned_remote_serving_generation_cannot_authorize_a_projection() + { + using var fixture = new LocalDataFixture(); + var source = new FakeProjectionSource(fixture.Clock, fixture.Serving with { ServingGeneration = 0 }, preserveGeneration: true); + using var resolver = CreateResolver(fixture, source, out var request); + using var result = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable); + } + + [Fact] + public void Expired_unpinned_pages_and_nodes_are_reclaimed_for_new_work() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(1, 1, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); + var local = fixture.Activation.CaptureAuthority(); + MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); + var firstLease = Lease(); var first = ParentProof(fixture, request, firstLease, local); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [first], true, null, 1, firstLease, local, first)).ShouldBeTrue(); + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + var secondRequest = request with { Filter = "new-filter" }; var secondLease = Lease(); var second = ParentProof(fixture, secondRequest, secondLease, local); + cache.TryPublish(secondRequest, new(ProjectionPageStatus.Ready, [second], true, null, 1, secondLease, local, second)).ShouldBeTrue(); + cache.TryGetParent(secondRequest).Status.ShouldBe(ProjectionPageStatus.Ready); + } + + [Fact] + public void Pinned_expired_proof_does_not_prevent_current_identical_placement_from_renewing() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(2, 2, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); + var local = fixture.Activation.CaptureAuthority(); + MetadataAuthorityLease Lease() => new(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(1)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(1), TimeSpan.Zero, fixture.Clock); + var oldLease = Lease(); var old = ParentProof(fixture, request, oldLease, local); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [old], true, null, 1, oldLease, local, old)).ShouldBeTrue(); + cache.TryPinProjected(DataRealm.Raw, old.LocalIdentifier, out var pin).ShouldBeTrue(); + try + { + fixture.Clock.Advance(TimeSpan.FromSeconds(2)); + var renewedLease = Lease(); var renewed = ParentProof(fixture, request, renewedLease, local); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [renewed], true, null, 1, renewedLease, local, renewed)).ShouldBeTrue(); + cache.TryResolveProjected(DataRealm.Raw, old.LocalIdentifier, out var current).ShouldBeTrue(); + current.ShouldNotBeNull().Lease.ShouldBeSameAs(renewedLease); + } + finally { pin!.Dispose(); } + } + + [Fact] + public void Parent_filter_and_caller_identifiers_are_charged_to_byte_budget() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 4096); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller, Filter = new string('x', 5000) }; cache.CaptureGeneration("mapping"); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); + var local = fixture.Activation.CaptureAuthority(); var parent = ParentProof(fixture, request, lease, local); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [], true, null, 1, lease, local, parent)).ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Projection_depth_is_relative_to_mapping_anchor_not_local_scope_depth() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + using var resolver = CreateResolver(fixture, source, out var request, maximumDepth: 1); + using var result = await resolver.PreparePageAsync(request, TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + result.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + result.TryCommit().ShouldBeTrue(); + } + + [Fact(Timeout = 30000)] + public async Task Mapping_node_limit_applies_across_continuation_pages() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + source.Connection.DistinctSecondPage = true; + using var resolver = CreateResolver(fixture, source, out var request, maximumNodes: 1); + var ct = TestContext.Current.CancellationToken; + using var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); first.TryCommit().ShouldBeTrue(); + var next = first.Snapshot.Continuation.ShouldNotBeNull(); + using var second = await resolver.PreparePageAsync(request with { Continuation = next }, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + (second.Snapshot.Status != ProjectionPageStatus.Ready || !second.TryCommit()).ShouldBeTrue(); + } + + [Fact(Timeout = 30000)] + public async Task Cancelled_queued_fetches_remain_bounded_until_physical_work_finishes() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var entered = new SemaphoreSlim(0); + Task BeforeFetch(CancellationToken _) { entered.Release(); return gate.Task; } + using var resolver = CreateResolver(fixture, source, out var request, beforeFetch: BeforeFetch); + var ct = TestContext.Current.CancellationToken; + try + { + for (var i = 0; i < 16; i++) + { + using var cancel = new CancellationTokenSource(); + var task = resolver.PreparePageAsync(request with { Filter = i.ToString() }, cancel.Token); + (await entered.WaitAsync(TimeSpan.FromSeconds(5), ct)).ShouldBeTrue(); + cancel.Cancel(); + await Assert.ThrowsAnyAsync(async () => await task.WaitAsync(TimeSpan.FromSeconds(5), ct)); + } + resolver.OutstandingPhysicalJobs.ShouldBe(16); + using var rejected = await resolver.PreparePageAsync(request with { Filter = "overflow" }, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + rejected.Snapshot.Status.ShouldBe(ProjectionPageStatus.Unavailable); + resolver.OutstandingPhysicalJobs.ShouldBe(16); + } + finally { gate.TrySetResult(); } + await resolver.WaitForPhysicalJobsAsync().WaitAsync(TimeSpan.FromSeconds(5), ct); + resolver.OutstandingPhysicalJobs.ShouldBe(0); + using var recovered = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + recovered.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + } + + [Fact] + public void Publishing_a_fresh_page_does_not_revalidate_unrelated_live_pages() + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(8, 8, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; cache.CaptureGeneration("mapping"); + var local = fixture.Activation.CaptureAuthority(); + var inner = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); + var tracked = new CountingLease(inner); var parent = ParentProof(fixture, request, tracked, local); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, [parent], true, null, 1, tracked, local, parent)).ShouldBeTrue(); + tracked.Reads = 0; + var other = request with { Filter = "another-query" }; var otherParent = ParentProof(fixture, other, inner, local); + cache.TryPublish(other, new(ProjectionPageStatus.Ready, [], true, null, 1, inner, local, otherParent)).ShouldBeTrue(); + tracked.Reads.ShouldBe(0); + } + + [Fact] + public void Captured_page_validity_does_not_revisit_siblings_for_each_returned_name() + { + using var fixture = new LocalDataFixture(); + var (cache, request, tracked) = LargeGuardPage(fixture); + var page = cache.TryGetParent(request); + var guard = cache.CaptureParentGuard(request, page).ShouldNotBeNull(); + tracked.Reads = 0; + for (var i = 0; i < 200; i++) guard.IsCurrent.ShouldBeTrue(); + tracked.Reads.ShouldBe(0, "per-child emission checks must not authorize the other 199 siblings again"); + cache.MarkUnavailable(request.MappingId, request.Parent); + guard.IsCurrent.ShouldBeFalse(); + } + + [Fact] + public void Captured_page_guard_does_not_keep_a_retired_page_graph_alive() + { + using var fixture = new LocalDataFixture(); + var (cache, request, _) = LargeGuardPage(fixture); + var (guard, weak) = Capture(cache, request); + cache.MarkUnavailable(request.MappingId, request.Parent); + GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); + weak.IsAlive.ShouldBeFalse("a cursor guard owns its detached control proof, not the retired page graph"); + guard.IsCurrent.ShouldBeFalse(); + GC.KeepAlive(guard); + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + static (IProjectedPageGuard Guard, WeakReference Page) Capture(ProjectedCatalogCache cache, ProjectedBrowseRequest request) + { + var page = cache.TryGetParent(request); + return (cache.CaptureParentGuard(request, page).ShouldNotBeNull(), new WeakReference(page)); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Oversized_origin_metadata_is_charged_for_parent_and_child_proofs(bool child) + { + using var fixture = new LocalDataFixture(); + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy, maxBytes: 32768); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller }; + cache.CaptureGeneration(request.MappingId); + var local = fixture.Activation.CaptureAuthority(); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), + fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); + var parent = ParentProof(fixture, request, lease, local); + var large = parent with { OriginMetadata = parent.OriginMetadata with { StableSourceId = new string('x', 32768), EngineeringUnits = new string('u', 32768) } }; + cache.TryPublish(request, new(ProjectionPageStatus.Ready, child ? [large] : [], true, null, 1, lease, local, child ? parent : large)).ShouldBeFalse(); + } + + private static (ProjectedCatalogCache Cache, ProjectedBrowseRequest Request, CountingLease Tracked) LargeGuardPage(LocalDataFixture fixture) + { + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 512, fixture.Clock, policy); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + var request = Request(fixture.Clock) with { Caller = caller, Budget = new DataBudget(TimeSpan.FromSeconds(3), 256, 1_000_000) }; + cache.CaptureGeneration("mapping"); + var local = fixture.Activation.CaptureAuthority(); + var lease = new MetadataAuthorityLease(fixture.Serving with { ServingGeneration = 1 }, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), + fixture.Clock.GetTimestamp(), TimeSpan.FromSeconds(10), TimeSpan.Zero, fixture.Clock); + var tracked = new CountingLease(lease); + var children = Enumerable.Range(0, 200).Select(index => + { + var id = "child" + index; + var view = request.Parent with { Address = request.Parent.Address with { Identifier = id }, Subject = "local/anchor/" + id }; + var subject = new MappedNamespaceSubject(view, + new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", id] }, ["folder"], lease.Serving, DataOperations.Browse); + var metadata = new DataMetadata(view, id, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving); + var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/" + id } }; + return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, + new MappedSubjectResolver([subject], 1, local), tracked, 1, origin); + }).ToArray(); + cache.TryPublish(request, new(ProjectionPageStatus.Ready, children, true, null, 1, lease, local, + ParentProof(fixture, request, lease, local))).ShouldBeTrue(); + return (cache, request, tracked); + } + + private sealed class CountingLease(IDataAuthorizationLease inner) : IDataAuthorizationLease + { + public int Reads { get; set; } + public bool IsValid { get { Reads++; return inner.IsValid; } } + public ServingIdentity Serving => inner.Serving; + } + + [Fact(Timeout = 30000)] + public async Task Per_mapping_limit_reclaims_expired_nodes_even_when_global_capacity_is_available() + { + using var fixture = new LocalDataFixture(); var source = new FakeProjectionSource(fixture.Clock, fixture.Serving); + source.Connection.DistinctFiltered = true; + using var resolver = CreateResolver(fixture, source, out var request, maximumNodes: 1); + var ct = TestContext.Current.CancellationToken; + using (var first = await resolver.PreparePageAsync(request, ct).WaitAsync(TimeSpan.FromSeconds(5), ct)) + { first.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); first.TryCommit().ShouldBeTrue(); } + fixture.Clock.Advance(TimeSpan.FromSeconds(11)); + var next = request with { Filter = "other", RequestStartedTimestamp = fixture.Clock.GetTimestamp() }; + using var second = await resolver.PreparePageAsync(next, ct).WaitAsync(TimeSpan.FromSeconds(5), ct); + second.Snapshot.Status.ShouldBe(ProjectionPageStatus.Ready); + second.TryCommit().ShouldBeTrue(); + } + + private static async Task DrainAsync(Task? task) + { + if (task is null) return; + try { (await task.WaitAsync(TimeSpan.FromSeconds(5))).Dispose(); } + catch (Exception ex) when (ex is OperationCanceledException or TimeoutException or InvalidOperationException) { } + } + + private static RemoteNamespaceResolver CreateResolver(LocalDataFixture fixture, IGrpcDataAdapterConnectionSource source, out ProjectedBrowseRequest request, int? maximumDepth = null, int? maximumNodes = null, Func? beforeFetch = null) + { + var policy = new DataOperationPolicy(fixture.Authority, new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock); + var cache = new ProjectedCatalogCache(4, 8, fixture.Clock, policy); + var resolver = new RemoteNamespaceResolver(cache, new BrowseContinuationRegistry(8, fixture.Clock), source, policy, 4, 1, beforeFetch); + var caller = new DataCallerIdentity(fixture.Context.PrincipalId, fixture.Context.ApiKeyId, fixture.Context.CredentialVersion, fixture.Context.CredentialExpiresUtc); + request = Request(fixture.Clock) with { Caller = caller }; + var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mapping", ClusterId = "cluster", DataConnectionId = "connection", + Revision = 1, Enabled = true, Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, BranchName = "branch", RemoteRootEntityId = "root", + RemoteNamespaceUri = "urn:raw", RemoteIdentifierKind = "string", RemoteIdentifier = "plant", AllowedOperations = DataOperations.Browse }; + if (maximumDepth is { } depth) mapping.MaxProjectionDepth = depth; + if (maximumNodes is { } nodes) mapping.MaxProjectionNodes = nodes; + resolver.ApplyMappings([new ProjectedMappingBinding(mapping, request.Parent, + new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch"] }, + ["folder"], fixture.Activation.CaptureAuthority(), (_, _) => false)]); + return resolver; + } + + private sealed class FakeProjectionSource(TimeProvider clock, ServingIdentity serving, bool preserveGeneration = false) : IGrpcDataAdapterConnectionSource + { + public FakeProjectionConnection Connection { get; } = new(clock, !preserveGeneration && serving.ServingGeneration == 0 ? serving with { ServingGeneration = 1 } : serving); + public TaskCompletionSource LeaseDisposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) => + ValueTask.FromResult(new FakeProjectionLease(Connection, () => LeaseDisposed.TrySetResult())); + } + private sealed class FakeProjectionLease(IDataConnection connection, Action released) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public ValueTask DisposeAsync() { released(); return ValueTask.CompletedTask; } + } + private sealed class FakeProjectionConnection(TimeProvider clock, ServingIdentity serving) : IDataConnection + { + public DataTarget Target => new(DataTargetMode.Node, "origin", "remote"); + public TimeProvider Clock => clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { + var root = request.Views[0] with { Subject = "origin/root" }; + var metadata = new DataMetadata(root, "root", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: serving); + return Task.FromResult>>([new("0", DataItemStatus.Good, metadata, null)]); + } + public bool BlockBrowse { get; set; } + public bool IgnoreCancellation { get; set; } + public bool DuplicateSecondPage { get; set; } + public bool DistinctSecondPage { get; set; } + public bool DistinctFiltered { get; set; } + public TaskCompletionSource BrowseEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource ReleaseBrowse { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _browseCalls; + public int BrowseCalls => Volatile.Read(ref _browseCalls); + public async Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _browseCalls); BrowseEntered.TrySetResult(); + if (BlockBrowse) await ReleaseBrowse.Task.WaitAsync(TimeSpan.FromSeconds(5), IgnoreCancellation ? CancellationToken.None : cancellationToken); + var id = ((DuplicateSecondPage || DistinctSecondPage) && request.Continuation is not null || DistinctFiltered && request.Filter is not null) ? "plant/other-child" : "plant/child"; + var child = new DataView(new DataAddress("origin", "urn:raw", "string", id), DataRealm.Raw, null, 0, "origin/child"); + var metadata = new DataMetadata(child, (DistinctSecondPage && request.Continuation is not null || DistinctFiltered && request.Filter is not null) ? "other" : "child", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: serving); + var continuation = (DuplicateSecondPage || DistinctSecondPage) && request.Continuation is null ? "peer-next" : null; + return new DataBrowseBranch(request.Parent, DataItemStatus.Good, [metadata], continuation is null, continuation, new MetadataLease(1, 1, TimeSpan.FromSeconds(10)), serving); + } + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task SubscribeAsync(CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private static ProjectedNodeProof ParentProof(LocalDataFixture fixture, ProjectedBrowseRequest request, + IDataAuthorizationLease lease, IDataMappedCatalogAuthority local, long generation = 1, bool forbidden = false) + { + var view = request.Parent; + var scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = [forbidden ? "Forbidden" : "Plant"] }; + var subject = new MappedNamespaceSubject(view, scope, ["folder"], lease.Serving, DataOperations.Browse); + var resolver = new MappedSubjectResolver([subject], fixture.Serving.CatalogEpoch, local); + var metadata = new DataMetadata(view, "branch", "Folder", DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false, Serving: lease.Serving); + var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/plant" } }; + return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, lease, generation, origin); + } + + private static ProjectedBrowseRequest Request(TimeProvider clock) => new("mapping", + new DataView(new DataAddress("origin", "urn:raw", "string", "plant"), DataRealm.Raw, "mapping", 1, "local/anchor"), + null, null, new DataCallerIdentity("peer", "key", "credential", null), + new DataBudget(TimeSpan.FromSeconds(3), 20, 10000), clock.GetTimestamp()); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs index 529408bd2..16248c99b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataLocalConnectionTests.cs @@ -20,6 +20,8 @@ public sealed class GrpcDataLocalConnectionTests await using var connection = fixture.Services.Create(context, new(DataTargetMode.Node, "cluster", "node-a")); var budget = LocalDataFixture.Budget with { MaxItems = 1 }; var branch = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken); + branch.Serving.ShouldNotBeNull(); + branch.Items.ShouldAllBe(x => x.Serving == branch.Serving); branch.Status.ShouldBe(DataItemStatus.Good); branch.Lease!.Duration.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1)); branch.Continuation.ShouldNotBeNull(); @@ -127,15 +129,16 @@ internal sealed class LocalDataFixture : IDisposable internal LocalDataFixture(int additionalRawNodes = 0, Func? subscriptions = null, Func? targetSubscriptions = null, - bool advanceAuthority = false, string role = "Primary") + bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false) { - Serving = Serving with { Role = role }; + Serving = Serving with { Role = role, ServingGeneration = servingGeneration }; Hub = HubTest.Create(clock: Clock, bytes: 1_000_000); Hub.TryBind(Ticket).ShouldBeTrue(); var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true }; Authority.Apply("cluster", "first", [key], - [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder, - ScopeId = "folder", PermissionFlags = NodePermissions.ReadOnly }], + [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", + ScopeKind = nestedUnsCatalog ? NodeAclScopeKind.Cluster : NodeAclScopeKind.RawFolder, + ScopeId = nestedUnsCatalog ? null : "folder", PermissionFlags = NodePermissions.ReadOnly }], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); if (advanceAuthority) { @@ -153,10 +156,24 @@ internal sealed class LocalDataFixture : IDisposable var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false); var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false); var unsMetadata = rawMetadata with { View = Uns }; + var folder = Root with { Address = Root.Address with { Identifier = "Plant/Driver" }, Subject = "Plant/Driver" }; + var unsRoot = Uns with { Address = Uns.Address with { Identifier = "Area" }, Subject = "Area" }; var nodes = new List {new("RawFolder", "folder", rootMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant"] }, null, null), - new("RawTag", "tag", rawMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed"] }, Root, Ticket.Key), - new("UnsTagReference", "reference", unsMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area", "Line", "Equipment", "Speed"] }, null, Ticket.Key)}; + new("RawTag", "tag", rawMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed"] }, nestedCatalog ? folder : Root, Ticket.Key), + new("UnsTagReference", "reference", unsMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area", "Line", "Equipment", "Speed"] }, nestedUnsCatalog ? unsRoot : null, Ticket.Key)}; + if (nestedUnsCatalog) + nodes.Add(new("UnsArea", "area", rootMetadata with { View = unsRoot, BrowseName = "Area" }, + new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area"] }, null, null)); + if (nestedCatalog) + { + nodes.Add(new("RawFolder", "nested-folder", rootMetadata with { View = folder, BrowseName = "Driver" }, + new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver"] }, Root, null)); + var array = Raw with { Address = Raw.Address with { Identifier = "Plant/Driver/Array" }, Subject = "Plant/Driver/Array" }; + nodes.Add(new("RawTag", "array", rawMetadata with { View = array, BrowseName = "Array", ValueKind = DataValueKind.Array, + ValueRank = 1, Dimensions = [3], ArrayElementKind = DataValueKind.UInt8 }, + new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Array"] }, folder, Ticket.Key)); + } for (var i = 0; i < additionalRawNodes; i++) { var view = Raw with { Address = Raw.Address with { Identifier = Raw.Address.Identifier + i }, Subject = Raw.Subject + i }; @@ -165,7 +182,7 @@ internal sealed class LocalDataFixture : IDisposable } Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes, [new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }, - new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "UnsTagReference", RootEntityId = "reference", PrincipalId = "peer", AllowedOperations = operations }]); + new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]); 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", () => Serving, () => Catalog.IsActive, limits); Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs new file mode 100644 index 000000000..627147beb --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedAccessTests.cs @@ -0,0 +1,501 @@ +using Opc.Ua; +using System.Threading.Channels; +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.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataProjectedAccessTests +{ + [Fact] + public void Acquisition_pins_the_exact_materialized_origin_and_disposal_fences_it() + { + using var fixture = new AccessFixture(); + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + demand.ShouldNotBeNull().OriginView.ShouldBe(fixture.Proof.OriginMetadata.View); + demand.MaximumSampleAge.ShouldBe(TimeSpan.FromSeconds(30)); + access.HasLiveDemand(DataRealm.Raw, fixture.Proof.LocalIdentifier).ShouldBeTrue(); + demand.Serving.ShouldBe(fixture.Proof.Lease.Serving); + demand.ProjectionGeneration.ShouldBe(fixture.Proof.Generation); + fixture.Pins.ShouldBe(1); + demand.IsValid.ShouldBeTrue(); + demand.Dispose(); + demand.IsValid.ShouldBeFalse(); + fixture.Pins.ShouldBe(0); + access.HasLiveDemand(DataRealm.Raw, fixture.Proof.LocalIdentifier).ShouldBeFalse(); + } + + [Fact] + public void Changed_materialization_or_revoked_proof_cannot_be_acquired_or_stay_live() + { + using var fixture = new AccessFixture(); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + fixture.Current = false; + demand.ShouldNotBeNull().IsValid.ShouldBeFalse(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse(); + demand.Dispose(); + fixture.Current = true; + fixture.Definition = fixture.Definition with { ProjectionGeneration = 2 }; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse(); + } + + [Fact] + public void Demand_admission_is_bounded_and_recovered_when_idle_demand_is_disposed() + { + using var fixture = new AccessFixture(); using var access = fixture.Create(maxDemands: 1); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse(); + first.ShouldNotBeNull().Dispose(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var next).ShouldBeTrue(); + next.ShouldNotBeNull().Dispose(); + } + + [Fact] + public void Demand_pins_sdk_incarnation_until_disposal_and_force_retirement_fences_it() + { + using var fixture = new AccessFixture(); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + fixture.Definition.Lifetime.TryRetire().ShouldBeFalse(); + fixture.Definition.Lifetime.ForceRetire(); + demand.ShouldNotBeNull().IsValid.ShouldBeFalse(); + demand.Dispose(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse(); + } + + [Fact] + public void Browse_demand_uses_the_original_caller_and_live_proof() + { + using var fixture = new AccessFixture(); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Browse, out var demand).ShouldBeTrue(); + demand.ShouldNotBeNull().IsValid.ShouldBeTrue(); + fixture.Current = false; + demand.IsValid.ShouldBeFalse(); + demand.Dispose(); + } + + [Fact] + public void Missing_freshness_policy_never_authorizes_terminal_read() + { + using var fixture = new AccessFixture(); fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.Zero }; + using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Read_source_pins_sdk_incarnation_until_mapping_invalidation_retires_it() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(); + fixture.Publish(7); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Definition.Lifetime.TryRetire().ShouldBeFalse(); + fixture.InvalidateMapping(); + await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + update.SourceProof.IsValid.ShouldBeFalse(); + fixture.Definition.Lifetime.TryRetire().ShouldBeTrue(); + } + + [Fact(Timeout = 30000)] + public async Task Invalidation_during_source_attachment_does_not_strand_its_pins() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(); + fixture.BeforeBind = () => fixture.InvalidateMapping(); + fixture.Publish(7); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken); + fixture.Definition.Lifetime.TryRetire().ShouldBeTrue(); + fixture.Published.Task.IsCompleted.ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Mapping_invalidation_never_waits_for_the_publication_lock() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(); + fixture.Publish(7); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + var field = typeof(ProjectedDataAccess).GetField("_sync", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + using var release = new ManualResetEventSlim(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var token = TestContext.Current.CancellationToken; + var publication = Task.Run(() => + { + lock (field.GetValue(access)!) { entered.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10), token).ShouldBeTrue(); } + }, token); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), token); + try { await Task.Run(() => fixture.InvalidateMapping(), token).WaitAsync(TimeSpan.FromSeconds(2), token); } + finally { release.Set(); await publication; } + await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + + [Fact(Timeout = 30000)] + public async Task Paused_source_retirement_does_not_queue_unowned_mapping_history() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(); + using var release = new ManualResetEventSlim(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + access.BeforeSourceRetirementForTests = () => { entered.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); }; + fixture.Publish(7); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.InvalidateMapping(); + await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + try + { + for (var i = 0; i < 10000; i++) fixture.InvalidateMapping("historical-" + i); + access.PendingSourceRetirementsForTests.ShouldBe(1, "only the owned source bucket can require retirement work"); + } + finally { release.Set(); await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); } + } + + [Fact(Timeout = 30000)] + public async Task Read_without_subscribe_permission_preserves_origin_age_timestamps_and_source_proof() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(); + fixture.Publish(42); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + update.IsCompleteSnapshot.ShouldBeTrue(); + update.Snapshot.Value.ShouldBe(42); + update.Snapshot.StatusCode.ShouldBe(0x00000400u); + update.Snapshot.SourceTimestampUtc.ShouldBeNull(); + update.Snapshot.ServerTimestampUtc.ShouldNotBeNull(); + update.OriginAgeBounds.Upper.ShouldNotBeNull(); + update.SourceProof.IsValid.ShouldBeTrue(); + update.Route.Serving.ShouldBe(fixture.Proof.Lease.Serving); + update.Route.ProjectionGeneration.ShouldBe(fixture.Proof.Generation); + fixture.Current = false; + update.SourceProof.IsValid.ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Renewed_metadata_replaces_expired_source_without_reviving_old_publication() + { + using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(); + fixture.Publish(42); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue(); + access.ScheduleRead(first!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var old = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.Renew(); + old.SourceProof.IsValid.ShouldBeFalse(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue(); + access.ScheduleRead(second!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var fresh = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fresh.SourceProof.IsValid.ShouldBeTrue(); + fresh.Route.PublicationId.ShouldNotBe(old.Route.PublicationId); + old.SourceProof.IsValid.ShouldBeFalse(); + } + + [Fact(Timeout = 30000)] + public async Task Strict_write_dispatch_uses_exact_origin_and_preserves_unknown_without_publishing_value() + { + using var fixture = new AccessFixture(writable: true); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue(); + var result = await access.WriteAsync(demand!, 42, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.OutcomeUnknown); + var sent = fixture.SentWrite.ShouldNotBeNull().Items.ShouldHaveSingleItem(); + sent.View.ShouldBe(fixture.Proof.OriginMetadata.View); + sent.ExpectedCatalogRevision.ShouldBe(fixture.Proof.OriginMetadata.CatalogRevision); + sent.ExpectedServingIncarnation.ShouldBe(fixture.Proof.Lease.Serving.Incarnation); + sent.ExpectedServingGeneration.ShouldBe(fixture.Proof.Lease.Serving.ServingGeneration); + sent.OperationId.ShouldNotBeNullOrWhiteSpace(); + fixture.Published.Task.IsCompleted.ShouldBeFalse(); + demand!.Dispose(); + } + + [Fact(Timeout = 30000)] + public async Task Local_primary_generation_change_before_dispatch_rejects_write_even_after_role_returns() + { + using var fixture = new AccessFixture(writable: true) { BlockAcquire = true }; using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue(); + try + { + var task = access.WriteAsync(demand!, 42, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken); + await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.RoleGeneration = 2; fixture.RoleAllowed = false; + fixture.RoleGeneration = 3; fixture.RoleAllowed = true; + fixture.ReleaseAcquire.TrySetResult(); + var outcome = await task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + fixture.SentWrite.ShouldBeNull(); + } + finally { fixture.ReleaseAcquire.TrySetResult(); demand?.Dispose(); } + } + + [Fact(Timeout = 30000)] + public async Task Compatible_distinct_views_share_stream_and_last_demand_closes_physical_owner() + { + using var fixture = new AccessFixture(streams: true); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue(); + access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue(); + try + { + access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + access.StartSubscription(second!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.StreamOpens.ShouldBe(1); + first!.Dispose(); + await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse(); + second!.Dispose(); + await fixture.StreamClosed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + } + finally { first?.Dispose(); second?.Dispose(); } + } + + [Fact(Timeout = 30000)] + public async Task Subscribe_only_demand_can_request_a_fresh_snapshot_without_read_permission() + { + using var fixture = new AccessFixture(streams: true, subscribeOnly: true); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + access.RequestFreshSnapshot(demand!).ShouldBeTrue(); + await fixture.SecondStreamOpened.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + fixture.StreamClosed.Task.IsCompleted.ShouldBeTrue(); + demand!.IsValid.ShouldBeTrue(); + } + finally { demand?.Dispose(); } + } + + [Fact] + public void Array_metadata_admission_uses_structural_dimensions_not_list_identity() + { + using var fixture = new AccessFixture(array: true); using var access = fixture.Create(); + fixture.Definition = fixture.Definition with { Metadata = fixture.Definition.Metadata with { Dimensions = new[] { 3 } } }; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue(); + demand.ShouldNotBeNull().Dispose(); + } + + [Fact(Timeout = 30000)] + public async Task Array_write_preserves_owned_shape_and_value() + { + using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create(); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue(); + var input = new[] { 8, 9, 10 }; + var result = await access.WriteAsync(demand!, input, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.OutcomeUnknown); + input[0] = 99; + fixture.CapturedArray.ShouldBe(new object[] { 8, 9, 10 }); + demand!.Dispose(); + } + + [Fact(Timeout = 30000)] + public async Task Array_read_and_write_preserve_owned_one_dimensional_values() + { + using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create(); + var original = new[] { 2, 4, 6 }; fixture.ReadElements = original; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var read).ShouldBeTrue(); + access.ScheduleRead(read!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue(); + var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + original[0] = 99; + update.Snapshot.Value.ShouldBeOfType().ShouldBe(new[] { 2, 4, 6 }); + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var write).ShouldBeTrue(); + var written = new[] { 8, 9, 10 }; + var result = await access.WriteAsync(write!, written, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + result.State.ShouldBe(DataWriteState.OutcomeUnknown); + written[0] = 100; + fixture.CapturedArray.ShouldBe(new object[] { 8, 9, 10 }); + write!.Dispose(); + } + + [Fact(Timeout = 30000)] + public async Task Array_subscription_snapshot_is_published_as_an_owned_typed_array() + { + using var fixture = new AccessFixture(streams: true, array: true); using var access = fixture.Create(); + fixture.ReadElements = [2, 4, 6]; + access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue(); + try + { + access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue(); + var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + update.IsCompleteSnapshot.ShouldBeTrue(); + update.Snapshot.Value.ShouldBeOfType().ShouldBe(new[] { 2, 4, 6 }); + } + finally { demand?.Dispose(); } + } + + private sealed class AccessFixture : IFederatedProjectionCatalog, IProjectedNodeLookup, IGrpcDataAdapterConnectionSource, IProjectedValuePublisher, IDisposable + { + private readonly LocalDataFixture _local = new(servingGeneration: 1); + private readonly DataOperationPolicy _policy; + internal readonly NodeId NodeId = new("projected", 2); + internal readonly NodeId SecondNodeId = new("projected-two", 2); + internal ProjectedNodeProof? SecondProof; + internal ProjectedVariableDefinition? SecondDefinition; + internal int StreamOpens; + internal readonly TaskCompletionSource FirstStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource SecondStreamOpened = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource TwoStreamItems = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ItemRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource StreamClosed = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly bool _streams; + private readonly bool _array; + internal int[] ReadElements = [2, 4, 6]; + internal object[]? CapturedArray; + internal readonly RoleCarryingUserIdentity Caller; + internal ProjectedNodeProof Proof; + internal ProjectedVariableDefinition Definition; + internal bool Current = true; + internal int Pins; + internal TaskCompletionSource Published = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal void Renew() + { + var lease = new MetadataAuthorityLease(_local.Serving, new(1, 1, TimeSpan.FromSeconds(15)), _local.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, _local.Clock); + Proof = Proof with { Lease = lease }; + Definition = Definition with { AuthorityIsCurrent = () => Current }; + Published = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + internal void Publish(int value) => _local.Publish(value); + internal WriteBatch? SentWrite; + internal bool BlockAcquire, RoleAllowed = true; + internal long RoleGeneration = 1; + internal readonly TaskCompletionSource AcquireEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource ReleaseAcquire = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal AccessFixture(bool readOnly = false, bool writable = false, bool streams = false, bool subscribeOnly = false, bool array = false) + { + _streams = streams; _array = array; + var authority = _local.Authority; + if (writable) + { + 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.Operator }], + new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] }); + } + _policy = new(authority, new TriePermissionEvaluator(authority.Tries, _local.Clock), _local.Clock); + Caller = new(new AnonymousIdentityToken(), [], _local.Context.PrincipalId, _local.Context.ApiKeyId, _local.Context.CredentialVersion, _local.Context.CredentialExpiresUtc); + var origin = _local.Raw; + var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Plant/branch/Speed" }; + var serving = _local.Serving; + var operations = subscribeOnly ? DataOperations.Subscribe : readOnly ? DataOperations.Read : DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe | (writable ? DataOperations.Write : DataOperations.None); + var subject = new MappedNamespaceSubject(mapped, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch", "Speed"] }, ["folder"], serving, operations, writable); + var metadata = new DataMetadata(mapped, "Speed", "Variable", DataValueKind.Int32, -1, [], writable, operations, 1, null, null, false, Serving: serving); + if (array) metadata = metadata with { ValueKind = DataValueKind.Array, ValueRank = 1, Dimensions = [3], ArrayElementKind = DataValueKind.Int32 }; + var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), _local.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, _local.Clock); + Proof = new(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject, new([subject], 1, _local.Activation.CaptureAuthority()), lease, 1, metadata with { View = origin }, TimeSpan.FromSeconds(30)); + Definition = new(DataRealm.Raw, Proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => Current); + if (streams) + { + var secondOrigin = origin with { Address = origin.Address with { Identifier = origin.Address.Identifier + "2" }, Subject = origin.Subject + "2" }; + var secondView = mapped with { Address = secondOrigin.Address, Subject = mapped.Subject + "2" }; + var secondSubject = subject with { View = secondView, Scope = subject.Scope with { Segments = ["Plant", "branch", "Speed2"] } }; + var secondMetadata = metadata with { View = secondView, BrowseName = "Speed2" }; + SecondProof = new(ProjectedDataIds.Identifier("mapping", secondOrigin.Address), secondMetadata, secondSubject, new([secondSubject], 1, _local.Activation.CaptureAuthority()), lease, 1, secondMetadata with { View = secondOrigin }, TimeSpan.FromSeconds(30)); + SecondDefinition = new(DataRealm.Raw, SecondProof.LocalIdentifier, new NodeId("parent", 2), secondMetadata, 1, () => Current); + } + } + internal ProjectedDataAccess Create(int maxDemands = 4) => new(this, this, this, _ => "link", _policy, this, _local.Clock, new(maxDemands, 4, 2000000, 2), () => (RoleAllowed, RoleGeneration)); + public TimeProvider Clock => _local.Clock; + public event Action? Invalidated; + internal readonly TaskCompletionSource ConnectionDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal readonly TaskCompletionSource NoPins = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal void InvalidateMapping(string mapping = "mapping") { if (mapping == "mapping") Current = false; Invalidated?.Invoke(mapping, 2); } + public bool TryResolveProjected(DataRealm realm, string id, out ProjectedNodeProof? proof) { proof = Current && realm == DataRealm.Raw ? id == Proof.LocalIdentifier ? Proof : id == SecondProof?.LocalIdentifier ? SecondProof : null : null; return proof is not null; } + public bool TryPinProjected(DataRealm realm, string id, out IDisposable? pin) { if (!Current || id != Proof.LocalIdentifier && id != SecondProof?.LocalIdentifier) { pin = null; return false; } Pins++; pin = new Pin(this); return true; } + private sealed class Pin(AccessFixture owner) : IDisposable { private int _done; public void Dispose() { if (Interlocked.Exchange(ref _done, 1) == 0 && Interlocked.Decrement(ref owner.Pins) == 0) owner.NoPins.TrySetResult(); } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException(); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException(); + public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = nodeId == NodeId ? Definition : nodeId == SecondNodeId ? SecondDefinition : null; return definition is not null; } + public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = NodeId; return true; } + public async ValueTask AcquireAsync(string connectionId, CancellationToken cancellationToken) + { + AcquireEntered.TrySetResult(); + if (BlockAcquire) await ReleaseAcquire.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); + return new ConnectionLease(new TestConnection(_local.Connection(), this), this); + } + private sealed class TestConnection(IDataConnection inner, AccessFixture owner) : IDataConnection + { + public DataTarget Target => inner.Target; + public TimeProvider Clock => inner.Clock; + public Task GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken); + public Task BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken); + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken); + public Task> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken) + { + if (!owner._array) return inner.ReadAsync(request, cancellationToken); + var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast().ToArray(), [owner.ReadElements.Length]); + var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), owner.Proof.Lease.Serving, 1); + return Task.FromResult>([new(request.Items[0].CorrelationId, DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, sample, null, AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero))]); + } + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + { + owner.SentWrite = request; + if (request.Items[0].Value.Kind == DataValueKind.Array) owner.CapturedArray = request.Items[0].Value.GetArray().ToArray(); + return Task.FromResult>([new(request.Items[0].CorrelationId, new(DataWriteState.OutcomeUnknown, StatusCodes.Bad.Code, null))]); + } + public Task SubscribeAsync(CancellationToken cancellationToken) + { + if (!owner._streams) return inner.SubscribeAsync(cancellationToken); + if (Interlocked.Increment(ref owner.StreamOpens) == 2) owner.SecondStreamOpened.TrySetResult(); + return Task.FromResult(new TestStream(owner, owner.Proof.Lease.Serving)); + } + public ValueTask DisposeAsync() => inner.DisposeAsync(); + } + private sealed class TestStream(AccessFixture owner, ServingIdentity serving) : IDataSubscription, IDataSubscriptionProvenance + { + private readonly Channel _frames = Channel.CreateUnbounded(); + private long _sequence; private ulong _handle; private int _items; + private readonly Dictionary _ids = new(); + public ServingIdentity Serving => serving; + public Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken) + { + IReadOnlyList items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] }; + var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good, + new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray(); + foreach (var ack in acks) if (ack.Handle is not null) _ids[ack.Handle] = ack.ClientItemId; + if (command is RemoveSubscriptionItems remove) + acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray(); + _frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks)); + if (items.Count > 0) + { + _items += items.Count; owner.FirstStreamItem.TrySetResult(); if (_items >= 2) owner.TwoStreamItems.TrySetResult(); + _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + if (owner._array && acks.Length > 0) + { + var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast().ToArray(), [owner.ReadElements.Length]); + var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), serving, 1); + _frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true, + [new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)])); + } + _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null)); + } + if (command is RemoveSubscriptionItems) owner.ItemRemoved.TrySetResult(); + return Task.CompletedTask; + } + public IAsyncEnumerable ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken); + public ValueTask DisposeAsync() { _frames.Writer.TryComplete(); owner.StreamClosed.TrySetResult(); return ValueTask.CompletedTask; } + } + private sealed class ConnectionLease(IDataConnection connection, AccessFixture owner) : IGrpcDataAdapterConnectionLease + { + public IDataConnection Connection => connection; + public CancellationToken CancellationToken => CancellationToken.None; + public async ValueTask DisposeAsync() { await connection.DisposeAsync(); owner.ConnectionDisposed.TrySetResult(); } + } + internal Action? BeforeBind; + public bool TryBind(ProjectedValueRoute route) { BeforeBind?.Invoke(); return true; } + public bool TryPublish(IReadOnlyList updates) { Published.TrySetResult(updates[0]); return true; } + public void Retire(ProjectedValueRoute route) { } + public void Dispose() => _local.Dispose(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRouteTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRouteTests.cs new file mode 100644 index 000000000..241b1aadd --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedRouteTests.cs @@ -0,0 +1,85 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataProjectedRouteTests +{ + [Fact] + public void Routes_use_exact_origin_metadata_and_keep_original_authority_live() + { + var catalog = new Catalog(); + var allowed = true; + string? connection = "link"; + var source = new ProjectedAdapterRouteSource(catalog, _ => connection, "link", _ => allowed); + source.TryResolve(catalog.Reference, out var route).ShouldBeTrue(); + route.ShouldNotBeNull(); + route.View.ShouldBe(catalog.Proof.OriginMetadata.View); + route.View.Subject.ShouldBe("Original/Value"); + route.View.MappingId.ShouldBeNull(); + route.Lease.IsValid.ShouldBeTrue(); + allowed = false; + route.Lease.IsValid.ShouldBeFalse(); + source.TryResolve(catalog.Reference, out _).ShouldBeFalse(); + allowed = true; + connection = "other-link"; + route.Lease.IsValid.ShouldBeFalse(); + source.TryResolve(catalog.Reference, out _).ShouldBeFalse(); + connection = "link"; + catalog.Proof = catalog.Proof with { Generation = 2 }; + route.Lease.IsValid.ShouldBeFalse(); + source.TryResolve(catalog.Reference, out var replacement).ShouldBeTrue(); + replacement.ShouldNotBeNull().ProjectionGeneration.ShouldBe(2); + catalog.Authority.Active = false; + replacement.Lease.IsValid.ShouldBeFalse(); + } + + [Fact] + public void Ordinary_paths_and_another_realm_cannot_alias_a_projected_route() + { + var catalog = new Catalog(); + var source = new ProjectedAdapterRouteSource(catalog, _ => "link", "link", _ => true); + source.TryResolve("Original/Value", out _).ShouldBeFalse(); + source.TryResolve(ProjectedDataIds.DependencyReference(DataRealm.Uns, catalog.Proof.LocalIdentifier), out _).ShouldBeFalse(); + } + + private sealed class Authority : IDataMappedCatalogAuthority + { + public bool Active = true; + public bool IsActive => Active; + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + } + private sealed class Catalog : IFederatedProjectionCatalog + { + internal readonly Authority Authority = new(); + internal ProjectedNodeProof Proof; + internal string Reference => ProjectedDataIds.DependencyReference(DataRealm.Raw, Proof.LocalIdentifier); + public Catalog() + { + var serving = new ServingIdentity("node", "boot", "Primary", 1, 1, 1); + var origin = new DataView(new("source", "urn:origin", "string", "Original/Value"), DataRealm.Raw, null, 0, "Original/Value"); + var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Local/Mount/Renamed" }; + var subject = new MappedNamespaceSubject(mapped, + new() { ClusterId = "local", Kind = NodeHierarchyKind.Raw, Segments = ["Local", "Mount", "Renamed"] }, + ["folder"], serving, DataOperations.Read | DataOperations.Subscribe); + var metadata = new DataMetadata(mapped, "Renamed", "Variable", DataValueKind.Int32, -1, [], false, + DataOperations.Read | DataOperations.Subscribe, 1, null, null, false, Serving: serving); + var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), + Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, Clock); + Proof = new(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject, + new([subject], 1, Authority), lease, 1, metadata with { View = origin }); + } + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public bool TryResolveProjected(DataRealm realm, string id, out ProjectedNodeProof? proof) + { proof = realm == DataRealm.Raw && id == Proof.LocalIdentifier ? Proof : null; return proof is not null; } + public bool TryPinProjected(DataRealm realm, string id, out IDisposable? pin) { pin = null; return false; } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException(); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken token) => throw new NotSupportedException(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionApplierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionApplierTests.cs new file mode 100644 index 000000000..18f318ae7 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectionApplierTests.cs @@ -0,0 +1,188 @@ +using Opc.Ua; +using Shouldly; +using Xunit; +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.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] +public sealed class GrpcDataProjectionApplierTests +{ + [Fact(Timeout = 15000)] + public async Task Cursor_is_committed_only_by_successful_atomic_application() + { + var catalog = new Catalog(); + var sink = new Sink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + var request = Request(); + sink.Accept = false; + (await applier.ApplyPageAsync(request, new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeFalse(); + catalog.LastPage.ShouldNotBeNull(); + catalog.LastPage.Commits.ShouldBe(0); + catalog.LastPage.Disposed.ShouldBeTrue(); + sink.Accept = true; + (await applier.ApplyPageAsync(request, new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeTrue(); + catalog.LastPage.ShouldNotBeNull(); + catalog.LastPage.Commits.ShouldBe(1); + catalog.LastPage.Disposed.ShouldBeTrue(); + } + + [Fact(Timeout = 15000)] + public async Task Authority_expiring_before_application_never_commits_the_cursor() + { + var catalog = new Catalog(); + var sink = new Sink { BeforeCommit = () => catalog.Lease.Valid = false }; + using var applier = new ProjectedNamespaceApplier(catalog, sink, 2); + (await applier.ApplyPageAsync(Request(), new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeFalse(); + catalog.LastPage.ShouldNotBeNull(); + catalog.LastPage.Commits.ShouldBe(0); + catalog.LastPage.Disposed.ShouldBeTrue(); + } + + [Fact] + public async Task Invalid_continuation_is_preserved_from_preparation_without_cursor_commit() + { + var catalog = new InvalidCatalog(); + using var applier = new ProjectedNamespaceApplier(catalog, new Sink(), 2); + var status = await applier.ApplyPageResultAsync(Request(), new NodeId("parent", 2), TestContext.Current.CancellationToken); + status.ShouldBe(ProjectionPageStatus.InvalidContinuation); + } + + [Fact(Timeout = 15000)] + [Trait("Phase", "P08Unit")] + public async Task Materialized_authority_checks_only_its_own_item_and_remains_valid_after_prepare_disposal() + { + var catalog = new GuardCatalog(); + var sink = new GuardSink(); + using var applier = new ProjectedNamespaceApplier(catalog, sink, 1); + (await applier.ApplyPageAsync(Request(), new NodeId("parent", 2), TestContext.Current.CancellationToken)).ShouldBeTrue(); + catalog.Page.Disposed.ShouldBeTrue(); + sink.Nodes.Count.ShouldBe(12); + foreach (var lease in catalog.Leases) lease.Checks = 0; + for (var i = 0; i < 50; i++) sink.Nodes[0].AuthorityIsCurrent().ShouldBeTrue(); + catalog.Leases.Skip(1).Sum(x => x.Checks).ShouldBe(0, "checking one retained definition must not rescan its page"); + var retained = sink.Nodes[0].AuthorityIsCurrent.Target.ShouldBeAssignableTo(); + retained!.RetainedBytes.ShouldBeGreaterThan(0); + catalog.Leases[0].Valid = false; + sink.Nodes[0].AuthorityIsCurrent().ShouldBeFalse(); + sink.Nodes[1].AuthorityIsCurrent().ShouldBeTrue(); + } + + private sealed class CountingLease : IDataAuthorizationLease + { + public int Checks; + public bool Valid = true; + public bool IsValid { get { Checks++; return Valid; } } + public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1); + } + private sealed class GuardCatalog : IFederatedProjectionCatalog + { + public readonly CountingLease[] Leases = Enumerable.Range(0, 12).Select(_ => new CountingLease()).ToArray(); + public readonly GuardPage Page; + public GuardCatalog() + { + var authority = new Authority(); + ProjectedNodeProof Proof(int i) + { + var view = new DataView(new("origin", "urn:raw", "string", "child" + i), DataRealm.Raw, "mapping", 1, "Plant/Mount/child" + i); + var subject = new MappedNamespaceSubject(view, + new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Mount", "child" + i] }, + ["folder"], Leases[i].Serving, DataOperations.Browse); + var resolver = new MappedSubjectResolver([subject], 1, authority); + var metadata = new DataMetadata(view, "child" + i, "Tag", DataValueKind.Int32, -1, [], false, + DataOperations.Browse, 1, null, null, false, Serving: Leases[i].Serving); + var origin = metadata with { View = view with { MappingId = null, MappingRevision = 0, Subject = "origin/child" + i } }; + return new ProjectedNodeProof(ProjectedDataIds.Identifier("mapping", view.Address), metadata, subject, resolver, Leases[i], 1, origin); + } + var items = Enumerable.Range(0, 12).Select(Proof).ToArray(); + Page = new GuardPage(new(ProjectionPageStatus.Ready, items, true, null, 1, Leases[0], authority)); + } + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => Page.Snapshot; + public IProjectedPageGuard? CaptureParentGuard(ProjectedBrowseRequest request, ProjectedParentSnapshot expected) => new PageGuard(); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => Task.FromResult(Page); + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + private sealed class PageGuard : IProjectedPageGuard { public bool IsCurrent => true; public long RetainedBytes => 64; } + } + private sealed class GuardPage(ProjectedParentSnapshot snapshot) : IProjectedPreparedPage + { + public bool Disposed; + public ProjectedParentSnapshot Snapshot => snapshot; + public bool TryCommit() => true; + public void Dispose() => Disposed = true; + } + private sealed class GuardSink : IProjectedNamespacePageSink + { + public IReadOnlyList Nodes = []; + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) + { Nodes = nodes; return commit(); } + public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => false; + } + + private sealed class InvalidCatalog : IFederatedProjectionCatalog + { + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => Task.FromResult(new InvalidPage()); + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + private sealed class InvalidPage : IProjectedPreparedPage + { + public ProjectedParentSnapshot Snapshot => new(ProjectionPageStatus.InvalidContinuation, [], false, null, 0); + public bool TryCommit() => throw new InvalidOperationException("Invalid continuation must not commit."); + public void Dispose() { } + } + } + + private static ProjectedBrowseRequest Request() => new("mapping", + new(new("origin", "urn:raw", "string", "root"), DataRealm.Raw, "mapping", 1, "Plant/Mount"), + null, "opaque-cursor", new("reader", "key", "version", null), new(TimeSpan.FromSeconds(5), 16, 4096), TimeProvider.System.GetTimestamp()); + + private sealed class Lease : IDataAuthorizationLease + { + public bool Valid = true; + public bool IsValid => Valid; + public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1); + } + private sealed class Authority : IDataMappedCatalogAuthority + { + public long CatalogEpoch => 1; + public long AuthorityEpoch => 1; + public bool IsActive => true; + } + private sealed class Page(Lease lease) : IProjectedPreparedPage + { + public int Commits; + public bool Disposed; + public ProjectedParentSnapshot Snapshot { get; } = new(ProjectionPageStatus.Ready, [], true, null, 1, lease, new Authority()); + public bool TryCommit() { Commits++; return true; } + public void Dispose() => Disposed = true; + } + private sealed class Sink : IProjectedNamespacePageSink + { + public bool Accept = true; + public Action? BeforeCommit; + public bool TryApply(NodeId parent, IReadOnlyList nodes, Func commit) + { if (!Accept) return false; BeforeCommit?.Invoke(); return commit(); } + public bool TryRemove(NodeId nodeId, ProjectedVariableDefinition expected) => false; + } + private sealed class Catalog : IFederatedProjectionCatalog + { + public Lease Lease { get; } = new(); + public Page? LastPage; + public TimeProvider Clock => TimeProvider.System; + public event Action? Invalidated { add { } remove { } } + public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => new(ProjectionPageStatus.Pending, [], false, null, 0); + public Task PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) + { LastPage = new Page(Lease); return Task.FromResult(LastPage); } + public bool TryResolveProjected(DataRealm realm, string localId, out ProjectedNodeProof? proof) { proof = null; return false; } + public bool TryPinProjected(DataRealm realm, string localId, out IDisposable? pin) { pin = null; return false; } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs index 017b4dfdd..f26277cc8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataWriteAdmissionTests.cs @@ -1,3 +1,8 @@ +using System.Buffers.Binary; +using System.Net; +using Google.Protobuf; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; @@ -153,6 +158,98 @@ public sealed class GrpcDataWriteAdmissionTests route.Dispatched.Order().ShouldBe(["failed", "ok"]); } + [Fact] + public async Task Executor_rejects_a_stale_generation_before_route_or_registry_claim() + { + using var fixture = new LocalDataFixture(); + var route = new RecordingRoute(fixture.Raw); + var executor = CreateExecutor(fixture, route); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, + fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), fixture.Serving.ServingGeneration + 1); + var stale = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + stale.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + route.Dispatched.ShouldBeEmpty(); + var valid = await executor.WriteAsync(new([item with { ExpectedServingGeneration = null }], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + valid.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + } + + [Fact] + public async Task Duplicate_operation_cannot_change_generation_presence() + { + using var fixture = new LocalDataFixture(servingGeneration: 1); + var route = new RecordingRoute(fixture.Raw); + var executor = CreateExecutor(fixture, route); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, + fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), 1); + var first = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + var changed = await executor.WriteAsync(new([item with { CorrelationId = "two", ExpectedServingGeneration = null }], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + changed.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); + route.Dispatched.ShouldBe(["same-operation"]); + } + + [Fact] + public async Task Same_operation_after_role_aba_returns_unknown_instead_of_retryable_rejection() + { + using var fixture = new LocalDataFixture(servingGeneration: 1); + var serving = fixture.Serving; + var catalog = fixture.Catalog; + var route = new RecordingRoute(fixture.Raw); + var executor = CreateExecutor(fixture, route, catalogSource: () => catalog, servingSource: () => serving); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, serving.Incarnation, TimeSpan.FromSeconds(5), 1); + var first = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + serving = serving with { ServingGeneration = 3 }; + catalog = catalog.WithServingRole(serving); + var afterAba = await executor.WriteAsync(new([item with { ExpectedServingGeneration = 3 }], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + afterAba.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); + route.Dispatched.ShouldBe(["same-operation"]); + } + + [Fact] + public async Task Legacy_client_does_not_fail_over_a_real_executor_conflict_after_role_aba() + { + using var fixture = new LocalDataFixture(servingGeneration: 1); + var serving = fixture.Serving; + var catalog = fixture.Catalog; + var route = new RecordingRoute(fixture.Raw); + var executor = CreateExecutor(fixture, route, catalogSource: () => catalog, servingSource: () => serving); + var first = new ExecutorWireHandler(() => serving, fixture.Raw, executor); + var second = new ExecutorWireHandler(() => serving with { NodeId = "node-b" }, fixture.Raw, null); + using var manager = new DataConnectionManager("consumer", 1); + manager.ApplyScope(new Dictionary> { ["link"] = new HashSet { "consumer" } }); + await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "cluster", null), + [new Uri("https://a.test"), new Uri("https://b.test")], new ExecutorWireSecurity(first, second), manager.Acquire("link"), + 1_000_000, 2, eligibleNodeIds: new HashSet { "node-a", "node-b" }); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, serving.Incarnation, TimeSpan.FromSeconds(5)); + var original = await connection.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + original.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + serving = serving with { ServingGeneration = 3 }; + catalog = catalog.WithServingRole(serving); + var repeated = await connection.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + repeated.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); + route.Dispatched.ShouldBe(["same-operation"]); + first.Writes.ShouldBe(2); second.Writes.ShouldBe(0); + } + + [Fact] + public async Task Strict_write_rejects_a_different_view_shape_before_dispatch() + { + using var fixture = new LocalDataFixture(servingGeneration: 1); + var route = new RecordingRoute(fixture.Raw); + var executor = CreateExecutor(fixture, route); + using var value = DataValue.FromScalar(DataValueKind.Int32, 42); + var item = new WriteItem("one", "operation", fixture.Raw with { Subject = "forged" }, value, 1, + fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), 1); + var result = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken); + result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); + route.Dispatched.ShouldBeEmpty(); + } + [Fact] public async Task Executor_joins_concurrent_duplicate_with_a_different_remaining_budget() { @@ -229,7 +326,7 @@ public sealed class GrpcDataWriteAdmissionTests 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); + two.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown); route.Dispatched.ShouldBe(["same-id"]); } @@ -300,7 +397,8 @@ public sealed class GrpcDataWriteAdmissionTests } private static DataWriteExecutor CreateExecutor(LocalDataFixture fixture, IDataWriteRoute route, - DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null) + DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null, + Func? catalogSource = null, Func? servingSource = null) { var authority = new DataPlaneAuthorityState(); var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true }; @@ -312,11 +410,64 @@ public sealed class GrpcDataWriteAdmissionTests 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, + var capabilities = new DataCapabilitiesProvider("cluster", servingSource ?? (() => fixture.Serving), () => true, limits); + return new DataWriteExecutor(context ?? fixture.Context, catalogSource ?? (() => catalog ?? fixture.Catalog), policy, capabilities, route, registry, new WriteValueBudget(16_384), fixture.Clock, new DriverWriteBounds(TimeSpan.FromMilliseconds(100))); } + private sealed class ExecutorWireSecurity(ExecutorWireHandler first, ExecutorWireHandler second) : IDataConnectionSecurityProvider + { + public event Action? Changed { add { } remove { } } + public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => + ValueTask.FromResult(new("v1", "ca", "key", () => endpoint.Host == "a.test" ? first : second)); + } + private sealed class ExecutorWireHandler(Func current, DataView view, DataWriteExecutor? executor) : HttpMessageHandler + { + public int Writes { get; private set; } + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var serving = current(); + IMessage message; + if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal)) + { + var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, serving, DataReadiness.Ready, + DataOperations.Read | DataOperations.Metadata | DataOperations.Write, new HashSet { DataValueKind.Int32 }, + limits, false, 0, "cluster", false, true, true)); + } + else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal)) + { + var metadata = new DataMetadata(view, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write, 1, null, null, false); + var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]); + response.Serving = DataProtoMapper.EncodeServing(serving); message = response; + } + else + { + Writes++; + var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken); + var wire = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray()); + var batch = DataProtoMapper.DecodeWriteRequest(wire, 100, 1_000_000); + try + { + var outcomes = executor is null ? batch.Items.Select(x => new WriteItemResult(x.CorrelationId, + new(DataWriteState.DriverConfirmedSuccess, 0, null))).ToArray() : + await executor.WriteAsync(batch, cancellationToken); + var response = DataProtoMapper.EncodeWriteResponse(outcomes); + response.Serving = DataProtoMapper.EncodeServing(serving); message = response; + } + finally { foreach (var item in batch.Items) item.Value.Dispose(); } + } + var payload = message.ToByteArray(); + var framed = new byte[payload.Length + 5]; + BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); + payload.CopyTo(framed, 5); + var http = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) }; + http.Content.Headers.ContentType = new("application/grpc"); + http.TrailingHeaders.Add("grpc-status", "0"); + return http; + } + } + private sealed class RecordingRoute(DataView view, DataView? alternate = null) : IDataWriteRoute { private readonly System.Collections.Concurrent.ConcurrentQueue _dispatched = new(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderAppendPipelineTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderAppendPipelineTests.cs index 5da844cd2..b8fc015ce 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderAppendPipelineTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/ContinuousHistorizationRecorderAppendPipelineTests.cs @@ -70,6 +70,35 @@ public sealed class ContinuousHistorizationRecorderAppendPipelineTests : TestKit outbox.AppendBatchCalls.ShouldBeLessThan(6, "the bursts waiting behind the slow append share its successor's commit"); } + [Fact(Timeout = 20000)] + public async Task Projected_input_revoked_while_waiting_for_append_capacity_is_not_admitted() + { + var log = new EventLog(); + var outbox = new LoggingOutbox(log) { AppendGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) }; + var rec = Start(outbox, new LoggingPassWriter(log), maxAppendsInFlight: 1); + rec.Tell(Burst(1)); + await outbox.AppendEntered.Task.WaitAsync(Wait, TestContext.Current.CancellationToken); + rec.Tell(Burst(1, 1)); + await AwaitAssertAsync(async () => (await StatusAsync(rec)).PendingAppends.ShouldBe(2), Wait, cancellationToken: TestContext.Current.CancellationToken); + var proof = new ProjectedGate(); + rec.Tell(new VirtualTagActor.DependencyValueBatch([new("A", 2d, T0.AddSeconds(2), PublicationProof: proof)])); + var status = StatusAsync(rec, Wait); + await Task.Delay(300, TestContext.Current.CancellationToken); + status.IsCompleted.ShouldBeFalse(); + proof.Invalidate(); + outbox.AppendGate.SetResult(); + await status; + await AwaitAssertAsync(() => outbox.Appended.Count.ShouldBe(2), Wait, cancellationToken: TestContext.Current.CancellationToken); + outbox.Appended.Select(x => x.Value.Number).ShouldBe([0d, 1d]); + } + private sealed class ProjectedGate : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof + { + private int _valid = 1; + public bool IsValid => Volatile.Read(ref _valid) != 0; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => Interlocked.Exchange(ref _valid, 0); + } + [Fact] public async Task A_full_append_queue_backpressures_the_mailbox_and_loses_nothing() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/DependencyMuxTagUpstreamSourceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/DependencyMuxTagUpstreamSourceTests.cs index 16ffd3976..dcc74eec2 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/DependencyMuxTagUpstreamSourceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/DependencyMuxTagUpstreamSourceTests.cs @@ -37,6 +37,80 @@ public sealed class DependencyMuxTagUpstreamSourceTests seen.ShouldBe(new[] { "old/renamed" }); } + [Fact] + public void Projected_evidence_belongs_to_exact_snapshot_and_later_sample_cannot_revive_it() + { + var src = new DependencyMuxTagUpstreamSource(); + var firstProof = new ProjectedProof(); var secondProof = new ProjectedProof(); + var sample = Good(1, DateTime.UtcNow); + src.Push("path", sample, firstProof); + var first = src.ReadTag("path"); + var evidence = src.CaptureEvidence(first).ShouldNotBeNull(); + evidence.IsValid.ShouldBeTrue(); + src.Push("path", sample, secondProof); + var second = src.ReadTag("path"); + second.ShouldNotBeSameAs(first); + firstProof.Invalidate(); + evidence.IsValid.ShouldBeFalse(); + src.CaptureEvidence(second).ShouldNotBeNull().IsValid.ShouldBeTrue(); + src.CaptureEvidence(sample).ShouldBeNull(); + } + [Fact] + public void Retained_projected_evaluation_payload_stays_charged_until_physical_release() + { + var src = new DependencyMuxTagUpstreamSource(maximumProjectedBytes: 1600); + var proof = new ProjectedProof(); + src.Push("path", Good(new byte[600], DateTime.UtcNow), proof); + var firstSnapshot = src.ReadTag("path"); + var first = src.CaptureEvidence(firstSnapshot).ShouldBeAssignableTo(); + first!.TryRetainPhysical(firstSnapshot, out var held).ShouldBeTrue(); + src.Push("path", Good(new byte[600], DateTime.UtcNow), proof); + var secondSnapshot = src.ReadTag("path"); + var second = src.CaptureEvidence(secondSnapshot).ShouldBeAssignableTo(); + second!.TryRetainPhysical(secondSnapshot, out _).ShouldBeFalse(); + held.ShouldNotBeNull().Dispose(); + second!.TryRetainPhysical(secondSnapshot, out var fresh).ShouldBeTrue(); + fresh.ShouldNotBeNull().Dispose(); + } + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Replaced_upstreams_share_the_process_physical_budget_until_each_run_releases() + { + var leases = new List(); + var payload = new byte[3 * 1024 * 1024]; + static bool Retain(byte[] value, out IDisposable? lease) + { + var source = new DependencyMuxTagUpstreamSource(); + source.Push("path", Good(value, DateTime.UtcNow), new ProjectedProof()); + var snapshot = source.ReadTag("path"); + var evidence = source.CaptureEvidence(snapshot).ShouldBeAssignableTo(); + return evidence!.TryRetainPhysical(snapshot, out lease); + } + try + { + for (var i = 0; i < 5; i++) + { + Retain(payload, out var held).ShouldBeTrue(); + leases.Add(held.ShouldNotBeNull()); + } + Retain(payload, out var rejected).ShouldBeFalse(); + rejected.ShouldBeNull(); + leases[0].Dispose(); + Retain(payload, out var replacement).ShouldBeTrue(); + leases.Add(replacement.ShouldNotBeNull()); + Retain(payload, out rejected).ShouldBeFalse(); + rejected.ShouldBeNull(); + } + finally { foreach (var lease in leases) lease.Dispose(); } + } + + private sealed class ProjectedProof : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof + { + private int _valid = 1; + public bool IsValid => Volatile.Read(ref _valid) != 0; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => Interlocked.Exchange(ref _valid, 0); + } + [Fact] public void Push_then_ReadTag_returns_the_pushed_snapshot() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs index 55dbe0872..455299d3e 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostActorTests.cs @@ -46,6 +46,27 @@ public sealed class ScriptedAlarmHostActorTests : RuntimeActorTestBase /// private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + [Fact] + public void A_delayed_engine_emission_with_revoked_original_evidence_is_not_published() + { + var publish = CreateTestProbe(); var mux = CreateTestProbe(); + var (host, _) = Spawn(publish, mux); + var evidence = new TestEvidence(); + var emission = new ScriptedAlarmEvent("alarm", "Plant", "Alarm", AlarmKind.AlarmCondition, + ZB.MOM.WW.OtOpcUa.Core.Abstractions.AlarmSeverity.High, "message", + AlarmConditionState.Fresh("alarm", DateTime.UtcNow), EmissionKind.QualityChanged, DateTime.UtcNow) + { InputEvidence = evidence }; + var type = typeof(ScriptedAlarmHostActor).GetNestedType("EngineEmission", System.Reflection.BindingFlags.NonPublic).ShouldNotBeNull(); + var message = Activator.CreateInstance(type, emission).ShouldNotBeNull(); + evidence.Valid = false; + host.Tell(message); + publish.ExpectNoMsg(TimeSpan.FromMilliseconds(250), TestContext.Current.CancellationToken); + evidence.Valid = true; + host.Tell(message); + publish.ExpectMsg(Timeout, cancellationToken: TestContext.Current.CancellationToken); + } + private sealed class TestEvidence : IAlarmInputEvidence { public bool Valid = true; public bool IsValid => Valid; } + /// Plan whose predicate compares the single tag "M.T" against 90 — enabled by default. private static EquipmentScriptedAlarmPlan Plan( string id = "alm-1", diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/DependencyConsumerMuxAdapterTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/DependencyConsumerMuxAdapterTests.cs index f8d7e80ed..0331881a6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/DependencyConsumerMuxAdapterTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/DependencyConsumerMuxAdapterTests.cs @@ -3,6 +3,7 @@ using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags; @@ -24,6 +25,89 @@ public sealed class DependencyConsumerMuxAdapterTests : RuntimeActorTestBase private const string TagA = "Plant/Modbus/dev1/a"; private const string TagB = "Plant/Modbus/dev1/b"; + [Theory(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + [InlineData(false)] + [InlineData(true)] + public void Revoked_projected_proof_is_bad_at_the_actual_consumer_callback(bool batch) + { + var (consumer, adapter) = Spawn(); + var message = new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, new RevokedProof()); + adapter.Tell(batch ? (object)new VirtualTagActor.DependencyValueBatch([message]) : message); + AwaitCondition(() => consumer.Received.Count == 1, PresenceBudget, TestContext.Current.CancellationToken); + consumer.Received[0].Value.ShouldBeNull(); + consumer.Received[0].StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication); + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Valid_projected_sample_keeps_its_exact_proof_at_the_consumer_boundary() + { + var consumer = new ProjectedConsumer(); + var mux = CreateTestProbe(); + var adapter = Sys.ActorOf(DependencyConsumerMuxAdapter.Props(consumer, mux.Ref)); + mux.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var proof = new MutableProof(); + adapter.Tell(new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, proof)); + AwaitCondition(() => Volatile.Read(ref consumer.Proof) is not null, PresenceBudget, TestContext.Current.CancellationToken); + consumer.Proof.ShouldBeSameAs(proof); + proof.Valid = false; + consumer.Proof!.IsValid.ShouldBeFalse(); + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Revoked_projected_sample_preserves_classification_with_a_bad_empty_value() + { + var consumer = new ProjectedConsumer(); + var mux = CreateTestProbe(); + var adapter = Sys.ActorOf(DependencyConsumerMuxAdapter.Props(consumer, mux.Ref)); + mux.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + var proof = new RevokedProof(); + adapter.Tell(new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, proof)); + AwaitCondition(() => Volatile.Read(ref consumer.Proof) is not null, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + consumer.Proof.ShouldBeSameAs(proof); + consumer.Value.ShouldBeNull(); + consumer.Status.ShouldBe(OpcUaStatus.BadNoCommunication); + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Valid_projected_sample_is_not_delivered_as_good_to_a_legacy_consumer() + { + var (consumer, adapter) = Spawn(); + adapter.Tell(new VirtualTagActor.DependencyValueChanged(TagA, 42, DateTime.UtcNow, OpcUaStatus.Good, new MutableProof())); + AwaitCondition(() => consumer.Received.Count == 1, PresenceBudget, TestContext.Current.CancellationToken); + consumer.Received[0].Value.ShouldBeNull(); + consumer.Received[0].StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication); + } + + private sealed class MutableProof : IProjectedSamplePublicationProof + { + public bool Valid = true; + public bool IsValid => Valid; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => Valid = false; + } + + private sealed class ProjectedConsumer : IDependencyConsumer, IProjectedDependencyConsumer + { + public IReadOnlyCollection DependencyRefs => [TagA]; + public IProjectedSamplePublicationProof? Proof; + public object? Value; + public uint Status; + public void OnDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc) { } + public void OnProjectedDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc, IProjectedSamplePublicationProof proof) + { + Value = value; + Status = statusCode; + Volatile.Write(ref Proof, proof); + } + } + + private sealed class RevokedProof : IProjectedSamplePublicationProof + { + public bool IsValid => false; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() { } + } + /// Single delivery: the status code reaches the consumer verbatim, sub-code and all. [Fact] public void A_single_dependency_value_carries_its_status_code_to_the_consumer() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorAsyncEvaluationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorAsyncEvaluationTests.cs index 5243656a7..f2f782c9d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorAsyncEvaluationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagActorAsyncEvaluationTests.cs @@ -148,6 +148,87 @@ one-thread-dispatcher { recovered.Value.ShouldBe(5); } + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Projected_input_is_not_passed_to_an_evaluator_without_physical_ownership_support() + { + var parent = CreateTestProbe(); + var evaluator = new ManualEvaluator(); + var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-projected", "expr", evaluator: evaluator, + dependencyRefs: ["a"]), TestContext.Current.CancellationToken); + actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, DateTime.UtcNow, OpcUaStatus.Good, new LiveProof())); + parent.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) + .StatusCode.ShouldNotBe(OpcUaStatus.Good); + evaluator.Calls.ShouldBeEmpty(); + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Revocation_during_projected_evaluation_prevents_good_acceptance() + { + var parent = CreateTestProbe(); + var evaluator = new ProjectedManualEvaluator(); + var proof = new LiveProof(); + var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-revoked", "expr", evaluator: evaluator, + dependencyRefs: ["a"]), TestContext.Current.CancellationToken); + try + { + actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, DateTime.UtcNow, OpcUaStatus.Good, proof)); + AwaitCondition(() => evaluator.Started, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); + proof.Invalidate(); + evaluator.Complete(); + var accepted = parent.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken); + accepted.StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication); + } + finally { evaluator.Complete(); } + } + + [Fact(Timeout = 15000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] + public void Throwing_projected_proof_fails_closed_without_restarting_the_actor() + { + var parent = CreateTestProbe(); + var evaluator = new ManualEvaluator(); + var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-proof-error", "expr", evaluator: evaluator, + dependencyRefs: ["a"]), TestContext.Current.CancellationToken); + actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, DateTime.UtcNow, OpcUaStatus.Good, new ThrowingProof())); + parent.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) + .StatusCode.ShouldBe(OpcUaStatus.BadNoCommunication); + evaluator.Calls.ShouldBeEmpty(); + } + + private sealed class ThrowingProof : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof + { + public bool IsValid => throw new InvalidOperationException("source retired"); + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() { } + } + + private sealed class ProjectedManualEvaluator : IProjectedVirtualTagEvaluator + { + private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + private IDisposable? _lease; + public bool Started => Volatile.Read(ref _lease) is not null; + public VirtualTagEvalResult Evaluate(string id, string expression, IReadOnlyDictionary dependencies) + => throw new InvalidOperationException("legacy evaluation is not permitted"); + public Task EvaluateProjectedAsync(string id, string expression, + IReadOnlyDictionary dependencies, IDisposable physicalLease) + { + Volatile.Write(ref _lease, physicalLease); + return _completion.Task; + } + public void Complete() + { + Interlocked.Exchange(ref _lease, null)?.Dispose(); + _completion.TrySetResult(VirtualTagEvalResult.Ok(1)); + } + } + + private sealed class LiveProof : ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.IProjectedSamplePublicationProof + { + private int _valid = 1; + public bool IsValid => Volatile.Read(ref _valid) == 1; + public TimeProvider Clock => TimeProvider.System; + public void Invalidate() => Interlocked.Exchange(ref _valid, 0); + } + /// Models the Roslyn evaluator: the blocking overload parks its caller until the script returns (what /// the actor used to call), the async one returns an incomplete task (what it calls now). private sealed class GatedEvaluator(object value) : IVirtualTagEvaluator diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs index bc9acb9af..926ecbe33 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/WorkerSoftClockTests.cs @@ -46,6 +46,30 @@ public sealed class WorkerSoftClockTests return worker; } + [Fact] + public async Task Physical_lease_stays_charged_through_transport_timeout_until_worker_actually_answers() + { + var timeout = TimeSpan.FromMilliseconds(150); + await using var runner = Runner(TimeSpan.FromMilliseconds(300)); + var worker = await WarmAsync(runner, "physical"); + var lease = new PhysicalLease(); + ScriptRunOutcome outcome; + using (ProcessFreezer.Freeze(worker.Pid)) + { + outcome = await runner.RunAsync(Scripts.Vt("physical", Trivial, timeout) with { PhysicalLease = lease }, Ct) + .WaitAsync(TimeSpan.FromSeconds(10), Ct); + outcome.Status.ShouldBe(ScriptRunStatus.Unavailable); + lease.Disposals.ShouldBe(0); + } + await outcome.Recovery.ShouldNotBeNull().WaitAsync(TimeSpan.FromSeconds(10), Ct); + lease.Disposals.ShouldBe(1); + } + private sealed class PhysicalLease : IDisposable + { + private int _disposals; public int Disposals => Volatile.Read(ref _disposals); + public void Dispose() => Interlocked.Increment(ref _disposals); + } + /// /// The issue's headline: a worker that cannot be scheduled for longer than T, but shorter than the transport /// deadline, answers a trivial script with its value. Before #827 the host's clock, started at submit, answered