feat: add immutable partitioned data publication hub
This commit is contained in:
@@ -19,7 +19,7 @@ The [implementation plan](../../2026-11-15-grpc-data-connections-implementation-
|
||||
| P01 | Domain/protobuf contracts | Passed; Astra freeze approved | 15 domain + 36 wire tests, zero failures/skips; run `20261116T024814.318745Z-3a06bbb5af5e` |
|
||||
| P02 | Schema/artifact/consumer projection | Passed; Astra approved | 72 F + 31 P + 106 R, no failures/skips; final run `20261116T034337.311145Z-cd97a339f340` |
|
||||
| P03 | Shared authorization and leases | Passed; Astra approved | 77 K + 89 O + 53 R + 19 H, no failures/skips; final run `20261116T034150.797719Z-8f107e03d8d5` |
|
||||
| P04 | Immutable publication, hub and local ports | Pending | |
|
||||
| P04 | Immutable publication, hub and local ports | Passed; Astra approved | 185 R + 16 A + 16 C + 77 O + 74 ScriptWorker + 88 MTConnect + 40 OpcUaClient = 496, no failures/skips; final run `20261116T060538.590404Z-b8ef1894731e` |
|
||||
| P05 | Mutation tickets/outcomes | Pending | |
|
||||
| P06 | Streams/sharing/fair delivery | Pending | |
|
||||
| P07 | TLS/provisioning/node+cluster clients | Pending | |
|
||||
@@ -67,13 +67,29 @@ Final [Astra P02/P03 review](p02-p03-astra-review.md) closes all five findings a
|
||||
|
||||
Independent Python helpers for local-context validation, fixture endpoint/manifest isolation, ownership-only cleanup, atomic secret files, bounded/redacted processes, deployment outcome polling and CLI result validation have test-first preparation evidence: initial discovery failed on missing modules; the focused combined run subsequently passed 44 tests. This is not the P10 gate. Concrete Compose, SQL/device/seeder, TLS/provisioning, runtime observation, CLI/probe scenarios and actual Docker integration remain pending. No containers or databases have been modified.
|
||||
|
||||
## P04 execution notes
|
||||
|
||||
Hub and source-feed expected missing-API RED runs: `20261116T035138.678709Z-921224df1e45` and `20261116T035253.701549Z-3677798d45ff`. The coordinated production graph then compiled while the Task10 test failed on the missing local catalog/facade APIs in `20261116T040451.917499Z-9fc5a1cf55f8`. [Publication review](p04-publication-astra-review.md) identified producer blocking, lifecycle, binding recovery and virtual freshness issues; correction candidates remain unapproved until their behavioral gate and rereview finish.
|
||||
|
||||
Acquisition retention is independent of served catalog activation: internal raw hub samples may carry the actual boot process identity with zero catalog/authority epochs. Public `DataSample.Validate` and wire codecs remain strict. A local facade must prove the active catalog/authority and current backing source, then attach current serving headers while preserving original value version/timestamps and monotonic receipt age. Charged cache-read resources remain owned until the recipient disposes `ReadResult`; publication guards fence retained replies after invalidation. The old SDK/actor delivery path remains separately copied and serialized and is outside the new hub's accounting; P11 must measure that overhead explicitly.
|
||||
|
||||
The second complete P04 attempt (`20261116T051418.493232Z-1a9b4de9e45b`) passed 155 Runtime, 16 Core.Abstractions, 16 Commons and 77 SDK tests. The gate then stopped because four Windows-only worker security tests explicitly skipped on macOS; this is not a completed P04 gate. Explicit, discoverable platform applicability is being added without relaxing unexpected-skip rejection. Astra additionally identified a legacy delivery regression under hub binding pressure: physical driver subscriptions must continue independently of the bounded new feed. Its correction and the production catalog activation integration remain pending. The follow-up publication review resolves H1/M2/M3 but leaves virtual retirement cleanup, legacy availability under hub pressure, source accounting across repartition, and case-insensitive origin cluster identity open. Task10 staging tests produced the expected missing-API RED in `20261116T052822.115386Z-041fa266b284`; implementation is in progress. The platform-aware runner regression suite passed 28 focused Python tests; the real platform-filtered C# gate has not yet run. Task10 staging subsequently passed all eight focused tests in `20261116T053226.727293Z-11a44bee32b8` after correcting an xUnit cancellation-token analyzer error. Source regression RED `20261116T053303.727269Z-0e8faa537de7` executed 35 tests (30 passed/five expected failures: binding contention, full hub, missing shape, virtual retirement and mixed-case cluster keys). Hub regression RED `20261116T053507.573526Z-b3f1ee05f515` executed 20 tests (15 passed/five expected failures: retained source charges across repartition and old-ticket retirement). The focused correction candidates passed 35/35 source tests in `20261116T054124.390909Z-bfd4f5cc2345` and 20/20 hub tests in `20261116T054353.930760Z-80fdd94dde21`, both with no skips. These do not replace the complete P04 gate. Staging follow-up RED `20261116T054026.209143Z-e6ba95281799` executed 18 tests (10 passed/eight expected failures): wrapper reuse, wrong serving-node provenance, headless/SDK same-revision retry after failed expected catalog activation, and all four cache/restore subscription-order cases. The 18 staging tests subsequently passed in `20261116T054720.800511Z-26d9fb40b300`. A later source review found the bounded 128-reference initial preparation could lose quiet tail values; the real 130-source test failed exactly at source-128 in `20261116T054854.714447Z-3f6eb6203de4` (35 passed/one expected failure). The source correction then passed all 36 tests in `20261116T055309.152744Z-9dee8a78ffeb`, including all 130 original initial values and prior pressure cases. Direct restore RED `20261116T055225.759147Z-001d468f9d9e` passed 18 staging tests and failed the real deferred-driver regression because it opened a third database context. The artifact-reuse correction passed all 19 staging tests in `20261116T055656.284057Z-33ba66cac80e`. The first complete gate then exposed nullable-timestamp comparison compilation errors in affected driver tests; explicit non-null assertions and value comparisons fixed them. Focused MTConnect 88/88 and OPC UA client 40/40 passed before the final complete P04 run passed all 496 applicable tests. Four explicitly declared Windows-only worker methods are verified during discovery and excluded on macOS; no applicable test is skipped. The final gate is `20261116T060538.590404Z-b8ef1894731e`. Staging review also requires deployment confirmation/retry to reflect catalog activation failure; a clean legacy topology apply alone must not suppress repair of the same desired data revision.
|
||||
|
||||
The P04 selector manifest adds only affected virtual/restart, timestamp/worker/history, domain-value and wire-read regression classes. Runtime desired-catalog staging now closes before physical driver replacement, shares an exact attempt with the SDK publisher, and also supports headless application/cache/restore. Source/hub and staging review findings have been corrected; see the final checkpoint disposition. P08 must consume independent original timestamps at the mapped SDK sink; carrying them in the compatible legacy envelope does not prove the SDK import boundary already preserves them.
|
||||
|
||||
## Later-phase integration obligations
|
||||
|
||||
P05 read-only preparation located the actual device invocation inside the resilience delegate, after actor dispatch and `Task.Yield`; final ticket validation must occur there. Capture the actual driver task for bounded late observation, because the resilience wrapper can time out first. Legacy Good acknowledgments without established device-application guarantees remain unconfirmed.
|
||||
|
||||
P06 must prove retained snapshot acquisition age survives transport/reconnect independently of optional wall-clock timestamps. Current unary `ReadResult` carries age, while subscription values do not yet carry an explicit age field; resolve this at the stream contract checkpoint rather than infer freshness from receipt. P07 should construct remote realm roots using the canonical cluster identity from validated capabilities, and compose source publishers with real atomic process/role provenance shared with the catalog coordinator.
|
||||
|
||||
## P00 verification
|
||||
|
||||
The runner tests first failed as expected while `run-unit-phase.py` was absent. After initial implementation, 18 fake-subprocess Python units passed. Astra found required existing regression classes were not enforced as strictly as new classes; four added regression tests failed before the correction. The final 22 Python tests passed, with red/green logs in `artifacts/grpc-data/p00-runner-regressions/`. The real P00 discovery/execution runner passed both counting-probe/reaper C# tests with no skips; the starting production graph compiled successfully. No solution test run or Docker mutation occurred. Raw TRX/commands/discovery identities remain in ignored artifacts. The runner validates discovery AND executed results for every required new class, retains parameterized class filters, and sanitizes both child environments. Astra approved P00 after the required-existing-class correction; see [checkpoint review](p00-astra-review.md).
|
||||
|
||||
## P03 preparation obligations
|
||||
|
||||
Read-only security preparation confirmed that caller-supplied `DataView.Subject` is a claim, never an ACL authority. P03 resolves subject/provenance against the active deployed catalog before either Raw/UNS fallback or cache lookup, and strictly caller-bound facades carry authenticated principal/key/version/original expiry. Revalidate the current key principal and credential version as well as expiry even without an authority-generation change. Deep-copy mutable authority inputs before publishing security snapshots. Failed desired-authority staging must close new mapped/data access rather than retain stale permissions. These obligations supplement the planned spoofed-subject, queued expiry, same-ID credential replacement, deep-copy mutation, and failed/empty apply tests; they are not yet implemented.
|
||||
Read-only security preparation confirmed that caller-supplied `DataView.Subject` is a claim, never an ACL authority. P03 resolves subject/provenance against the active deployed catalog before either Raw/UNS fallback or cache lookup, and strictly caller-bound facades carry authenticated principal/key/version/original expiry. Revalidate the current key principal and credential version as well as expiry even without an authority-generation change. Deep-copy mutable authority inputs before publishing security snapshots. Failed desired-authority staging must close new mapped/data access rather than retain stale permissions. These obligations supplement the planned spoofed-subject, queued expiry, same-ID credential replacement, deep-copy mutation, and failed/empty apply tests. They were subsequently implemented and verified in P03, as recorded above.
|
||||
|
||||
## P01 verification and frozen contracts
|
||||
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
# P04 Astra publication-boundary review
|
||||
|
||||
**Disposition: P04 approved. All source/hub and staging findings H1/H2/H3 and M1–M6 are resolved, and the complete applicable phase gate passed 496/496 with no failures or skips.** Review began against `d0af4d2148c172b0e3f001e8c1b8129cf16649be` plus the coordinator's frozen publication/hub candidate. The reviewer subsequently reread the corrected publication/hub code, actor integration, local catalog/browse/read services, Task 10 staging and corresponding tests. The reviewer ran no tests, builds, migrations or Docker, and changed only this document.
|
||||
|
||||
At the initial publication checkpoint, Task 10's catalog/policy facade and staging review remained pending; they are covered by the final review below. Production Host DI remains scheduled for P07. A compiling source/hub graph and the initial missing-API RED alone did not establish behavioral GREEN. Saved run `20261116T035138.678709Z-921224df1e45/unit/P04/run.json` records a failed discovery/build for the initial `GrpcDataPartitionTests` case; this is the scaffold RED, not an assertion-based reproduction of the findings below.
|
||||
|
||||
## Final phase evidence and candidate reconciliation
|
||||
|
||||
The complete applicable P04 gate `20261116T060538.590404Z-b8ef1894731e/unit/P04/run.json` passed:
|
||||
|
||||
| Project | Passed | Failed | Skipped |
|
||||
|---|---:|---:|---:|
|
||||
| Runtime | 185 | 0 | 0 |
|
||||
| Core.Abstractions | 16 | 0 | 0 |
|
||||
| Commons | 16 | 0 | 0 |
|
||||
| OPC UA SDK | 77 | 0 | 0 |
|
||||
| ScriptWorker | 74 | 0 | 0 |
|
||||
| MTConnect | 88 | 0 | 0 |
|
||||
| OPC UA Client | 40 | 0 | 0 |
|
||||
| **Total** | **496** | **0** | **0** |
|
||||
|
||||
The reviewer independently inspected the final report and verified that every required new and existing class executed. The run and reviewed checkout have the same base `d0af4d2148c172b0e3f001e8c1b8129cf16649be`. The complete tracked `git diff HEAD --binary` digest matched **`40a4d33e94da9bd93e25b3eb172e1c7f21d3eb591a1aa52045c15fa3e2b1d9bd`**. All 23 recorded untracked-file digests matched, including all 22 production/test files, before this final review-only document update. No production change intervened after source approval. The two driver test adjustments explicitly assert a non-null original server timestamp before comparing `.Value`; the final MTConnect and OPC UA Client gates execute those assertions.
|
||||
|
||||
The manifest declares four Windows-only ScriptWorker methods as inapplicable on macOS. The reviewer checked the source platform guards, verified all four methods remain present in the saved discovery, and verified none appears in the executed TRX definitions/results. All 74 applicable ScriptWorker cases ran successfully. The runner verifies named exclusions during discovery, cannot exclude an entire required class, rejects an excluded method appearing in results, and continues rejecting unexpected skips. This is an applicability declaration, not a claim that Windows-specific behavior ran on macOS.
|
||||
|
||||
**Final approval covers P04 publication, ownership, partitioned cache/snapshot foundations, local caller-bound ports and deployment catalog staging.** It does not claim completion of later gRPC transports/streams/writes/mounts, production Host DI (P07), imported SDK timestamp consumption (P08), disposable integration fixtures or final feature validation. The historical checkpoint entries below retain the progression from open findings to their verified corrections; their earlier conditional/pending statements are superseded by this final disposition.
|
||||
|
||||
## Rereview evidence
|
||||
|
||||
Saved run `20261116T051418.493232Z-1a9b4de9e45b/unit/P04/run.json` records **155 Runtime, 16 Core.Abstractions, 16 Commons and 77 SDK passing tests**, with zero failures/skips in those completed projects. The overall run is **failed**, because the selected ScriptWorker run contained unexpected platform skips; no completed phase gate is inferred. The reviewer inspected the report and reconciled its recorded hashes for all 14 reread publication/hub/local-service source files and focused test files; each matched. Catalog staging is separately in progress and is not a new absence finding in this review.
|
||||
|
||||
The original findings below preserve their initial trigger. Resolution applies only where explicitly stated; additional concrete regressions found during rereview are recorded afterward.
|
||||
|
||||
## H1 — Remove blocking and partition-wide producer work
|
||||
|
||||
**Severity: High. Status: resolved in reviewed source and completed Runtime gate.** In the initial `Runtime/DataConnections/SourceSamplePublisher.cs`, capture, publication admission, commit and the `finally` in-flight decrement all took the global `_gate`. `RetireDriver` and `PublishDriverStatus` walked the driver's sources under that same gate; publication also invoked the serving provider and hub commit while holding it. A paused control operation or unrelated source could therefore block a driver callback before its mailbox enqueue. The initial `SamplePartition.InvalidatePartition` also synchronously traversed every source and released queued/dirty/change work when producer admission overflowed. Neither behavior meets Task 9's bounded nonblocking producer contract.
|
||||
|
||||
Use nonblocking source admission with an immediate generation/retirement fence, and move whole-partition cleanup off the producer thread. A rejected publication must invalidate readiness without waiting for another publisher or a partition worker. Exercise a real publisher with a deliberately blocked lifecycle/serving operation and an unrelated callback; also prove that overflow does not traverse a large source population on the caller thread. Include retirement and rebind races so the replacement does not allow stale samples through.
|
||||
|
||||
**Correction:** callback capture uses concurrent routes, commit uses per-source `Monitor.TryEnter`, and producer retirement shares an immediate fence with the hub. Partition invalidation advances an epoch and schedules cleanup. The repair queue is bounded at 4,096 entries, processes bounded batches and limits repeated repair attempts. The reviewer inspected blocked-status/unrelated-callback, immediate retirement, busy-partition and deferred-overflow-cleanup regressions included in the completed 155-test Runtime gate. These resolve the original blocking/traversal finding; the separate H3 and M4 findings still apply.
|
||||
|
||||
## H2 — Retire producer identity on supervision and unexpected termination
|
||||
|
||||
**Severity: High. Status: resolved, including the resource-lifetime residual.** `DriverInstanceActor.PostStop` (approximately line 2088 in the initial candidate) queues `ConnectivityChanged` and detaches handlers, but does not retire its source identity. `PostRestart` requests reprovisioning; `DriverHostActor.ReprovisionChild` (approximately line 4289) reinitializes the same ActorRef without changing the readonly source incarnation carried in Props. A callback retained by the previous actor instance can consequently capture a still-current producer ticket and publish after the restart or its status event. The ordinary deploy replacement path's retirement does not cover this case.
|
||||
|
||||
`VirtualTagActor.PostStop` at line 262 only cancels its timer and unregisters from the mux. `VirtualTagHostActor.OnChildTerminated` (approximately line 381) removes child/plan entries without retiring the producer. Unexpected termination can leave the hub's previous sample Ready, and the host retains the token for a later respawn. An asynchronous completion from an earlier actor instance must likewise not become a new acquisition in its replacement.
|
||||
|
||||
Retire the old producer synchronously at the actual lifecycle boundary, arrange a distinct valid identity for the replacement, and release/invalidate its old source state. Test supervision of the real driver actor with a retained old callback, and unexpected stop/restart of a real virtual actor with an old asynchronous evaluation. Verify unavailability during the gap, rejection of old work, and recovery only from the replacement's fresh acquisition.
|
||||
|
||||
**Rereview:** driver and virtual `PostStop` now retire the producer, and `PreStart` renews a retired identity. Virtual asynchronous completions carry a distinct actor incarnation checked before application. The real driver supervision and stopped-virtual-actor tests pass in the completed Runtime gate. However, `SourceSamplePublisher.RetireVirtualIncarnation` at approximately line 278 retires/removes only the producer fence, leaving its source ticket, routes and cached payload. `VirtualTagHostActor.OnApply` at lines 122–123 retires before attempting `TryCaptureVirtual`; that capture now fails, so `TryRemove` never runs. `SamplePartition.Current` denies the retired fence but does not mark the source Removed, and tombstone reclamation only handles Removed states. Repeated deletion of virtual IDs therefore retains source capacity and payload charges indefinitely. Remove the matching old binding after the immediate fence, preserving newer-incarnation protection, and verify actual virtual-host removal churn returns resource/source capacity.
|
||||
|
||||
## M1 — Reconcile publisher bindings after routing reset and failed initial bind
|
||||
|
||||
**Severity: Medium. Status: resolved, including the quiet-initial-batch residual.** The initial `SourceSamplePublisher.EnsureBinding` returned success whenever its private ticket's incarnation matched. `PartitionedSampleHub.Repartition` clears hub registrations but does not clear those private tickets. Subsequent publication then fails permanently while `EnsureBinding` continues to report success. Initial `EnsureDriverBinding` and `EnsureVirtualBinding` admission failures were also ignored by their actor callers, leaving a source with no route and no retry.
|
||||
|
||||
Check current hub routing when reconciling bindings and provide bounded recovery for temporary admission contention. Recovery must install a new unavailable generation and wait for a real acquisition; it must not replay a dropped value as fresh. Cover the actual publisher plus hub through repartition, failed initial driver bind and failed initial virtual bind, including a source whose initial callback is quiet afterward.
|
||||
|
||||
**Rereview:** the nonblocking ticket check, lifecycle advancement and bounded repair queue recover an actual publisher/hub after repartition; the dedicated test passes. H3 legacy-delivery independence is now corrected. M1 nevertheless remains open for the quiet initial batch residual documented in the focused correction review below.
|
||||
|
||||
## M2 — Publish real equal-value virtual acquisitions before legacy deduplication
|
||||
|
||||
**Severity: Medium. Status: resolved in reviewed source and completed Runtime gate.** The initial `VirtualTagActor.ApplyEvaluation` returned on equal value/status before calling the source publisher. Once hub overflow or contention invalidated that source, subsequent successful evaluations with the same value never reached the hub, so it remained unavailable indefinitely and acquisition age/timestamps did not advance.
|
||||
|
||||
Publish each actual completed evaluation before the optional SDK value/status deduplication. Keep `VirtualTagEvalResult.NoChange` and deploy `ReassertValue` excluded: neither represents a new acquisition. A real actor regression should publish an initial value, invalidate the hub, then complete a successful equal-value evaluation and verify recovery with that evaluation's actual timestamps.
|
||||
|
||||
**Correction:** `ApplyEvaluation` places source publication after the `NoChange` guard and before legacy deduplication. `Equal_fresh_virtual_evaluation_recovers_invalidated_hub_without_sdk_duplicate` exercises the real actor and hub, verifies the equal-value acquisition's timestamp and preserves SDK deduplication; it passes in the completed Runtime gate.
|
||||
|
||||
## M3 — Preserve held-value age and timestamps on virtual failures
|
||||
|
||||
**Severity: Medium. Status: resolved in reviewed source and completed Runtime gate.** The initial `VirtualTagActor.OnInputsBad` (approximately line 527) and `OnEvaluationFailed` (approximately line 561) call `PublishSource` with the previous `_lastValue` and the new failure trigger time. `PublishSource` creates a full acquisition with both timestamps set to that time. The partition consequently resets the monotonic received time too. A failure has changed quality, but the old payload is now represented as freshly acquired; an initial failure can also create a sample when no successful evaluation ever occurred.
|
||||
|
||||
Use the source status-only path for held-value failures. Preserve the previous acquisition's timestamps and monotonic age; without an acquired sample, keep waiting-for-initial-data semantics. The existing driver status path already demonstrates this distinction. Verify success at T1 followed by bad input/evaluator failure at T2 retains T1 and the original age, and that initial failure cannot create a fresh sample. Existing legacy SDK/historian presentation may remain separate.
|
||||
|
||||
**Correction:** both virtual failure paths call `PublishSourceStatus`, preserving the cached acquisition. The actual-actor initial-failure and later-failure theory passes, verifying absent initial sample, original timestamps, retained value/changed quality and unchanged monotonic received time.
|
||||
|
||||
## H3 — Keep legacy driver delivery independent of hub admission
|
||||
|
||||
**Severity: High. Status: resolved in the focused correction candidate.** `DriverInstanceActor.Subscribe` at approximately lines 1488–1507 first unsubscribes an existing handle, then returns before attaching callbacks or calling driver Subscribe whenever any `EnsureDriverBinding` fails. It retries the entire request every 250 ms. A full hub source/byte budget or unavailable declared shape can therefore prevent the physical subscription indefinitely; a subscription update can also tear down previously healthy SDK/mux/history delivery. The new bounded feed must not become an availability dependency for the established local path.
|
||||
|
||||
Proceed with the legacy subscription independently, fail the new source unavailable, and recover its binding through bounded work. Recovery must obtain a genuine fresh acquisition without replaying a dropped payload as fresh. Test a real actor against a deliberately full hub and verify driver Subscribe and legacy callback delivery continue, including an existing-subscription update. Replace the current test expectation that admission failure prevents the driver from subscribing.
|
||||
|
||||
## M4 — Retain source charges across repartition while owners remain
|
||||
|
||||
**Severity: Medium. Status: resolved in the focused correction candidate.** `SamplePartition.Dispose` at approximately line 435 releases every `SourceCharge` and decrements tracked-source count unconditionally. `PartitionedSampleHub.Repartition` calls it while recipient-owned reads and ingress reservations may still retain the old `SourceState`, ticket and source-key strings. Ordinary tombstone reclamation correctly waits for Readers, Reservations and Snapshots; repartition bypasses that protection and reopens node-wide capacity before this storage is released.
|
||||
|
||||
Retire the old partition and preserve each retained source charge/count until its final owner releases, with exactly-once accounting and no possibility of old ticket resurrection. Cover held read and ingress leases across repartition with long keys and tight source/byte limits; releasing the final lease should return capacity exactly once.
|
||||
|
||||
## M5 — Canonicalize the source cluster consistently
|
||||
|
||||
**Severity: Medium. Status: resolved in the focused correction candidate.** `LocalExportCatalog.Compilation.cs` around line 125 constructs driver source keys using `snapshot.ClusterId`. `DriverHostActor` around line 4034 passes the driver row's original `spec.ClusterId` into `EnsureDriverBinding`, which constructs the acquisition key from that string verbatim. Cluster membership/foreign-key matching accepts case variants, while `BackingSourceKey` record equality is case-sensitive. A driver row belonging to `CLUSTER-A` under canonical snapshot `cluster-a` can publish successfully into a cache key that its valid catalog never finds, leaving reads waiting for initial data.
|
||||
|
||||
Use the same trusted canonical origin-cluster identity at the shared source-key boundary. Preserve separately declared identity comparison rules for references and serving identities. Add a catalog/producer parity regression using mixed-case cluster foreign keys and the canonical cluster root. No virtual FolderPath hierarchy finding is raised: the current composer emits an empty virtual FolderPath.
|
||||
|
||||
## Reviewed boundaries and outstanding integration obligations
|
||||
|
||||
- `OwnedDataSample` estimates and rejects unsupported/oversized payloads before hub copying. The supported array/byte payload is copied before actor enqueue, and downstream legacy envelopes copy producer-owned arrays too. The hub's immutable `DataValue` retention is independently disposable and budgeted. Legacy actor/sink queues and arbitrary nested legacy payload serialization remain outside the new hub's bounded-ingress claim.
|
||||
- Original driver source/server timestamps are independently optional; the source feed does not duplicate the legacy collapsed timestamp. Status-only hub updates preserve acquisition timestamps and receive age. Initial status without a value does not manufacture Good/null.
|
||||
- Reservation, cache, read and snapshot ownership have explicit release paths. Shared budgeting includes source records, admitted payloads, controls, retained references and snapshot items across partitions. New binding identity fences prevent an old ticket from targeting a fresh binding even when key and numeric generation are reused. Ordinary source reclamation waits for reads, ingress reservations and snapshots, and its churn/owner-lifetime regressions pass; the H2 virtual-retirement and M4 repartition residuals remain.
|
||||
- Snapshot capture retains immutable samples with partition watermarks and epoch checks. Cancellation, expiry, overflow, removal and repartition must reset/release the snapshot, and an independent delta read carries its own charge. Later stream/frame writers must retain their own charged references and perform the final publication gate; this checkpoint does not establish P06 wire delivery safety.
|
||||
- Internal pre-activation acquisition may carry zero catalog/authority epochs. Public `DataSample.Validate` and wire codecs remain strict. The reviewed local read facade checks current catalog/authority, current source identity, type and caller policy before overlaying the trusted serving header, preserving original payload, version, age and timestamps. Returned values retain global resource charges and expose a publication lease invalidated by source/partition or authority changes. The quiet provisional-acquisition and prepared-response invalidation tests pass. Final transport use of that gate remains a later obligation.
|
||||
- Local browse/metadata/read uses an origin-only immutable catalog, caller-bound credentials, export and local ACL decisions, bounded pages, and authenticated continuations tied to the caller and serving generation. Unknown, denied, initial, invalidated and over-age reads remain distinct. Imported views are excluded. Unsupported write/subscription adapters remain explicitly unavailable at this stage. Production catalog staging/Host activation is a separately scheduled review, not a new absence finding here.
|
||||
- Task 10 and Host wiring remain review obligations: actual singleton ownership/disposal, shared catalog projection, activation failure/no-op/authority transitions, local policy and caller binding, missing/denied/waiting/over-age read results, capability availability, and source lifecycle/repartition recovery through the production graph. This document does not approve those unfinished boundaries or the complete gRPC feature.
|
||||
|
||||
All original and rereview findings were sent directly to the coordinator. Final disposition requires the remaining corrections, separate production-staging review and the coordinator's complete applicable gate, with saved candidate identity reconciled to the source reviewed here. The current partial pass is not P04 or complete-feature approval.
|
||||
|
||||
## Task 10 staging review
|
||||
|
||||
**Disposition: incomplete pending the agreed correction batch and M6.** The focused run `20261116T053226.727293Z-11a44bee32b8/unit/P04/run.json` passed all eight `GrpcDataCatalogStagingTests`, with no failures/skips. The reviewer inspected its report and confirmed the recorded `LocalCatalogCoordinator.cs` and staging-test hashes match the reviewed files. This is a focused staging pass, not a full P04 gate. The reviewed paths include `CatalogAttempt`, provisional activation authority, `ParseLocalCatalogSnapshot`, normal apply, cached boot, restore, headless completion and the joined publisher attempt. Production Host DI remains scheduled for P07 and is not an absence finding here.
|
||||
|
||||
The coordinator already identified three corrections before this review; they are recorded as agreed work, not new findings: cache a coherent role-adjusted catalog wrapper rather than allocating a new one on every access; fail eligibility closed when supplied serving NodeId differs from the host's local NodeId; and move cached/restore publisher sends after fallible desired-subscription work. These require the worker's tests-first correction and rereview.
|
||||
|
||||
The attempt coordinator uses exact object identity for authority installation, staging and completion; an older attempt cannot reinstall authority or activate its catalog after `BeginAttempt` closes it. The activation epoch advances even for a repeated artifact hash, so the staged token cannot revive an earlier completed catalog. Credentials are installed independently before catalog compilation and driver reconciliation; failed catalog topology does not roll back an already parsed revocation. Joined publisher requests do not begin a second activation, and publisher completion activates only the matching staged attempt. `PlanReady`/`PlanFailed` from another actor incarnation are rejected, while completion from a superseded attempt is rejected by the coordinator. These are sound source boundaries in the reviewed candidate. Actual stale-plan interleavings and corrected cache/restore failure paths still need applicable evidence.
|
||||
|
||||
### M6 — Make failed expected catalog activation retryable through deployment dispatch
|
||||
|
||||
**Severity: Medium. Status: resolved in final staging rereview.** `DriverHostActor.HandleArtifactForApply` around lines 3066–3068 ignores a false result from `LocalCatalogCoordinator.Complete`, then headless `AwaitAddressSpaceOutcomeThenAck` around line 3127 marks the revision confirmed and sends a clean Applied acknowledgment. With an SDK publisher, `FinishRebuild` around lines 1216–1219 also ignores failed catalog completion and reports only the sink outcome. A failed expected catalog stage or activation with successful legacy topology can therefore be recorded as clean. `HandleDispatchFromSteady` around lines 2859–2869 subsequently short-circuits the same revision, preventing operator redispatch from retrying catalog repair.
|
||||
|
||||
Keep legacy availability independent, but include failure of an expected data catalog in deployment degraded/unconfirmed status. Ordinary artifacts with no expected data catalog must retain their compatibility behavior. Test an actual host dispatch with a transient catalog-stage failure followed by redispatch of the same revision, verifying a new attempt and eventual readiness. The existing same-revision test invokes `BeginAttempt` directly and does not exercise the host dispatch short-circuit.
|
||||
|
||||
The staging corrections and M6 were sent to the coordinator. This review stops at the requested checkpoint while source/hub and staging workers apply their separate verified corrections; it makes no overall phase approval.
|
||||
|
||||
|
||||
## Focused source/hub correction review
|
||||
|
||||
The source run `20261116T054124.390909Z-bfd4f5cc2345` passed **35/35**, and the hub run `20261116T054353.930760Z-80fdd94dde21` passed **20/20**, both with zero failures/skips. The reviewer inspected both saved reports and reconciled the recorded hashes for the publisher, partition/hub/snapshot sources and their two focused test classes; each matched. Staging files were actively being corrected separately and were excluded from this focused rereview. These results do not constitute the full P04 gate.
|
||||
|
||||
- **H2 resolved:** virtual retirement immediately closes the producer fence, then removes only the route whose producer object matches that retired identity. Registering a replacement cleans the previous binding too. Real virtual-actor churn with a one-source limit returns capacity, and stale retirement cannot close a replacement. The prior fence-only leak is corrected.
|
||||
- **H3 resolved:** failed initial hub admission no longer prevents physical Subscribe or legacy callback delivery. Initial binding work and subsequent retries are bounded batches; a single versioned timer with capped backoff cannot accumulate retry messages or tear down the active subscription. Missing and unsupported shapes remain unavailable in the new feed while legacy delivery proceeds. Recovery waits for an actual new source event and never replays the dropped payload as fresh. The full-hub and missing/unsupported-shape actor regressions pass. The remaining initial-batch coverage issue is M1 below.
|
||||
- **M4 resolved:** a source now has a registry metadata owner plus an owner for every retained read, reservation and snapshot. Partition disposal retires old binding fences and releases only the registry owner. The source byte charge and tracked-source count are released exactly once when the last metadata owner goes away. Ordinary reclamation, failed old commit, repeated disposal and repartition remain fenced. Four long-key cases cover read/reservation retention against both byte and source-count limits; a separate regression rejects the old ticket after partition disposal.
|
||||
- **M5 resolved:** shared driver and virtual source-key factories canonicalize only the origin-cluster string with invariant uppercase. Driver/reference, virtual ID, node and incarnation remain opaque and case-preserving. The catalog and producers both use these factories. The case-parity regression verifies canonical cluster equality and distinguishes opaque identifier variants.
|
||||
|
||||
### M1 residual — Preserve quiet initial acquisitions beyond the preparation batch
|
||||
|
||||
`DriverInstanceActor.HandleSubscribeAsync` around line 1506 prepares only `SourceBindingBatchSize` (128) references before calling the driver's Subscribe for the entire list. `PublishSource` around line 1986 only captures an existing route and silently returns when none exists. Consequently, even with ample hub capacity and valid types, a driver subscribing more than 128 quiet sources and synchronously emitting its initial batch loses every new acquisition after the first 128. The later timer creates those bindings but does not obtain a fresh acquisition; those sources remain waiting indefinitely if the device values do not change. The existing corrected tests each use one source and do not cover this ordinary healthy case.
|
||||
|
||||
Complete healthy initial preparation in bounded stages without waiting indefinitely for failed admissions, or use an equivalent nonblocking callback-admission/fresh-acquisition strategy. Preserve H3's legacy availability under pressure and the prohibition on replaying an old payload as fresh. Add an actual actor/driver regression with at least 129 quiet initial values and sufficient hub capacity, verifying that every admissible source obtains its real initial sample.
|
||||
|
||||
This residual was sent directly to the coordinator. Source/hub findings H2/H3/M4/M5 are closed; M1 remains open. Staging corrections, M6 and the full phase gate remain separate pending work.
|
||||
|
||||
|
||||
## Final targeted M1 correction review
|
||||
|
||||
**M1 resolved.** The reviewer inspected the actual RED TRX from `20261116T054854.714447Z-3f6eb6203de4`: the 130-source sole-initial-batch actor test failed because `source-128` had no admitted ticket. The subsequent focused run `20261116T055309.152744Z-9dee8a78ffeb` passed **36/36**, zero failures/skips, including that regression and the H3 pressure cases. Recorded publisher, hub/partition and source-test hashes match the reread candidate.
|
||||
|
||||
When a current driver callback has no route, it now attempts admission using the registered trusted shape and current producer incarnation. Admission uses `Monitor.TryEnter` for both the publisher control gate and an existing per-source gate; creating a new slot under the already-held control gate cannot wait behind a competing creator. The hub retains its nonblocking admission and retirement checks. The callback then recaptures the valid ticket and publishes that same actual acquisition, preserving its original timestamps. It neither queues a historical payload for later replay nor makes legacy subscription success depend on hub admission. Missing shapes, retired producers, contention and capacity rejection remain fail-closed for the new feed while the legacy callback proceeds.
|
||||
|
||||
The actual batch-capable driver regression emits all 130 initial values once, verifies one legacy subscription and one full legacy batch, then verifies every hub source, value and original timestamp. H2/H3/M4/M5 remain resolved; no additional source/hub blocker was found in this narrow review. Staging files were excluded, and neither this focused pass nor these source resolutions approve the overall P04 phase.
|
||||
|
||||
|
||||
## Final staging source rereview
|
||||
|
||||
**M6 and the three agreed staging corrections are resolved.** The reviewer inspected `20261116T055656.284057Z-33ba66cac80e/unit/P04/run.json`, which passed **19/19 staging tests**, zero failures/skips. Recorded coordinator, catalog/local-service and staging-test hashes matched the reread candidate. The source/hub corrections remain resolved by their earlier focused gates; this pass did not reopen unrelated source/hub work.
|
||||
|
||||
- `LocalCatalogCoordinator.Current` caches a role-adjusted wrapper using compare/exchange. Reads make a bounded number of lock-free identity/role/activity checks and return unavailable during unresolved churn; the producer never waits on the coordinator's staging lock. The role transition reuses the immutable node catalog and does not change acquisition timestamps, version or monotonic receive age. The role-wrapper identity and retained-acquisition regression passes.
|
||||
- Host and standalone publisher staging require the serving NodeId to match the actual actor's local NodeId. Coordinator staging also checks the exact serving node against enabled, non-maintenance membership in the authority's cluster. The materialized snapshot parser requires one eligible node and one enabled matching cluster before supplying a snapshot. Failed eligibility does not roll back independently installed credentials.
|
||||
- Cache boot and Direct restore perform desired-subscription work before sending publisher completion work. Throwing work closes the attempt and prevents the send. Direct restore reuses its loaded `appliedBlob`, eliminating the redundant database read; the regression limits the DB factory to Bootstrap plus artifact load and observes the real deferred driver's Subscribe references. Four cache/restore ordering/failure cases pass.
|
||||
- A failed **expected** catalog activation now contributes degraded/unconfirmed deployment status in both headless and publisher-backed apply. Actual host redispatch of the same revision retries and advances the attempt epoch after a transient provenance failure; both variants pass. Artifacts without data configuration, or with well-formed empty data sections, preserve clean legacy behavior. Cache boot remains unconfirmed until a subsequent real dispatch; Direct restore marks failed or unconfirmed expected catalog work accordingly.
|
||||
- Exact attempt identity, staged-epoch activation, stale-attempt authority rejection and independent revocation behavior remain intact. Catalog failure does not undo parsed key revocation; a previously completed catalog stays inactive after a new attempt, including a repeated revision hash. The joined host/publisher path uses one attempt and waits for successful topology before serving it.
|
||||
|
||||
No remaining source blocker was found in this final staging scope. The source checkpoint is approved **conditional on the complete applicable P04 gate and reconciliation of its candidate identity**. Production Host DI is still P07; transport final-send use of the publication lease and imported SDK timestamp consumption remain later planned obligations. This source approval does not imply completion of the whole gRPC feature.
|
||||
@@ -76,7 +76,7 @@ def command(project, expression, directory, discovery=False):
|
||||
return argv + (["--list-tests"] if discovery else ["--logger", "trx;LogFileName=results.trx"])
|
||||
|
||||
|
||||
def validate_trx(directory, started_ns, expected_classes=()):
|
||||
def validate_trx(directory, started_ns, expected_classes=(), excluded_methods=()):
|
||||
files = list(directory.rglob("*.trx"))
|
||||
if not files:
|
||||
raise GateError("missing TRX result")
|
||||
@@ -108,9 +108,11 @@ def validate_trx(directory, started_ns, expected_classes=()):
|
||||
for unit in root.findall(".//{*}TestDefinitions/{*}UnitTest"):
|
||||
method = unit.find("{*}TestMethod")
|
||||
if method is not None:
|
||||
definitions[unit.get("id")] = method.get("className", "").split(",", 1)[0]
|
||||
definitions[unit.get("id")] = (method.get("className", "").split(",", 1)[0], method.get("name", ""))
|
||||
for result in results:
|
||||
class_name = definitions.get(result.get("testId"), "")
|
||||
class_name, method_name = definitions.get(result.get("testId"), ("", ""))
|
||||
if class_name + "." + method_name in excluded_methods:
|
||||
raise ValueError("excluded method present in results: " + class_name + "." + method_name)
|
||||
for expected in expected_classes:
|
||||
if class_name == expected or class_name.endswith("." + expected):
|
||||
executed_classes.add(expected)
|
||||
@@ -148,16 +150,38 @@ def selected_records(manifest, phase, root, case):
|
||||
return records
|
||||
|
||||
|
||||
def run_phase(manifest, phase, root, case=None, dry_run=False, invoke=subprocess.run, environ=None):
|
||||
def platform_exclusions(item, platform, case):
|
||||
declared = item.get("platform_exclusions", {})
|
||||
if not isinstance(declared, dict) or set(declared) - {"windows", "non_windows"}:
|
||||
raise GateError("invalid platform exclusions")
|
||||
for values in declared.values():
|
||||
if not isinstance(values, list) or any(
|
||||
not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)+", name)
|
||||
for name in values
|
||||
) or len(values) != len(set(values)):
|
||||
raise GateError("invalid platform exclusions")
|
||||
names = declared.get("windows" if platform == "win32" else "non_windows", [])
|
||||
return [name for name in names if not case or class_matches(name, case)]
|
||||
|
||||
|
||||
def execution_filter(expression, excluded):
|
||||
if not excluded:
|
||||
return expression
|
||||
return "(" + expression + ")" + "".join("&(FullyQualifiedName!=" + name + ")" for name in excluded)
|
||||
|
||||
|
||||
def run_phase(manifest, phase, root, case=None, dry_run=False, invoke=subprocess.run, environ=None, platform=None):
|
||||
root = Path(root).resolve()
|
||||
records = selected_records(manifest, phase, root, case)
|
||||
platform = sys.platform if platform is None else platform
|
||||
exclusions = [platform_exclusions(item, platform, case) for item in records]
|
||||
run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ") + "-" + uuid.uuid4().hex[:12]
|
||||
directory = root / "artifacts" / "grpc-data" / run_id / "unit" / phase
|
||||
if dry_run:
|
||||
for index, item in enumerate(records):
|
||||
target = directory / f'{index:02d}-{Path(item["project"]).stem}'
|
||||
print(shlex.join(command(item["project"], item["filter"], target, True)))
|
||||
print(shlex.join(command(item["project"], item["filter"], target)))
|
||||
print(shlex.join(command(item["project"], execution_filter(item["filter"], exclusions[index]), target)))
|
||||
return directory
|
||||
directory.mkdir(parents=True, exist_ok=False)
|
||||
env = unit_environment(environ)
|
||||
@@ -190,7 +214,9 @@ def run_phase(manifest, phase, root, case=None, dry_run=False, invoke=subprocess
|
||||
for index, item in enumerate(records):
|
||||
target = directory / f'{index:02d}-{Path(item["project"]).stem}'
|
||||
target.mkdir()
|
||||
excluded = exclusions[index]
|
||||
entry = {"project": item["project"], "filter": item["filter"],
|
||||
"platform": platform, "platform_exclusions": excluded,
|
||||
"new_classes": item.get("new_classes", []), "existing_classes": item.get("existing_classes", [])}
|
||||
report["projects"].append(entry)
|
||||
tick = time.monotonic()
|
||||
@@ -201,24 +227,32 @@ def run_phase(manifest, phase, root, case=None, dry_run=False, invoke=subprocess
|
||||
if case:
|
||||
names = [name for name in names if class_matches(name, case)]
|
||||
required_classes = item.get("new_classes", []) + item.get("existing_classes", [])
|
||||
mapping = {name: [test for test in names if class_matches(test, name)] for name in required_classes}
|
||||
available = {name.split("(", 1)[0] for name in names}
|
||||
applicable = [name for name in names if name.split("(", 1)[0] not in excluded]
|
||||
mapping = {name: [test for test in applicable if class_matches(test, name)] for name in required_classes}
|
||||
write_json(target / "discovery.json", {
|
||||
"filter": item["filter"], "tests": names,
|
||||
"filter": item["filter"], "tests": names, "platform": platform,
|
||||
"platform_exclusions": excluded,
|
||||
"new_classes": {name: mapping[name] for name in item.get("new_classes", [])},
|
||||
"existing_classes": {name: mapping[name] for name in item.get("existing_classes", [])},
|
||||
})
|
||||
if not names:
|
||||
raise GateError(f"zero discovered tests for {item['project']}")
|
||||
missing_exclusions = sorted(set(excluded) - available)
|
||||
if missing_exclusions:
|
||||
raise GateError("missing platform exclusions in discovery: " + ", ".join(missing_exclusions))
|
||||
if not applicable:
|
||||
raise GateError(f"zero applicable discovered tests for {item['project']}")
|
||||
absent = [name for name, tests in mapping.items() if not tests]
|
||||
if absent:
|
||||
raise GateError(f"missing required classes: {', '.join(absent)}")
|
||||
expression = item["filter"]
|
||||
expression = execution_filter(item["filter"], excluded)
|
||||
execution = command(item["project"], expression, target)
|
||||
entry["execution_filter"] = expression
|
||||
entry["execution_argv"] = execution
|
||||
before = time.time_ns()
|
||||
_, entry["execution_seconds"] = child(execution, target, "execution")
|
||||
entry["trx"] = validate_trx(target, before, required_classes)
|
||||
entry["trx"] = validate_trx(target, before, required_classes, excluded)
|
||||
entry["duration_seconds"] = time.monotonic() - tick
|
||||
report["status"] = "passed"
|
||||
return directory
|
||||
|
||||
@@ -206,6 +206,59 @@ class UnitPhaseRunnerTests(unittest.TestCase):
|
||||
self.assertEqual(self.calls, [])
|
||||
self.assertFalse((self.root / "artifacts").exists())
|
||||
|
||||
def test_platform_exclusions_are_verified_and_recorded_before_execution(self):
|
||||
self.manifest["P00"][0]["platform_exclusions"] = {
|
||||
"non_windows": ["Example.OldTests.WindowsOnly"],
|
||||
"windows": ["Example.OldTests.UnixOnly"],
|
||||
}
|
||||
self.listing += " Example.OldTests.WindowsOnly\n Example.OldTests.UnixOnly\n"
|
||||
for platform, excluded in (("darwin", "Example.OldTests.WindowsOnly"),
|
||||
("win32", "Example.OldTests.UnixOnly")):
|
||||
with self.subTest(platform=platform):
|
||||
directory = self.run_gate(platform=platform)
|
||||
report = json.loads((directory / "run.json").read_text())["projects"][0]
|
||||
discovery = json.loads(next(directory.rglob("discovery.json")).read_text())
|
||||
self.assertEqual(report["platform"], platform)
|
||||
self.assertEqual(report["platform_exclusions"], [excluded])
|
||||
self.assertEqual(discovery["platform_exclusions"], [excluded])
|
||||
self.assertIn("FullyQualifiedName!=" + excluded, report["execution_filter"])
|
||||
self.assertNotIn("FullyQualifiedName!=", report["filter"])
|
||||
|
||||
def test_missing_platform_exclusion_fails_before_execution(self):
|
||||
self.manifest["P00"][0]["platform_exclusions"] = {"non_windows": ["Example.OldTests.Missing"]}
|
||||
with self.assertRaisesRegex(runner.GateError, "missing.*exclu"):
|
||||
self.run_gate(platform="darwin")
|
||||
self.assertFalse(any(a[0] == "dotnet" and "--list-tests" not in a for a, _ in self.calls))
|
||||
|
||||
def test_exclusions_cannot_mask_a_required_class(self):
|
||||
self.manifest["P00"][0]["platform_exclusions"] = {"non_windows": ["Example.OldTests.Works"]}
|
||||
with self.assertRaisesRegex(runner.GateError, "OldTests"):
|
||||
self.run_gate(platform="darwin")
|
||||
|
||||
def test_case_excludes_only_methods_in_selected_class(self):
|
||||
self.manifest["P00"][0]["platform_exclusions"] = {"non_windows": ["Example.OldTests.WindowsOnly"]}
|
||||
self.listing = "The following Tests are available:\n Example.NewTests.Works\n"
|
||||
self.run_gate(case="NewTests", platform="darwin")
|
||||
|
||||
def test_excluded_method_in_results_is_rejected(self):
|
||||
self.manifest["P00"][0]["platform_exclusions"] = {"non_windows": ["Example.OldTests.WindowsOnly"]}
|
||||
self.listing += " Example.OldTests.WindowsOnly\n"
|
||||
original = self.fake
|
||||
def unexpected(argv, **kwargs):
|
||||
result = original(argv, **kwargs)
|
||||
if argv[0] == "dotnet" and "--list-tests" not in argv:
|
||||
path = Path(argv[argv.index("--results-directory") + 1]) / "results.trx"
|
||||
path.write_text(path.read_text().replace('className="Example.OldTests" name="Works"',
|
||||
'className="Example.OldTests" name="WindowsOnly"'))
|
||||
return result
|
||||
with self.assertRaisesRegex(runner.GateError, "excluded.*result"):
|
||||
runner.run_phase(self.manifest, "P00", self.root, invoke=unexpected, platform="darwin")
|
||||
|
||||
def test_invalid_exclusion_is_rejected(self):
|
||||
self.manifest["P00"][0]["platform_exclusions"] = {"non_windows": ["Example.OldTests.Works|FullyQualifiedName~Other"]}
|
||||
with self.assertRaisesRegex(runner.GateError, "invalid.*exclu"):
|
||||
self.run_gate(platform="darwin")
|
||||
|
||||
def test_allowlist_removes_inherited_secrets_and_overrides_shared_sql(self):
|
||||
env = runner.unit_environment({"PATH": "/bin", "HOME": "/home/test",
|
||||
"OTOPCUA_CONFIG_TEST_SERVER": "shared-db", "OTOPCUA_CONFIG_CONNECTION": "secret",
|
||||
|
||||
@@ -127,7 +127,7 @@
|
||||
"P04": [
|
||||
{
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=P04)|FullyQualifiedName~.DriverInstanceActorBatchForwardTests.|FullyQualifiedName~.DriverHostActorBatchFanOutTests.|FullyQualifiedName~.DriverHostActorSourceRemovedTests.|FullyQualifiedName~.DriverHostActorCommsLossTests.|FullyQualifiedName~.OpcUaPublishActorBatchTests.|FullyQualifiedName~.OpcUaPublishActorStatusBatchTests.",
|
||||
"filter": "(Feature=GrpcData&Phase=P04)|FullyQualifiedName~.DriverInstanceActorBatchForwardTests.|FullyQualifiedName~.DriverHostActorBatchFanOutTests.|FullyQualifiedName~.DriverHostActorSourceRemovedTests.|FullyQualifiedName~.DriverHostActorCommsLossTests.|FullyQualifiedName~.OpcUaPublishActorBatchTests.|FullyQualifiedName~.OpcUaPublishActorStatusBatchTests.|FullyQualifiedName~.VirtualTagActorTests.|FullyQualifiedName~.VirtualTagHostActorTests.|FullyQualifiedName~.DependencyMuxTagUpstreamSourceTests.|FullyQualifiedName~.DriverHostActorRestartTests.|FullyQualifiedName~.DriverHostActorReprovisionStampTests.",
|
||||
"new_classes": [
|
||||
"GrpcDataSampleOwnershipTests",
|
||||
"GrpcDataSourceFeedParityTests",
|
||||
@@ -136,7 +136,8 @@
|
||||
"GrpcDataIngressOverflowTests",
|
||||
"GrpcDataLocalConnectionTests",
|
||||
"GrpcDataCachedReadTests",
|
||||
"GrpcDataLocalExportCatalogTests"
|
||||
"GrpcDataLocalExportCatalogTests",
|
||||
"GrpcDataCatalogStagingTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"DriverInstanceActorBatchForwardTests",
|
||||
@@ -144,7 +145,76 @@
|
||||
"DriverHostActorSourceRemovedTests",
|
||||
"DriverHostActorCommsLossTests",
|
||||
"OpcUaPublishActorBatchTests",
|
||||
"OpcUaPublishActorStatusBatchTests"
|
||||
"OpcUaPublishActorStatusBatchTests",
|
||||
"VirtualTagActorTests",
|
||||
"VirtualTagHostActorTests",
|
||||
"DependencyMuxTagUpstreamSourceTests",
|
||||
"DriverHostActorRestartTests",
|
||||
"DriverHostActorReprovisionStampTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.GrpcDataContractsTests.|FullyQualifiedName~.DataChangeBatchContractTests.",
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"GrpcDataContractsTests",
|
||||
"DataChangeBatchContractTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/ZB.MOM.WW.OtOpcUa.Commons.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.GrpcDataCodecTests.",
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"GrpcDataCodecTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.NodeManagerHistoryReadPagingTests.|FullyQualifiedName~.NodeManagerHistoryReadModifiedTests.|FullyQualifiedName~.DataPlaneAuthorizerTests.",
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"NodeManagerHistoryReadPagingTests",
|
||||
"NodeManagerHistoryReadModifiedTests",
|
||||
"DataPlaneAuthorizerTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.ProtocolTests.|FullyQualifiedName~.WorkerIsolationTests.|FullyQualifiedName~.WorkerSoftClockTests.",
|
||||
"platform_exclusions": {
|
||||
"non_windows": [
|
||||
"ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests.WorkerIsolationTests.The_pipe_acl_is_protected_and_admits_exactly_the_host_and_the_worker_identity",
|
||||
"ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests.WorkerIsolationTests.A_live_pipe_carries_the_acl_and_a_host_only_pipe_admits_the_host_alone",
|
||||
"ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests.WorkerIsolationTests.The_worker_token_is_restricted_privilege_free_and_reaches_only_what_its_identity_may",
|
||||
"ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests.WorkerIsolationTests.A_worker_under_the_identity_runs_scripts_with_a_restricted_token_and_a_plain_one_does_not"
|
||||
],
|
||||
"windows": [
|
||||
"ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests.WorkerIsolationTests.A_runner_configured_with_an_identity_off_windows_refuses_to_start_rather_than_fall_back"
|
||||
]
|
||||
},
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"ProtocolTests",
|
||||
"WorkerIsolationTests",
|
||||
"WorkerSoftClockTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests/ZB.MOM.WW.OtOpcUa.Driver.MTConnect.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.MTConnectObservationIndexTests.",
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"MTConnectObservationIndexTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests.csproj",
|
||||
"filter": "FullyQualifiedName~.OpcUaClientSdkValueBoundaryTests.",
|
||||
"new_classes": [],
|
||||
"existing_classes": [
|
||||
"OpcUaClientSdkValueBoundaryTests"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -246,7 +246,8 @@ public interface IOpcUaAddressSpaceSink
|
||||
/// <summary>One value write within a <see cref="IOpcUaAddressSpaceSink.WriteValues"/> batch.
|
||||
/// Same semantics per field as <see cref="IOpcUaAddressSpaceSink.WriteValue"/> (status verbatim).</summary>
|
||||
public readonly record struct ValueWrite(
|
||||
string NodeId, object? Value, uint StatusCode, DateTime SourceTimestampUtc, AddressSpaceRealm Realm);
|
||||
string NodeId, object? Value, uint StatusCode, DateTime SourceTimestampUtc, AddressSpaceRealm Realm,
|
||||
DateTime? OriginalSourceTimestampUtc = null, DateTime? OriginalServerTimestampUtc = null);
|
||||
|
||||
/// <summary>One status-only write within a <see cref="IOpcUaAddressSpaceSink.WriteStatuses"/> batch: the
|
||||
/// node's current VALUE is retained and only <paramref name="StatusCode"/> +
|
||||
|
||||
@@ -19,6 +19,28 @@ public sealed class DataValue : IDisposable
|
||||
{ Kind = kind; _payload = payload; Dimensions = dimensions; }
|
||||
public DataValueKind Kind { get; }
|
||||
public IReadOnlyList<int>? Dimensions { get; }
|
||||
/// <summary>A conservative, allocation-free estimate of retained value storage, in bytes.</summary>
|
||||
public long EstimatedRetainedBytes
|
||||
{
|
||||
get
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
checked
|
||||
{
|
||||
const long baseline = 256;
|
||||
if (_payload is byte[] bytes) return baseline + 32L + bytes.LongLength;
|
||||
if (_payload is string text) return baseline + 32L + 2L * text.Length;
|
||||
if (_payload is ArrayPayload array)
|
||||
{
|
||||
long size = baseline + 128L + 8L * (Dimensions?.Count ?? 0) + 48L * array.Elements.LongLength;
|
||||
if (array.Kind == DataValueKind.String)
|
||||
foreach (var element in array.Elements) size += 2L * ((string)element).Length;
|
||||
return size;
|
||||
}
|
||||
return baseline + 32L;
|
||||
}
|
||||
}
|
||||
}
|
||||
public static DataValue Null() => new(DataValueKind.Null, null);
|
||||
public static DataValue FromBytes(byte[] bytes) => new(DataValueKind.Bytes, (byte[])bytes.Clone());
|
||||
public static DataValue FromScalar(DataValueKind kind, object value)
|
||||
|
||||
@@ -43,3 +43,9 @@ public interface IDataConnectionFactory
|
||||
{
|
||||
IDataConnection Create(DataAuthenticatedContext context, DataTarget target);
|
||||
}
|
||||
|
||||
/// <summary>Final-send guard for metadata and values prepared by a caller-bound connection.</summary>
|
||||
public interface IDataConnectionPublicationGate
|
||||
{
|
||||
bool CanPublish(ServingIdentity expectedServing);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>A retained response's live publication fence and resource ownership.</summary>
|
||||
public interface IDataPublicationLease : IDisposable
|
||||
{
|
||||
bool IsValid { get; }
|
||||
}
|
||||
|
||||
public sealed record BrowseRequest(DataView Parent, string? Filter, string? Continuation, DataBudget Budget);
|
||||
public sealed record MetadataRequest(IReadOnlyList<DataView> Views, DataBudget Budget);
|
||||
public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? MaximumAge);
|
||||
public sealed record ReadRequest(IReadOnlyList<ReadItem> Items, DataBudget Budget);
|
||||
/// <summary>Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality.</summary>
|
||||
public sealed record ReadResult(string CorrelationId, DataItemStatus Status, DataReadiness Readiness,
|
||||
TimeSpan? Age, DataSample? Sample, string? Diagnostic) : IDisposable
|
||||
TimeSpan? Age, DataSample? Sample, string? Diagnostic, IDisposable? ResourceLease = null) : IDisposable
|
||||
{
|
||||
public void Dispose() => Sample?.Dispose();
|
||||
public void Dispose()
|
||||
{
|
||||
try { Sample?.Dispose(); }
|
||||
finally { ResourceLease?.Dispose(); }
|
||||
}
|
||||
}
|
||||
public sealed record WriteItem(string CorrelationId, string OperationId, DataView View, DataValue Value,
|
||||
long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget);
|
||||
|
||||
@@ -9,9 +9,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
/// <param name="Value">The raw value; null when <see cref="StatusCode"/> indicates Bad.</param>
|
||||
/// <param name="StatusCode">OPC UA status code (numeric value matches the OPC UA spec).</param>
|
||||
/// <param name="SourceTimestampUtc">Driver-side timestamp when the value was sampled at the source. Null if unavailable.</param>
|
||||
/// <param name="ServerTimestampUtc">Driver-side timestamp when the driver received / processed the value.</param>
|
||||
/// <param name="ServerTimestampUtc">Driver-side timestamp when the driver received / processed the value, or null if unavailable.</param>
|
||||
public sealed record DataValueSnapshot(
|
||||
object? Value,
|
||||
uint StatusCode,
|
||||
DateTime? SourceTimestampUtc,
|
||||
DateTime ServerTimestampUtc);
|
||||
DateTime? ServerTimestampUtc);
|
||||
|
||||
@@ -819,7 +819,7 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable,
|
||||
{
|
||||
StatusCode = snapshot.StatusCode,
|
||||
SourceTsTicks = snapshot.SourceTimestampUtc is { } source ? VariantCodec.ToUtc(source).Ticks : 0,
|
||||
ServerTsTicks = VariantCodec.ToUtc(snapshot.ServerTimestampUtc).Ticks,
|
||||
ServerTsTicks = snapshot.ServerTimestampUtc is { } server ? VariantCodec.ToUtc(server).Ticks : 0,
|
||||
};
|
||||
if (entry.Slots.TryGetValue(path, out var slot)) input.Slot = slot;
|
||||
else input.Path = path;
|
||||
|
||||
@@ -20,6 +20,8 @@ public sealed record DataCallerIdentity(string Principal, string? ApiKeyId, stri
|
||||
/// <summary>Transport-independent data-plane grant and credential policy.</summary>
|
||||
public sealed class DataOperationPolicy
|
||||
{
|
||||
/// <summary>The currently installed local authority generation, rechecked at publication boundaries.</summary>
|
||||
public long AuthorityEpoch => _authority.Current.GenerationId;
|
||||
private readonly IDataPlaneAuthoritySource _authority;
|
||||
private readonly IPermissionEvaluator _evaluator;
|
||||
private readonly TimeProvider _clock;
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
|
||||
/// <summary>Shared placement of equipment-owned values that are not raw-tag references.</summary>
|
||||
public static class DataScopeSubjects
|
||||
{
|
||||
/// <summary>Cannot match an authored name or inherit tag-only browse transit.</summary>
|
||||
public const string OwnedNodeSegment = "\u0000owned";
|
||||
public static NodeScope Owned(NodeScope owner) => owner with
|
||||
{ Segments = Array.AsReadOnly(owner.Segments.Append(OwnedNodeSegment).ToArray()) };
|
||||
}
|
||||
@@ -9815,7 +9815,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
SdkValueBoundary.FromClr(snapshot.Value),
|
||||
new StatusCode(snapshot.StatusCode),
|
||||
snapshot.SourceTimestampUtc ?? DateTime.MinValue,
|
||||
snapshot.ServerTimestampUtc);
|
||||
snapshot.ServerTimestampUtc ?? DateTime.MinValue);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
|
||||
|
||||
@@ -195,7 +195,7 @@ public sealed class DataPlaneAuthorizer
|
||||
/// own path — the owner's Browse TRANSIT (an ancestor of a Tag grant) is not inherited, so a principal holding
|
||||
/// only a Tag grant cannot enumerate the equipment's alarms and virtual tags by browsing.
|
||||
/// </summary>
|
||||
internal const string OwnedNodeSegment = "\u0000owned";
|
||||
internal const string OwnedNodeSegment = DataScopeSubjects.OwnedNodeSegment;
|
||||
|
||||
/// <summary>
|
||||
/// The single segment, directly under the UNS realm, that an identifier no live node holds is placed at
|
||||
|
||||
@@ -18,6 +18,27 @@ public sealed class CatalogActivation
|
||||
return new CapturedAuthority(this, current);
|
||||
}
|
||||
|
||||
/// <summary>Create an initially inactive token for a staged, not-yet-published catalog.</summary>
|
||||
internal IDataMappedCatalogAuthority CaptureStagedAuthority(long catalogEpoch, long authorityEpoch)
|
||||
{
|
||||
if (catalogEpoch <= 0 || authorityEpoch <= 0) throw new ArgumentOutOfRangeException(nameof(catalogEpoch));
|
||||
return new StagedAuthority(this, catalogEpoch, authorityEpoch);
|
||||
}
|
||||
|
||||
private sealed class StagedAuthority(CatalogActivation owner, long catalogEpoch, long authorityEpoch) : IDataMappedCatalogAuthority
|
||||
{
|
||||
public long CatalogEpoch => catalogEpoch;
|
||||
public long AuthorityEpoch => authorityEpoch;
|
||||
public bool IsActive
|
||||
{
|
||||
get
|
||||
{
|
||||
var current = owner.Current;
|
||||
return current.IsReady && current.CatalogEpoch == catalogEpoch && current.AuthorityEpoch == authorityEpoch;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CapturedAuthority(CatalogActivation owner, CatalogActivationState captured) : IDataMappedCatalogAuthority
|
||||
{
|
||||
public long CatalogEpoch => captured.CatalogEpoch;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Live process provenance and implemented capability limits, independent of any mount.</summary>
|
||||
public sealed class DataCapabilitiesProvider
|
||||
{
|
||||
private readonly Func<ServingIdentity> _serving;
|
||||
private readonly Func<bool> _ready;
|
||||
public DataCapabilitiesProvider(string clusterId, Func<ServingIdentity> serving, Func<bool> ready, DataLimits limits)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
|
||||
ClusterId = clusterId;
|
||||
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
|
||||
_ready = ready ?? throw new ArgumentNullException(nameof(ready));
|
||||
Limits = limits ?? throw new ArgumentNullException(nameof(limits));
|
||||
limits.Validate();
|
||||
}
|
||||
public string ClusterId { get; }
|
||||
public DataLimits Limits { get; }
|
||||
public ServingIdentity Serving => _serving();
|
||||
public bool IsReady => _ready();
|
||||
internal DataCapabilities Get(DataOperations operations, DataLimits limits)
|
||||
{
|
||||
var serving = Serving;
|
||||
var ready = IsReady;
|
||||
serving.Validate(requireEpochs: ready);
|
||||
if (!string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~DataOperations.Write;
|
||||
return new(1, 0, serving, ready ? DataReadiness.Ready : DataReadiness.Unavailable,
|
||||
ready ? operations : DataOperations.None,
|
||||
Enum.GetValues<DataValueKind>().Where(x => x != DataValueKind.Unspecified).ToHashSet(),
|
||||
limits, true, 1, ClusterId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Node-wide admission limits for the source cache and retained work.</summary>
|
||||
public sealed class DataResourceLimits
|
||||
{
|
||||
public int PartitionCount { get; init; } = 4;
|
||||
public long MaxRetainedBytes { get; init; } = 64 * 1024 * 1024;
|
||||
public int MaxTrackedSources { get; init; } = 100_000;
|
||||
public int MaxIngressItemsPerPartition { get; init; } = 1024;
|
||||
public int MaxDirtySourcesPerPartition { get; init; } = 1024;
|
||||
public int MaxControlItemsPerPartition { get; init; } = 256;
|
||||
public int MaxSnapshotItems { get; init; } = 10_000;
|
||||
public long MaxSnapshotBytes { get; init; } = 16 * 1024 * 1024;
|
||||
public int MaxSnapshotCatchUpItems { get; init; } = 1024;
|
||||
public TimeSpan MaxSnapshotLifetime { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
if (PartitionCount <= 0 || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 ||
|
||||
MaxIngressItemsPerPartition <= 0 || MaxDirtySourcesPerPartition <= 0 ||
|
||||
MaxControlItemsPerPartition <= 0 || MaxSnapshotItems <= 0 || MaxSnapshotBytes <= 0 ||
|
||||
MaxSnapshotCatchUpItems <= 0 || MaxSnapshotLifetime <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(DataResourceLimits));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Atomic accounting shared by partitions, reservations, snapshots and readers.</summary>
|
||||
public sealed class DataResourceBudget
|
||||
{
|
||||
private long _retainedBytes;
|
||||
internal DataResourceBudget(long maximum) => MaximumBytes = maximum;
|
||||
public long MaximumBytes { get; }
|
||||
public long RetainedBytes => Interlocked.Read(ref _retainedBytes);
|
||||
|
||||
internal bool TryReserve(long bytes)
|
||||
{
|
||||
if (bytes <= 0 || bytes > MaximumBytes) return false;
|
||||
while (true)
|
||||
{
|
||||
var current = Interlocked.Read(ref _retainedBytes);
|
||||
if (current > MaximumBytes - bytes) return false;
|
||||
if (Interlocked.CompareExchange(ref _retainedBytes, current + bytes, current) == current) return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Release(long bytes)
|
||||
{
|
||||
if (bytes > 0 && Interlocked.Add(ref _retainedBytes, -bytes) < 0)
|
||||
throw new InvalidOperationException("Resource charge released more than once.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Identifies one deployment attempt, including retries of the same artifact.</summary>
|
||||
public sealed record CatalogAttempt(long Epoch, string Revision)
|
||||
{
|
||||
private int _expected;
|
||||
internal bool Expected => Volatile.Read(ref _expected) != 0;
|
||||
internal void SetExpected(bool expected) => Volatile.Write(ref _expected, expected ? 1 : 0);
|
||||
}
|
||||
|
||||
/// <summary>Coordinates desired authority, private catalog staging and served topology activation.</summary>
|
||||
public sealed class LocalCatalogCoordinator
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly CatalogActivation _activation;
|
||||
private readonly DataPlaneAuthorityState _authority;
|
||||
private readonly Func<ServingIdentity> _serving;
|
||||
private CatalogAttempt? _attempt;
|
||||
private LocalExportCatalog? _staged;
|
||||
private LocalExportCatalog? _published;
|
||||
private bool _terminal;
|
||||
private bool _catalogValid;
|
||||
|
||||
// A test can hold the host's existing subscription boundary to observe ordering.
|
||||
internal Action? BeforeSubscriptionApplyForTests { get; set; }
|
||||
|
||||
public LocalCatalogCoordinator(CatalogActivation activation, DataPlaneAuthorityState authority, Func<ServingIdentity> serving)
|
||||
{
|
||||
_activation = activation ?? throw new ArgumentNullException(nameof(activation));
|
||||
_authority = authority ?? throw new ArgumentNullException(nameof(authority));
|
||||
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
|
||||
}
|
||||
|
||||
/// <summary>Only a matching, activated candidate may be observed by data facades.</summary>
|
||||
public LocalExportCatalog? Current
|
||||
{
|
||||
get
|
||||
{
|
||||
// A producer never waits for the control path or spins indefinitely under role churn.
|
||||
for (var retry = 0; retry < 3; retry++)
|
||||
{
|
||||
var catalog = Volatile.Read(ref _published);
|
||||
if (catalog is null || !catalog.IsActive) return null;
|
||||
var current = _serving();
|
||||
if (current.NodeId != catalog.Serving.NodeId || current.Incarnation != catalog.Serving.Incarnation) return null;
|
||||
if (current.Role == catalog.Serving.Role)
|
||||
{
|
||||
var verified = _serving();
|
||||
if (verified.NodeId != catalog.Serving.NodeId || verified.Incarnation != catalog.Serving.Incarnation) return null;
|
||||
if (verified.Role != catalog.Serving.Role || !ReferenceEquals(Volatile.Read(ref _published), catalog)) continue;
|
||||
return catalog.IsActive ? catalog : null;
|
||||
}
|
||||
var adjusted = catalog.WithServingRole(catalog.Serving with { Role = current.Role });
|
||||
if (ReferenceEquals(Interlocked.CompareExchange(ref _published, adjusted, catalog), catalog))
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Live process provenance for producers; epochs remain zero while no catalog is served.</summary>
|
||||
public ServingIdentity Serving
|
||||
{
|
||||
get
|
||||
{
|
||||
var current = Current;
|
||||
return current?.Serving ?? _serving() with { CatalogEpoch = 0, AuthorityEpoch = 0 };
|
||||
}
|
||||
}
|
||||
|
||||
public CatalogAttempt BeginAttempt(string revision)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var attempt = new CatalogAttempt(_activation.Begin(revision), revision);
|
||||
_attempt = attempt;
|
||||
_staged = null;
|
||||
_terminal = false;
|
||||
_catalogValid = false;
|
||||
Volatile.Write(ref _published, null);
|
||||
return attempt;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Install independently readable credentials even when catalog topology is invalid.</summary>
|
||||
public bool InstallAuthority(CatalogAttempt attempt, DataPlaneAuthorityProjection projection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attempt);
|
||||
ArgumentNullException.ThrowIfNull(projection);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_terminal || !ReferenceEquals(_attempt, attempt)) return false;
|
||||
var installed = _authority.Apply(projection.ClusterId, attempt.Revision, projection.Keys, projection.Grants,
|
||||
projection.ScopePaths, projection.EquipmentScopePaths, projection.ScriptedAlarmOwners,
|
||||
projection.UnsFolderScopes, projection.TagReferencingEquipment);
|
||||
_catalogValid = projection.CatalogValid && !string.IsNullOrWhiteSpace(installed.ClusterId);
|
||||
return _activation.AuthorityInstalled(attempt.Epoch, installed.GenerationId);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Stage(CatalogAttempt attempt, DraftSnapshot snapshot, string? expectedNodeId = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attempt);
|
||||
ArgumentNullException.ThrowIfNull(snapshot);
|
||||
lock (_gate)
|
||||
{
|
||||
var state = _activation.Current;
|
||||
if (_terminal || !ReferenceEquals(_attempt, attempt) || !_catalogValid || state.AuthorityEpoch <= 0
|
||||
|| _authority.Current.GenerationId != state.AuthorityEpoch) return false;
|
||||
var serving = _serving() with { CatalogEpoch = attempt.Epoch, AuthorityEpoch = state.AuthorityEpoch };
|
||||
if ((expectedNodeId is not null && serving.NodeId != expectedNodeId)
|
||||
|| !string.Equals(snapshot.ClusterId, _authority.Current.ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| !snapshot.ClusterNodes.Any(node => node.NodeId == serving.NodeId
|
||||
&& string.Equals(node.ClusterId, snapshot.ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
&& node.Enabled && !node.MaintenanceMode)) return false;
|
||||
var token = _activation.CaptureStagedAuthority(attempt.Epoch, state.AuthorityEpoch);
|
||||
_staged = LocalExportCatalog.Compile(snapshot, serving, token);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Complete(CatalogAttempt attempt, bool topologySucceeded)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attempt);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_terminal || !ReferenceEquals(_attempt, attempt)) return false;
|
||||
_terminal = true;
|
||||
var state = _activation.Current;
|
||||
var valid = topologySucceeded && _staged is not null && _catalogValid
|
||||
&& state.AuthorityEpoch == _authority.Current.GenerationId;
|
||||
if (valid) Volatile.Write(ref _published, _staged);
|
||||
if (!_activation.Complete(attempt.Epoch, valid))
|
||||
{
|
||||
Volatile.Write(ref _published, null);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Strictly caller-bound local data facade; it creates no namespace projection.</summary>
|
||||
public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate
|
||||
{
|
||||
private readonly LocalDataServices _services;
|
||||
private readonly DataAuthenticatedContext _context;
|
||||
private int _disposed;
|
||||
internal LocalDataConnection(LocalDataServices services, DataAuthenticatedContext context, DataTarget target)
|
||||
{ _services = services; _context = context; Target = target; }
|
||||
public DataTarget Target { get; }
|
||||
public TimeProvider Clock => _services.Clock;
|
||||
public bool CanPublish(ServingIdentity expectedServing) => Volatile.Read(ref _disposed) == 0 && _services.CanPublish(_context, expectedServing);
|
||||
private void Check() => ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken)
|
||||
{ Check(); return _services.GetCapabilitiesAsync(_context, budget, cancellationToken); }
|
||||
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken)
|
||||
{ Check(); return _services.BrowseAsync(_context, request, cancellationToken); }
|
||||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken)
|
||||
{ Check(); return _services.GetMetadataAsync(_context, request, cancellationToken); }
|
||||
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken)
|
||||
{ Check(); return _services.ReadAsync(_context, request, cancellationToken); }
|
||||
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
|
||||
{ Check(); return _services.WriteAsync(_context, request, cancellationToken); }
|
||||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
|
||||
{ Check(); return _services.SubscribeAsync(_context, cancellationToken); }
|
||||
public ValueTask DisposeAsync() { Interlocked.Exchange(ref _disposed, 1); return ValueTask.CompletedTask; }
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Runtime.CompilerServices;
|
||||
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;
|
||||
|
||||
/// <summary>Origin-local cached data ports; every facade retains its authenticated caller.</summary>
|
||||
public sealed class LocalDataServices : IDataConnectionFactory
|
||||
{
|
||||
private readonly Func<LocalExportCatalog?> _catalog;
|
||||
private readonly PartitionedSampleHub _hub;
|
||||
private readonly DataOperationPolicy _policy;
|
||||
private readonly DataCapabilitiesProvider _capabilities;
|
||||
private readonly Func<DataAuthenticatedContext, IDataWriteService>? _writes;
|
||||
private readonly Func<DataAuthenticatedContext, IDataSubscriptionService>? _subscriptions;
|
||||
private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32);
|
||||
private readonly ConditionalWeakTable<DataAuthenticatedContext, DataCallerIdentity> _callers = new();
|
||||
private sealed record Continuation(DataView Parent, string? Filter, int Offset, string Principal,
|
||||
string KeyId, string CredentialVersion, ServingIdentity Serving, long Started, long DurationTicks);
|
||||
|
||||
public LocalDataServices(Func<LocalExportCatalog?> catalog, PartitionedSampleHub hub,
|
||||
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock,
|
||||
Func<DataAuthenticatedContext, IDataWriteService>? writes = null,
|
||||
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null)
|
||||
{
|
||||
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
|
||||
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
|
||||
_policy = policy ?? throw new ArgumentNullException(nameof(policy));
|
||||
_capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities));
|
||||
Clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Hub and facade must use one clock.", nameof(clock));
|
||||
_writes = writes;
|
||||
_subscriptions = subscriptions;
|
||||
}
|
||||
|
||||
public TimeProvider Clock { get; }
|
||||
private DataOperations Implemented => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read
|
||||
| (_writes is null ? DataOperations.None : DataOperations.Write)
|
||||
| (_subscriptions is null ? DataOperations.None : DataOperations.Subscribe);
|
||||
private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value =>
|
||||
new(value.PrincipalId, value.ApiKeyId, value.CredentialVersion, value.CredentialExpiresUtc));
|
||||
|
||||
internal bool CanPublish(DataAuthenticatedContext context, ServingIdentity expectedServing)
|
||||
{
|
||||
var catalog = _catalog();
|
||||
return catalog is not null && Ready(catalog) && catalog.Serving == expectedServing
|
||||
&& _policy.IsCallerUsable(Caller(context));
|
||||
}
|
||||
|
||||
private sealed class PublicationReadLease(CachedSourceRead read, Func<bool> gate) : IDataPublicationLease
|
||||
{
|
||||
private int _disposed;
|
||||
public bool IsValid => Volatile.Read(ref _disposed) == 0 && read.IsValid && gate();
|
||||
public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) read.Dispose(); }
|
||||
}
|
||||
|
||||
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
context.Validate(); target.Validate();
|
||||
var serving = _capabilities.Serving;
|
||||
if (!string.Equals(target.ExpectedClusterId, _capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| (target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, serving.NodeId, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new ArgumentException("Target does not identify this data service.", nameof(target));
|
||||
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException("Authenticated caller is no longer usable.");
|
||||
return new LocalDataConnection(this, context, target);
|
||||
}
|
||||
|
||||
private bool Ready(LocalExportCatalog catalog) => catalog.IsActive && _capabilities.IsReady
|
||||
&& catalog.Serving == _capabilities.Serving && catalog.AuthorityEpoch == _policy.AuthorityEpoch;
|
||||
private bool Allowed(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node, DataOperations operation)
|
||||
{
|
||||
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context))
|
||||
|| (node.Metadata.AllowedOperations & operation) != operation
|
||||
|| !catalog.AllowsExport(context.PrincipalId, node, operation)) return false;
|
||||
var required = operation switch
|
||||
{
|
||||
DataOperations.Browse => OpcUaOperation.Browse,
|
||||
DataOperations.Read => OpcUaOperation.Read,
|
||||
DataOperations.Write => OpcUaOperation.WriteOperate,
|
||||
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
|
||||
DataOperations.Metadata => OpcUaOperation.Browse,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(operation))
|
||||
};
|
||||
var allowed = _policy.AuthorizeLocal(Caller(context), required, node.Scope);
|
||||
if (!allowed && operation == DataOperations.Metadata)
|
||||
allowed = _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Read, node.Scope);
|
||||
return allowed && Ready(catalog);
|
||||
}
|
||||
|
||||
private DataLimits Limits(LocalExportCatalog catalog, DataAuthenticatedContext context) =>
|
||||
catalog.LimitsFor(context.PrincipalId, _capabilities.Limits);
|
||||
private void CheckBudget(DataBudget budget, int count, int limit, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(budget);
|
||||
cancellationToken.ThrowIfCancellationRequested(); budget.Validate();
|
||||
if (count < 0 || count > Math.Min(budget.MaxItems, limit) || count > budget.MaxBytes / 256)
|
||||
throw new ArgumentOutOfRangeException(nameof(count), "Request exceeds the admitted item/byte budget.");
|
||||
}
|
||||
private bool Expired(long start, DataBudget budget) => Clock.GetElapsedTime(start) >= budget.Timeout;
|
||||
private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node)
|
||||
{
|
||||
var operations = DataOperations.None;
|
||||
foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, DataOperations.Subscribe })
|
||||
if ((node.Supported || operation == DataOperations.Browse)
|
||||
&& (node.SourceEnabled || operation is DataOperations.Browse or DataOperations.Metadata)
|
||||
&& (Implemented & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0
|
||||
&& (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) };
|
||||
}
|
||||
|
||||
internal Task<DataCapabilities> GetCapabilitiesAsync(DataAuthenticatedContext context, DataBudget budget, CancellationToken cancellationToken)
|
||||
{
|
||||
CheckBudget(budget, 0, 0, cancellationToken);
|
||||
var catalog = _catalog();
|
||||
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException();
|
||||
var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented,
|
||||
catalog is null ? _capabilities.Limits : Limits(catalog, context));
|
||||
if (catalog is null || !Ready(catalog)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None };
|
||||
return Task.FromResult(capabilities);
|
||||
}
|
||||
|
||||
internal Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(DataAuthenticatedContext context, MetadataRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Views);
|
||||
var catalog = _catalog();
|
||||
CheckBudget(request.Budget, request.Views.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken);
|
||||
if (catalog is null) return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(request.Views.Select((_, i) =>
|
||||
new DataItemResult<DataMetadata>(i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Unavailable, null, null)).ToArray());
|
||||
var start = Clock.GetTimestamp();
|
||||
var results = new List<DataItemResult<DataMetadata>>(request.Views.Count);
|
||||
long bytes = 0;
|
||||
for (var i = 0; i < request.Views.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var view = request.Views[i]; view.Validate();
|
||||
var status = !Ready(catalog) || Expired(start, request.Budget) ? DataItemStatus.Unavailable
|
||||
: !_policy.IsCallerUsable(Caller(context)) ? DataItemStatus.Denied
|
||||
: !catalog.TryResolveAddress(view, out _) ? catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound
|
||||
: DataItemStatus.Good;
|
||||
DataMetadata? metadata = null;
|
||||
if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node))
|
||||
{
|
||||
if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied;
|
||||
else if (!node.Supported) status = DataItemStatus.Unsupported;
|
||||
else
|
||||
{
|
||||
metadata = Metadata(catalog, context, node);
|
||||
bytes = checked(bytes + MetadataBytes(metadata));
|
||||
if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes))
|
||||
{ status = DataItemStatus.LimitExceeded; metadata = null; }
|
||||
}
|
||||
}
|
||||
results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null));
|
||||
}
|
||||
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
|
||||
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(results.Select(x => x with
|
||||
{ Status = !Ready(catalog) ? DataItemStatus.Unavailable : DataItemStatus.Denied, Value = null }).ToArray());
|
||||
return Task.FromResult<IReadOnlyList<DataItemResult<DataMetadata>>>(results);
|
||||
}
|
||||
|
||||
internal Task<IReadOnlyList<ReadResult>> ReadAsync(DataAuthenticatedContext context, ReadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items);
|
||||
var catalog = _catalog();
|
||||
CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken);
|
||||
if (catalog is null) return Task.FromResult<IReadOnlyList<ReadResult>>(request.Items.Select(item =>
|
||||
new ReadResult(item.CorrelationId, DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null)).ToArray());
|
||||
var start = Clock.GetTimestamp();
|
||||
var results = new List<ReadResult>(request.Items.Count);
|
||||
long bytes = 0;
|
||||
try
|
||||
{
|
||||
foreach (var item in request.Items)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested(); item.View.Validate();
|
||||
if (item.MaximumAge is { } maximumAge && maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(item.MaximumAge));
|
||||
ReadResult Empty(DataItemStatus status, DataReadiness readiness = DataReadiness.Unavailable) =>
|
||||
new(item.CorrelationId, status, readiness, null, null, null);
|
||||
if (!Ready(catalog) || Expired(start, request.Budget)) { results.Add(Empty(DataItemStatus.Unavailable)); continue; }
|
||||
if (!_policy.IsCallerUsable(Caller(context))) { results.Add(Empty(DataItemStatus.Denied)); continue; }
|
||||
if (!catalog.TryResolve(item.View, out var node))
|
||||
{ results.Add(Empty(catalog.ContainsAddress(item.View) ? DataItemStatus.Denied : DataItemStatus.NotFound)); continue; }
|
||||
if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(DataItemStatus.Denied)); continue; }
|
||||
if (!node.Supported) { results.Add(Empty(DataItemStatus.Unsupported)); continue; }
|
||||
if (!node.SourceEnabled) { results.Add(Empty(DataItemStatus.Unavailable)); continue; }
|
||||
if (node.Source is not { } key) { results.Add(Empty(DataItemStatus.Unsupported)); continue; }
|
||||
if (!_hub.TryGetCurrentTicket(key, out var ticket))
|
||||
{ results.Add(Empty(DataItemStatus.WaitingForInitialData, DataReadiness.WaitingForInitialData)); continue; }
|
||||
var read = _hub.Read(ticket);
|
||||
if (read.Sample is not { } sample || read.Readiness != DataReadiness.Ready)
|
||||
{ results.Add(new(item.CorrelationId, read.Status, read.Readiness, null, null, null)); read.Dispose(); continue; }
|
||||
if (sample.Serving.NodeId != key.ServingNodeId || sample.Serving.Incarnation != key.ServingIncarnation
|
||||
|| !_hub.TryGetCurrentTicket(key, out var current) || current != ticket)
|
||||
{ read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; }
|
||||
if (!ValueMatches(node.Metadata, sample.Value))
|
||||
{ read.Dispose(); results.Add(Empty(DataItemStatus.TypeMismatch)); continue; }
|
||||
bytes = checked(bytes + sample.Value.EstimatedRetainedBytes + 256);
|
||||
if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes))
|
||||
{ read.Dispose(); results.Add(Empty(DataItemStatus.LimitExceeded)); continue; }
|
||||
var age = Clock.GetElapsedTime(read.ReceivedTimestamp);
|
||||
if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; }
|
||||
// Catalog/authority headers describe current serving. Acquisition age, value version
|
||||
// and original timestamps remain unchanged, including provisional boot acquisitions.
|
||||
var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving };
|
||||
exposed.Validate();
|
||||
if (!Allowed(catalog, context, node, DataOperations.Read)
|
||||
|| !_hub.TryGetCurrentTicket(key, out current) || current != ticket)
|
||||
{ exposed.Dispose(); read.Dispose(); results.Add(Empty(DataItemStatus.Denied)); continue; }
|
||||
var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving)
|
||||
&& !Expired(start, request.Budget));
|
||||
results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good,
|
||||
DataReadiness.Ready, age, exposed, null, publication));
|
||||
}
|
||||
if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
|
||||
for (var i = 0; i < results.Count; i++)
|
||||
{ var result = results[i]; result.Dispose(); results[i] = new(result.CorrelationId,
|
||||
Ready(catalog) ? DataItemStatus.Denied : DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null); }
|
||||
return Task.FromResult<IReadOnlyList<ReadResult>>(results);
|
||||
}
|
||||
catch { foreach (var result in results) result.Dispose(); throw; }
|
||||
}
|
||||
|
||||
internal Task<DataBrowseBranch> BrowseAsync(DataAuthenticatedContext context, BrowseRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request); request.Parent.Validate();
|
||||
var catalog = _catalog();
|
||||
var limits = catalog is null ? _capabilities.Limits : Limits(catalog, context);
|
||||
CheckBudget(request.Budget, 0, limits.MaxPageItems, cancellationToken);
|
||||
DataBrowseBranch Empty(DataItemStatus status) => new(request.Parent, status, [], true, null, null);
|
||||
if (catalog is null || !Ready(catalog)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
|
||||
if (!catalog.TryResolve(request.Parent, out var parent) || !Allowed(catalog, context, parent, DataOperations.Browse))
|
||||
return Task.FromResult(Empty(DataItemStatus.Denied));
|
||||
var start = Clock.GetTimestamp();
|
||||
var offset = 0;
|
||||
if (request.Continuation is not null)
|
||||
{
|
||||
var continuation = DecodeContinuation(request.Continuation);
|
||||
if (continuation is null || continuation.Parent != request.Parent || continuation.Filter != request.Filter
|
||||
|| continuation.Principal != context.PrincipalId || continuation.KeyId != context.ApiKeyId
|
||||
|| continuation.CredentialVersion != context.CredentialVersion || continuation.Serving != catalog.Serving
|
||||
|| Clock.GetElapsedTime(continuation.Started).Ticks >= continuation.DurationTicks)
|
||||
return Task.FromResult(Empty(DataItemStatus.InvalidContinuation));
|
||||
offset = continuation.Offset;
|
||||
}
|
||||
var children = catalog.Children(parent);
|
||||
if (offset < 0 || offset > children.Count) return Task.FromResult(Empty(DataItemStatus.InvalidContinuation));
|
||||
var page = new List<DataMetadata>();
|
||||
long bytes = 256;
|
||||
var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems);
|
||||
var scanned = 0;
|
||||
while (offset < children.Count && page.Count < maximum && scanned++ < maximum)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable));
|
||||
var child = children[offset++];
|
||||
if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal))
|
||||
|| !Allowed(catalog, context, child, DataOperations.Browse)) continue;
|
||||
var metadata = Metadata(catalog, context, child);
|
||||
var size = MetadataBytes(metadata);
|
||||
if (bytes + size > Math.Min(request.Budget.MaxBytes, limits.MaxMessageBytes))
|
||||
{
|
||||
offset--;
|
||||
if (page.Count == 0) return Task.FromResult(Empty(DataItemStatus.LimitExceeded));
|
||||
break;
|
||||
}
|
||||
bytes += size; page.Add(metadata);
|
||||
}
|
||||
if (!Allowed(catalog, context, parent, DataOperations.Browse)) return Task.FromResult(Empty(DataItemStatus.Denied));
|
||||
var complete = offset == children.Count;
|
||||
var token = complete ? null : EncodeContinuation(new(request.Parent, request.Filter, offset, context.PrincipalId,
|
||||
context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, limits.MaxMetadataLease.Ticks));
|
||||
return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token,
|
||||
new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, limits.MaxMetadataLease)));
|
||||
}
|
||||
|
||||
internal async Task<IReadOnlyList<WriteItemResult>> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items);
|
||||
var catalog = _catalog(); CheckBudget(request.Budget, request.Items.Count,
|
||||
catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken);
|
||||
var results = new WriteItemResult[request.Items.Count];
|
||||
var allowed = new List<WriteItem>(); var indexes = new List<int>();
|
||||
for (var i = 0; i < request.Items.Count; i++)
|
||||
{
|
||||
var item = request.Items[i];
|
||||
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))
|
||||
{ allowed.Add(item); indexes.Add(i); }
|
||||
else results[i] = new(item.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable or denied before dispatch."));
|
||||
}
|
||||
if (allowed.Count > 0)
|
||||
{
|
||||
var outcomes = await _writes!(context).WriteAsync(new(allowed, request.Budget), cancellationToken).ConfigureAwait(false);
|
||||
if (outcomes.Count != allowed.Count) throw new InvalidOperationException("Write delegate returned an invalid result count.");
|
||||
for (var i = 0; i < outcomes.Count; i++) results[indexes[i]] = outcomes[i];
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
internal Task<IDataSubscription> SubscribeAsync(DataAuthenticatedContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var catalog = _catalog();
|
||||
if (_subscriptions is null || catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context)))
|
||||
throw new InvalidOperationException("Subscriptions are unavailable.");
|
||||
return _subscriptions(context).SubscribeAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private static bool ValueMatches(DataMetadata metadata, DataValue value) => value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind
|
||||
&& (value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind
|
||||
&& metadata.Dimensions.Count == value.Dimensions!.Count
|
||||
&& metadata.Dimensions.Zip(value.Dimensions).All(x => x.First == 0 || x.First == x.Second));
|
||||
private static long MetadataBytes(DataMetadata metadata) => checked(512L + 2L *
|
||||
(metadata.BrowseName.Length + metadata.NodeKind.Length + metadata.View.Address.Identifier.Length
|
||||
+ metadata.View.Address.NamespaceUri.Length + metadata.View.Subject.Length + (metadata.EngineeringUnits?.Length ?? 0))
|
||||
+ 8L * metadata.Dimensions.Count);
|
||||
private string EncodeContinuation(Continuation value)
|
||||
{
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(value);
|
||||
return Convert.ToBase64String(payload) + "." + Convert.ToBase64String(HMACSHA256.HashData(_continuationKey, payload));
|
||||
}
|
||||
private Continuation? DecodeContinuation(string token)
|
||||
{
|
||||
if (token.Length > 16_384) return null;
|
||||
var parts = token.Split('.'); if (parts.Length != 2) return null;
|
||||
try
|
||||
{
|
||||
var payload = Convert.FromBase64String(parts[0]); var signature = Convert.FromBase64String(parts[1]);
|
||||
if (!CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(_continuationKey, payload), signature)) return null;
|
||||
return JsonSerializer.Deserialize<Continuation>(payload);
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or JsonException) { return null; }
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
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;
|
||||
|
||||
public sealed partial class LocalExportCatalog
|
||||
{
|
||||
/// <summary>Stable data-service realm root; its identifier kind cannot collide with an SDK string NodeId.</summary>
|
||||
public static DataView RealmRoot(string clusterId, DataRealm realm)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId); DataContractValidation.Required(realm);
|
||||
return new(new(clusterId, realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
|
||||
"realm-root", clusterId), realm, null, 0, realm == DataRealm.Raw ? "raw" : "uns");
|
||||
}
|
||||
|
||||
/// <summary>Compile origin views from the deployed snapshot using the same identity and ACL producers as the SDK.</summary>
|
||||
public static LocalExportCatalog Compile(DraftSnapshot snapshot, ServingIdentity serving,
|
||||
IDataMappedCatalogAuthority activation, int maximumNodes = 100_000)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(snapshot);
|
||||
serving.Validate(requireEpochs: true);
|
||||
if (DataConnectionValidator.Validate(snapshot).Count != 0)
|
||||
throw new InvalidDataException("Origin catalog configuration is invalid.");
|
||||
var cluster = snapshot.ClusterId;
|
||||
var ids = StringComparer.OrdinalIgnoreCase;
|
||||
bool Same(string a, string b) => ids.Equals(a, b);
|
||||
var folders = snapshot.RawFolders.Where(x => Same(x.ClusterId, cluster)).ToArray();
|
||||
var drivers = snapshot.DriverInstances.Where(x => Same(x.ClusterId, cluster)).ToArray();
|
||||
var driverIds = drivers.Select(x => x.DriverInstanceId).ToHashSet(ids);
|
||||
var devices = snapshot.Devices.Where(x => driverIds.Contains(x.DriverInstanceId)).ToArray();
|
||||
var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(ids);
|
||||
var groups = snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId)).ToArray();
|
||||
var tags = snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId)).ToArray();
|
||||
var areas = snapshot.UnsAreas.Where(x => Same(x.ClusterId, cluster)).ToArray();
|
||||
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(ids);
|
||||
var lines = snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToArray();
|
||||
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(ids);
|
||||
var equipment = snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId)).ToArray();
|
||||
var equipmentIds = equipment.Select(x => x.EquipmentId).ToHashSet(ids);
|
||||
var tagIds = tags.Select(x => x.TagId).ToHashSet(ids);
|
||||
var references = snapshot.UnsTagReferences.Where(x => equipmentIds.Contains(x.EquipmentId) && tagIds.Contains(x.TagId)).ToArray();
|
||||
var virtuals = snapshot.VirtualTags.Where(x => equipmentIds.Contains(x.EquipmentId)).ToArray();
|
||||
var count = 2L + folders.Length + drivers.Length + devices.Length + groups.Length + tags.Length
|
||||
+ areas.Length + lines.Length + equipment.Length + references.Length + virtuals.Length;
|
||||
if (maximumNodes <= 0 || count > maximumNodes) throw new ArgumentOutOfRangeException(nameof(maximumNodes), "Origin catalog node budget exceeded.");
|
||||
var tagById = tags.ToDictionary(x => x.TagId, ids);
|
||||
var deviceById = devices.ToDictionary(x => x.DeviceId, ids);
|
||||
var driverById = drivers.ToDictionary(x => x.DriverInstanceId, ids);
|
||||
var referenceNames = references.Select(x => (x.EquipmentId, x.TagId, EffectiveName: x.DisplayNameOverride ?? tagById[x.TagId].Name)).ToArray();
|
||||
var scopeResolver = new AclScopePathResolver(
|
||||
folders.ToDictionary(x => x.RawFolderId, x => (x.ParentRawFolderId, x.Name), ids),
|
||||
drivers.ToDictionary(x => x.DriverInstanceId, x => (x.RawFolderId, x.Name), ids),
|
||||
devices.ToDictionary(x => x.DeviceId, x => (x.DriverInstanceId, x.Name), ids),
|
||||
groups.ToDictionary(x => x.TagGroupId, x => (x.ParentTagGroupId, x.DeviceId, x.Name), ids),
|
||||
tags.ToDictionary(x => x.TagId, x => (x.DeviceId, x.TagGroupId, x.Name), ids),
|
||||
areas.ToDictionary(x => x.UnsAreaId, x => x.Name, ids),
|
||||
lines.ToDictionary(x => x.UnsLineId, x => (x.UnsAreaId, x.Name), ids),
|
||||
equipment.ToDictionary(x => x.EquipmentId, x => (x.UnsLineId, x.Name), ids), referenceNames);
|
||||
var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, [], virtuals,
|
||||
snapshot.Scripts, references, tags, folders, devices, groups);
|
||||
var nodes = new List<LocalDataNode>((int)count);
|
||||
var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>();
|
||||
var rawViewsByPath = new Dictionary<string, DataView>(StringComparer.Ordinal);
|
||||
const DataOperations navigation = DataOperations.Browse | DataOperations.Metadata;
|
||||
const DataOperations data = navigation | DataOperations.Read | DataOperations.Subscribe;
|
||||
|
||||
NodeScope Scope(NodeAclScopeKind kind, string id, DataRealm realm)
|
||||
{
|
||||
var token = realm == DataRealm.Raw ? "raw" : "uns";
|
||||
var paths = scopeResolver.ResolveOne(kind, id).Where(x => x.Segments.Count > 0 && x.Segments[0] == token).ToArray();
|
||||
if (paths.Length != 1) throw new InvalidDataException("Origin entity has ambiguous or missing policy ancestry.");
|
||||
return new() { ClusterId = cluster, Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns,
|
||||
Segments = Array.AsReadOnly(paths[0].Segments.Skip(1).ToArray()) };
|
||||
}
|
||||
DataView View(DataRealm realm, string identifier, NodeScope scope) => new(
|
||||
new(cluster, realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri, "string", identifier),
|
||||
realm, null, 0, string.Join('/', scope.Segments));
|
||||
void Add(string kind, string id, string name, DataView view, NodeScope scope, DataView? parent,
|
||||
BackingSourceKey? source = null, DataValueKind valueKind = DataValueKind.Null, bool writable = false,
|
||||
bool array = false, uint? length = null, bool supported = true, bool enabled = true)
|
||||
{
|
||||
var operations = source is null ? navigation : data | (writable ? DataOperations.Write : DataOperations.None);
|
||||
var metadata = new DataMetadata(view, name, source is null ? "Folder" : supported ? "Variable" : "UnsupportedVariable",
|
||||
array && supported ? DataValueKind.Array : valueKind, array && supported ? 1 : -1,
|
||||
array && supported ? Array.AsReadOnly(new[] { length is { } n ? checked((int)n) : 0 }) : [],
|
||||
writable, operations, serving.CatalogEpoch, source?.StableSourceId, null, false,
|
||||
array && supported ? valueKind : null);
|
||||
nodes.Add(new(kind, id, metadata, scope, parent, source, supported, enabled));
|
||||
views.Add((view.Realm, kind, id.ToUpperInvariant()), view);
|
||||
if (view.Realm == DataRealm.Raw && view.Address.IdentifierKind == "string") rawViewsByPath.Add(view.Address.Identifier, view);
|
||||
}
|
||||
foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns })
|
||||
{
|
||||
var root = RealmRoot(cluster, realm);
|
||||
Add("Cluster", cluster, realm.ToString(), root,
|
||||
new() { ClusterId = cluster, Kind = realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = [] }, null);
|
||||
}
|
||||
DataView RawParent(NodeScope scope) => scope.Segments.Count <= 1 ? RealmRoot(cluster, DataRealm.Raw)
|
||||
: rawViewsByPath.GetValueOrDefault(string.Join('/', scope.Segments.Take(scope.Segments.Count - 1)))
|
||||
?? throw new InvalidDataException("Origin raw parent is not compiled.");
|
||||
|
||||
var rawEntities = new List<(string Kind, string Id, string Name, NodeScope Scope)>();
|
||||
rawEntities.AddRange(folders.Select(x => ("RawFolder", x.RawFolderId, x.Name, Scope(NodeAclScopeKind.RawFolder, x.RawFolderId, DataRealm.Raw))));
|
||||
rawEntities.AddRange(drivers.Select(x => ("RawDriver", x.DriverInstanceId, x.Name, Scope(NodeAclScopeKind.RawDriver, x.DriverInstanceId, DataRealm.Raw))));
|
||||
rawEntities.AddRange(devices.Select(x => ("RawDevice", x.DeviceId, x.Name, Scope(NodeAclScopeKind.RawDevice, x.DeviceId, DataRealm.Raw))));
|
||||
rawEntities.AddRange(groups.Select(x => ("RawTagGroup", x.TagGroupId, x.Name, Scope(NodeAclScopeKind.RawTagGroup, x.TagGroupId, DataRealm.Raw))));
|
||||
foreach (var entity in rawEntities.OrderBy(x => x.Scope.Segments.Count).ThenBy(x => x.Id, StringComparer.Ordinal))
|
||||
{
|
||||
var path = RawPaths.Build(entity.Scope.Segments);
|
||||
Add(entity.Kind, entity.Id, entity.Name, View(DataRealm.Raw, path, entity.Scope), entity.Scope, RawParent(entity.Scope));
|
||||
}
|
||||
var rawPlans = composition.RawTags.ToDictionary(x => x.NodeId, StringComparer.Ordinal);
|
||||
var rawSources = new Dictionary<string, (BackingSourceKey Key, bool Enabled)>(StringComparer.Ordinal);
|
||||
foreach (var plan in composition.RawTags)
|
||||
{
|
||||
var scope = Scope(NodeAclScopeKind.Tag, plan.TagId, DataRealm.Raw);
|
||||
var source = SourceKey.ForDriver(cluster, driverById[plan.DriverInstanceId].DriverInstanceId, plan.NodeId, serving.NodeId, serving.Incarnation);
|
||||
var enabled = deviceById[tagById[plan.TagId].DeviceId].Enabled && driverById[plan.DriverInstanceId].Enabled;
|
||||
rawSources.Add(plan.NodeId, (source, enabled));
|
||||
var kind = ValueKind(plan.DataType);
|
||||
var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||||
Add("RawTag", plan.TagId, plan.Name, View(DataRealm.Raw, plan.NodeId, scope), scope, RawParent(scope), source,
|
||||
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
|
||||
plan.IsArray, plan.ArrayLength, supported, enabled);
|
||||
}
|
||||
foreach (var area in areas)
|
||||
{
|
||||
var scope = Scope(NodeAclScopeKind.UnsArea, area.UnsAreaId, DataRealm.Uns);
|
||||
Add("UnsArea", area.UnsAreaId, area.Name, View(DataRealm.Uns, area.UnsAreaId, scope), scope, RealmRoot(cluster, DataRealm.Uns));
|
||||
}
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var scope = Scope(NodeAclScopeKind.UnsLine, line.UnsLineId, DataRealm.Uns);
|
||||
Add("UnsLine", line.UnsLineId, line.Name, View(DataRealm.Uns, line.UnsLineId, scope), scope, views[(DataRealm.Uns, "UnsArea", line.UnsAreaId.ToUpperInvariant())]);
|
||||
}
|
||||
foreach (var item in equipment)
|
||||
{
|
||||
var scope = Scope(NodeAclScopeKind.Equipment, item.EquipmentId, DataRealm.Uns);
|
||||
Add("Equipment", item.EquipmentId, item.Name, View(DataRealm.Uns, item.EquipmentId, scope), scope,
|
||||
views[(DataRealm.Uns, "UnsLine", item.UnsLineId.ToUpperInvariant())]);
|
||||
}
|
||||
foreach (var reference in composition.UnsReferenceVariables)
|
||||
{
|
||||
var scope = new NodeScope { ClusterId = cluster, Kind = NodeHierarchyKind.Uns,
|
||||
Segments = Array.AsReadOnly(reference.NodeId.Split(RawPaths.Separator)) };
|
||||
var source = rawSources[reference.BackingRawPath];
|
||||
var plan = rawPlans[reference.BackingRawPath];
|
||||
var kind = ValueKind(reference.DataType);
|
||||
var supported = kind != DataValueKind.Unspecified && (!reference.BackingIsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||||
Add("UnsTagReference", reference.UnsTagReferenceId, reference.EffectiveName, View(DataRealm.Uns, reference.NodeId, scope), scope,
|
||||
views[(DataRealm.Uns, "Equipment", reference.EquipmentId.ToUpperInvariant())], source.Key, supported ? kind : DataValueKind.Null,
|
||||
reference.Writable && (!reference.BackingIsArray || reference.BackingArrayWritable),
|
||||
reference.BackingIsArray, plan.ArrayLength, supported, source.Enabled);
|
||||
}
|
||||
foreach (var value in composition.EquipmentVirtualTags)
|
||||
{
|
||||
var owner = Scope(NodeAclScopeKind.Equipment, value.EquipmentId, DataRealm.Uns);
|
||||
var scope = DataScopeSubjects.Owned(owner);
|
||||
var identifier = string.IsNullOrWhiteSpace(value.FolderPath) ? V3NodeIds.Uns(value.EquipmentId, value.Name)
|
||||
: V3NodeIds.Uns(new[] { value.EquipmentId }.Concat(value.FolderPath.Split(RawPaths.Separator)).Append(value.Name));
|
||||
var view = View(DataRealm.Uns, identifier, owner) with { Subject = string.Join('/', owner.Segments.Append(value.Name)) };
|
||||
var kind = ValueKind(value.DataType);
|
||||
Add("VirtualTag", value.VirtualTagId, value.Name, view, scope, views[(DataRealm.Uns, "Equipment", value.EquipmentId.ToUpperInvariant())],
|
||||
SourceKey.ForVirtual(cluster, value.VirtualTagId, serving.NodeId, serving.Incarnation),
|
||||
kind == DataValueKind.Unspecified ? DataValueKind.Null : kind, supported: kind != DataValueKind.Unspecified, enabled: value.Enabled);
|
||||
}
|
||||
return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes);
|
||||
}
|
||||
|
||||
private static DataValueKind ValueKind(string type) => type switch
|
||||
{
|
||||
"Boolean" => DataValueKind.Boolean, "SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8,
|
||||
"Int16" => DataValueKind.Int16, "Int32" => DataValueKind.Int32, "Int64" => DataValueKind.Int64,
|
||||
"UInt16" => DataValueKind.UInt16, "UInt32" => DataValueKind.UInt32, "UInt64" => DataValueKind.UInt64,
|
||||
"Float" or "Single" => DataValueKind.Float, "Double" => DataValueKind.Double, "String" => DataValueKind.String,
|
||||
"ByteString" => DataValueKind.Bytes, "DateTime" => DataValueKind.Timestamp, "Guid" => DataValueKind.Guid,
|
||||
_ => DataValueKind.Unspecified
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
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;
|
||||
|
||||
/// <summary>An origin-owned view, with policy placement separate from its backing acquisition.</summary>
|
||||
public sealed record LocalDataNode(string EntityKind, string EntityId, DataMetadata Metadata,
|
||||
NodeScope Scope, DataView? Parent, BackingSourceKey? Source, bool Supported = true, bool SourceEnabled = true);
|
||||
|
||||
/// <summary>Immutable origin-only catalog. Projected peer nodes cannot become export authority.</summary>
|
||||
public sealed partial class LocalExportCatalog
|
||||
{
|
||||
private readonly Dictionary<(DataAddress Address, DataRealm Realm), LocalDataNode> _nodes = new();
|
||||
private readonly Dictionary<DataView, LocalDataNode[]> _children;
|
||||
private readonly ExportRule[] _exports;
|
||||
private readonly IDataMappedCatalogAuthority _activation;
|
||||
private sealed record ExportRule(string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
|
||||
DataOperations Operations, int Batch, int Page, int Items, int Streams);
|
||||
|
||||
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
|
||||
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
|
||||
ArgumentNullException.ThrowIfNull(serving);
|
||||
ArgumentNullException.ThrowIfNull(activation);
|
||||
ArgumentNullException.ThrowIfNull(nodes);
|
||||
ArgumentNullException.ThrowIfNull(exports);
|
||||
serving.Validate(requireEpochs: true);
|
||||
if (maximumNodes <= 0) throw new ArgumentOutOfRangeException(nameof(maximumNodes));
|
||||
ClusterId = clusterId;
|
||||
Serving = serving;
|
||||
_activation = activation;
|
||||
foreach (var input in nodes)
|
||||
{
|
||||
if (_nodes.Count >= maximumNodes) throw new ArgumentOutOfRangeException(nameof(nodes), "Catalog node budget exceeded.");
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
input.Metadata.Validate();
|
||||
var view = input.Metadata.View;
|
||||
if (view.MappingId is not null || !string.Equals(view.Address.OriginClusterId, clusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| !string.Equals(input.Scope.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| input.EntityKind == "RemoteNamespaceMapping" || input.Metadata.CatalogRevision != serving.CatalogEpoch
|
||||
|| input.Scope.Kind is not (NodeHierarchyKind.Raw or NodeHierarchyKind.Uns)
|
||||
|| view.Address.NamespaceUri != (view.Realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri)
|
||||
|| view.Realm != (input.Scope.Kind == NodeHierarchyKind.Raw ? DataRealm.Raw : DataRealm.Uns)
|
||||
|| (input.Source is { } source && (!string.Equals(source.OriginClusterId, clusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| source.ServingNodeId != serving.NodeId || source.ServingIncarnation != serving.Incarnation)))
|
||||
throw new ArgumentException("Catalog contains a nonlocal or projected node.", nameof(nodes));
|
||||
var node = input with
|
||||
{
|
||||
Metadata = input.Metadata with { View = view with { Address = view.Address with { OriginClusterId = clusterId } },
|
||||
Dimensions = Array.AsReadOnly(input.Metadata.Dimensions.ToArray()) },
|
||||
Scope = input.Scope with { Segments = Array.AsReadOnly(input.Scope.Segments.ToArray()) }
|
||||
};
|
||||
if (!_nodes.TryAdd((node.Metadata.View.Address, view.Realm), node))
|
||||
throw new ArgumentException("Catalog contains duplicate addresses.", nameof(nodes));
|
||||
}
|
||||
foreach (var pair in _nodes.ToArray())
|
||||
if (pair.Value.Parent is { } parent)
|
||||
{
|
||||
if (!TryResolve(parent, out var resolved)) throw new ArgumentException("Catalog parent is not origin-local.", nameof(nodes));
|
||||
_nodes[pair.Key] = pair.Value with { Parent = resolved.Metadata.View };
|
||||
}
|
||||
// A bounded parent walk makes a corrupt cycle a rejected generation, rather than an export escape.
|
||||
foreach (var node in _nodes.Values)
|
||||
{
|
||||
var seen = new HashSet<DataView>();
|
||||
var current = node;
|
||||
while (current.Parent is { } parent)
|
||||
{
|
||||
if (!seen.Add(parent)) throw new ArgumentException("Catalog contains a parent cycle.", nameof(nodes));
|
||||
current = _nodes[(parent.Address, parent.Realm)];
|
||||
}
|
||||
}
|
||||
_children = _nodes.Values.Where(x => x.Parent is not null).GroupBy(x => x.Parent!)
|
||||
.ToDictionary(x => x.Key, x => x.OrderBy(n => n.Metadata.BrowseName, StringComparer.Ordinal)
|
||||
.ThenBy(n => n.Metadata.View.Address.Identifier, StringComparer.Ordinal).ToArray());
|
||||
var rules = new List<ExportRule>();
|
||||
foreach (var export in exports.Where(x => x.Enabled && string.Equals(x.ClusterId, clusterId, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var wholeRealm = export.RootKind == "Cluster" && string.Equals(export.RootEntityId, clusterId, StringComparison.OrdinalIgnoreCase);
|
||||
var roots = _nodes.Values.Where(x => x.EntityKind == export.RootKind
|
||||
&& string.Equals(x.EntityId, export.RootEntityId, StringComparison.OrdinalIgnoreCase)
|
||||
&& x.Metadata.View.Realm == export.Realm).ToArray();
|
||||
if ((!wholeRealm && roots.Length != 1) || string.IsNullOrWhiteSpace(export.PrincipalId)
|
||||
|| export.AllowedOperations == DataOperations.None || export.MaxBatchItems <= 0 || export.MaxPageItems <= 0
|
||||
|| export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0)
|
||||
throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports));
|
||||
rules.Add(new(export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm,
|
||||
export.AllowedOperations, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams));
|
||||
}
|
||||
_exports = rules.ToArray();
|
||||
Nodes = new ReadOnlyCollection<LocalDataNode>(_nodes.Values.ToArray());
|
||||
}
|
||||
|
||||
public string ClusterId { get; }
|
||||
public ServingIdentity Serving { get; }
|
||||
public long AuthorityEpoch => _activation.AuthorityEpoch;
|
||||
public bool IsActive => _activation.IsActive && _activation.CatalogEpoch == Serving.CatalogEpoch
|
||||
&& _activation.AuthorityEpoch == Serving.AuthorityEpoch;
|
||||
public IReadOnlyList<LocalDataNode> Nodes { get; }
|
||||
|
||||
private LocalExportCatalog(LocalExportCatalog current, ServingIdentity serving)
|
||||
{
|
||||
serving.Validate(requireEpochs: true);
|
||||
if (serving.NodeId != current.Serving.NodeId || serving.Incarnation != current.Serving.Incarnation
|
||||
|| serving.CatalogEpoch != current.Serving.CatalogEpoch || serving.AuthorityEpoch != current.Serving.AuthorityEpoch)
|
||||
throw new ArgumentException("A new process or catalog generation requires a newly compiled catalog.", nameof(serving));
|
||||
ClusterId = current.ClusterId; Serving = serving; _activation = current._activation;
|
||||
_nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes;
|
||||
}
|
||||
|
||||
/// <summary>A role-only transition changes serving provenance without freshening source acquisitions.</summary>
|
||||
public LocalExportCatalog WithServingRole(ServingIdentity serving) => new(this, serving);
|
||||
public bool TryResolve(DataView view, out LocalDataNode node)
|
||||
{
|
||||
var address = LocalAddress(view.Address);
|
||||
if (_nodes.TryGetValue((address, view.Realm), out var found)
|
||||
&& found.Metadata.View == (view with { Address = address }))
|
||||
{ node = found; return true; }
|
||||
node = null!;
|
||||
return false;
|
||||
}
|
||||
private DataAddress LocalAddress(DataAddress address) => string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
? address with { OriginClusterId = ClusterId } : address;
|
||||
internal bool ContainsAddress(DataView view) => _nodes.ContainsKey((LocalAddress(view.Address), view.Realm));
|
||||
internal bool TryResolveAddress(DataView view, out LocalDataNode node)
|
||||
{
|
||||
if (view.MappingId is null && view.MappingRevision == 0 && _nodes.TryGetValue((LocalAddress(view.Address), view.Realm), out var found))
|
||||
{ node = found; return true; }
|
||||
node = null!; return false;
|
||||
}
|
||||
public IReadOnlyList<LocalDataNode> Children(LocalDataNode parent) =>
|
||||
_children.TryGetValue(parent.Metadata.View, out var children) ? Array.AsReadOnly(children) : [];
|
||||
|
||||
internal bool AllowsExport(string principal, LocalDataNode node, DataOperations operation)
|
||||
{
|
||||
foreach (var rule in _exports)
|
||||
{
|
||||
if (!string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase)
|
||||
|| rule.Realm != node.Metadata.View.Realm || (rule.Operations & operation) != operation) continue;
|
||||
if (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View)
|
||||
|| (operation == DataOperations.Browse && IsAncestor(node.Metadata.View, rule.Root!))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool IsAncestor(DataView ancestor, DataView candidate)
|
||||
{
|
||||
var current = candidate;
|
||||
for (var depth = 0; depth <= _nodes.Count; depth++)
|
||||
{
|
||||
if (current == ancestor) return true;
|
||||
if (!TryResolve(current, out var node) || node.Parent is null) return false;
|
||||
current = node.Parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
internal DataLimits LimitsFor(string principal, DataLimits limits)
|
||||
{
|
||||
var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
return rules.Length == 0 ? limits : limits with
|
||||
{
|
||||
MaxBatchItems = Math.Min(limits.MaxBatchItems, rules.Min(x => x.Batch)),
|
||||
MaxPageItems = Math.Min(limits.MaxPageItems, rules.Min(x => x.Page)),
|
||||
MaxMonitoredItems = Math.Min(limits.MaxMonitoredItems, rules.Min(x => x.Items)),
|
||||
MaxStreams = Math.Min(limits.MaxStreams, rules.Min(x => x.Streams))
|
||||
};
|
||||
}
|
||||
|
||||
internal DataOperations ExportOperations(string principal) => _exports
|
||||
.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase))
|
||||
.Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Validates borrowed driver values before creating the immutable data-plane value.</summary>
|
||||
internal static class OwnedDataSample
|
||||
{
|
||||
private const int MaxElements = 65_536;
|
||||
private const long MaxBytes = 4 * 1024 * 1024;
|
||||
private const int MaxRank = 4;
|
||||
|
||||
public static long Estimate(object? value, SourceValueShape? shape = null)
|
||||
{
|
||||
checked
|
||||
{
|
||||
const long baseline = 256;
|
||||
long size;
|
||||
if (value is byte[] bytes && shape is { Kind: DataValueKind.Array, ElementKind: DataValueKind.UInt8, Rank: 1 })
|
||||
{
|
||||
if (bytes.LongLength > MaxElements) throw new ArgumentException("Array exceeds ingestion limit.");
|
||||
size = baseline + 128L + 8L + 48L * bytes.LongLength;
|
||||
}
|
||||
else if (value is byte[] bytesValue) size = baseline + 32L + bytesValue.LongLength;
|
||||
else if (value is string text) size = baseline + 32L + 2L * text.Length;
|
||||
else if (value is Array array)
|
||||
{
|
||||
if (array.Rank > MaxRank || array.LongLength > MaxElements || array.GetType().GetElementType() is not { } elementType || Kind(elementType) == DataValueKind.Unspecified)
|
||||
throw new ArgumentException("Unsupported array shape or type.");
|
||||
for (var dimension = 0; dimension < array.Rank; dimension++)
|
||||
if (array.GetLowerBound(dimension) != 0) throw new ArgumentException("Non-zero array lower bounds are unsupported.");
|
||||
size = baseline + 128L + 8L * array.Rank + 48L * array.LongLength;
|
||||
if (elementType == typeof(string))
|
||||
foreach (var element in array)
|
||||
size += 2L * ((string?)element ?? throw new ArgumentException("Null array element.")).Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (value is not null && Kind(value.GetType()) == DataValueKind.Unspecified)
|
||||
throw new ArgumentException("Unsupported mutable value.");
|
||||
size = baseline + 32L;
|
||||
}
|
||||
if (size > MaxBytes) throw new ArgumentException("Value exceeds ingestion limit.");
|
||||
if (value is not null && shape is { } declared)
|
||||
{
|
||||
var isByteArray = value is byte[] && declared.Kind == DataValueKind.Array && declared.ElementKind == DataValueKind.UInt8;
|
||||
if (declared.Kind == DataValueKind.Array)
|
||||
{
|
||||
if (value is not Array declaredArray || declaredArray.Rank != declared.Rank ||
|
||||
(!isByteArray && Kind(declaredArray.GetType().GetElementType()!) != declared.ElementKind))
|
||||
throw new ArgumentException("Value does not match its declared array shape.");
|
||||
}
|
||||
else if (declared.Kind == DataValueKind.Bytes ? value is not byte[] : Kind(value.GetType()) != declared.Kind)
|
||||
throw new ArgumentException("Value does not match its declared type.");
|
||||
}
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
||||
public static DataValue Copy(object? value, SourceValueShape? shape = null)
|
||||
{
|
||||
if (value is null) return DataValue.Null();
|
||||
if (value is byte[] bytes && shape is not { Kind: DataValueKind.Array }) return DataValue.FromBytes(bytes);
|
||||
if (value is Array array)
|
||||
{
|
||||
var elementKind = Kind(array.GetType().GetElementType()!);
|
||||
var elements = new object[array.Length];
|
||||
var index = 0;
|
||||
foreach (var item in array) elements[index++] = Normalize(item!);
|
||||
var dimensions = new int[array.Rank];
|
||||
for (var i = 0; i < dimensions.Length; i++) dimensions[i] = array.GetLength(i);
|
||||
return DataValue.FromArray(elementKind, elements, dimensions);
|
||||
}
|
||||
return DataValue.FromScalar(Kind(value.GetType()), Normalize(value));
|
||||
}
|
||||
|
||||
// The legacy SDK path has its own managed defensive copy. It is deliberately outside the hub's
|
||||
// budget and must be measured separately; never expose the hub's immutable backing to it.
|
||||
public static object? CopyLegacy(object? value) => value is Array array
|
||||
? CopyLegacyArray(array, new Dictionary<Array, Array>(ReferenceEqualityComparer.Instance)) : value;
|
||||
|
||||
private static Array CopyLegacyArray(Array original, Dictionary<Array, Array> seen)
|
||||
{
|
||||
if (seen.TryGetValue(original, out var existing)) return existing;
|
||||
var copy = (Array)original.Clone();
|
||||
seen.Add(original, copy);
|
||||
if (original.GetType().GetElementType()?.IsValueType != false || original.Length == 0) return copy;
|
||||
var indices = new int[original.Rank];
|
||||
void Walk(int dimension)
|
||||
{
|
||||
var end = original.GetUpperBound(dimension);
|
||||
for (var i = original.GetLowerBound(dimension); i <= end; i++)
|
||||
{
|
||||
indices[dimension] = i;
|
||||
if (dimension + 1 < original.Rank) Walk(dimension + 1);
|
||||
else if (original.GetValue(indices) is Array nested) copy.SetValue(CopyLegacyArray(nested, seen), indices);
|
||||
}
|
||||
}
|
||||
Walk(0);
|
||||
return copy;
|
||||
}
|
||||
|
||||
public static DateTimeOffset? Timestamp(DateTime? value) => value is null ? null :
|
||||
new DateTimeOffset(value.Value.Kind == DateTimeKind.Unspecified
|
||||
? DateTime.SpecifyKind(value.Value, DateTimeKind.Utc)
|
||||
: value.Value.ToUniversalTime());
|
||||
|
||||
private static object Normalize(object value) => value switch
|
||||
{
|
||||
DateTime time => Timestamp(time)!.Value,
|
||||
DateTimeOffset offset => offset.ToUniversalTime(),
|
||||
_ => value
|
||||
};
|
||||
|
||||
private static DataValueKind Kind(Type type) => type == typeof(bool) ? DataValueKind.Boolean :
|
||||
type == typeof(sbyte) ? DataValueKind.Int8 : type == typeof(short) ? DataValueKind.Int16 :
|
||||
type == typeof(int) ? DataValueKind.Int32 : type == typeof(long) ? DataValueKind.Int64 :
|
||||
type == typeof(byte) ? DataValueKind.UInt8 : type == typeof(ushort) ? DataValueKind.UInt16 :
|
||||
type == typeof(uint) ? DataValueKind.UInt32 : type == typeof(ulong) ? DataValueKind.UInt64 :
|
||||
type == typeof(float) ? DataValueKind.Float : type == typeof(double) ? DataValueKind.Double :
|
||||
type == typeof(string) ? DataValueKind.String : type == typeof(Guid) ? DataValueKind.Guid :
|
||||
type == typeof(DateTime) || type == typeof(DateTimeOffset) ? DataValueKind.Timestamp : DataValueKind.Unspecified;
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System.Collections.Concurrent;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Canonical acquisition identity, independent of any authorized view or principal.</summary>
|
||||
public sealed record BackingSourceKey(string OriginClusterId, string SourceKind, string StableSourceId,
|
||||
string ServingNodeId, string ServingIncarnation);
|
||||
public readonly record struct SourceGeneration(long Incarnation, long Lifecycle);
|
||||
internal sealed class SourceBindingFence
|
||||
{
|
||||
private int _retired;
|
||||
internal bool IsRetired => Volatile.Read(ref _retired) != 0;
|
||||
internal void Retire() => Interlocked.Exchange(ref _retired, 1);
|
||||
}
|
||||
/// <summary>An individual binding; two bindings of the same key and generation remain distinct.</summary>
|
||||
public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneration Generation)
|
||||
{
|
||||
internal SourceBindingFence? Binding { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>Shared producer lifetime; retirement immediately fences every source bound to this token.</summary>
|
||||
public sealed class ProducerFence
|
||||
{
|
||||
private int _retired;
|
||||
public ProducerFence(long incarnation)
|
||||
{
|
||||
if (incarnation <= 0) throw new ArgumentOutOfRangeException(nameof(incarnation));
|
||||
Incarnation = incarnation;
|
||||
}
|
||||
public long Incarnation { get; }
|
||||
public bool IsRetired => Volatile.Read(ref _retired) != 0;
|
||||
public void Retire() => Interlocked.Exchange(ref _retired, 1);
|
||||
}
|
||||
|
||||
public interface IIngressReservation : IDisposable
|
||||
{
|
||||
/// <summary>On success transfers the sample; on failure it remains owned by the caller.</summary>
|
||||
bool TryCommit(DataSample owned, long sequence);
|
||||
}
|
||||
|
||||
public interface ISourceSampleHub
|
||||
{
|
||||
bool TryBind(SourceTicket ticket);
|
||||
bool TryBind(SourceTicket ticket, ProducerFence? fence);
|
||||
bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket);
|
||||
bool IsTicketCurrentNonBlocking(SourceTicket ticket);
|
||||
void InvalidatePartitionFor(BackingSourceKey key, string reason);
|
||||
bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation);
|
||||
void Invalidate(SourceTicket ticket, string reason);
|
||||
bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc);
|
||||
bool TryRemove(SourceTicket ticket, long sequence);
|
||||
}
|
||||
|
||||
/// <summary>A recipient-owned cache read. Dispose releases its independent sample lease and admission charge.</summary>
|
||||
public sealed class CachedSourceRead : IDisposable
|
||||
{
|
||||
private readonly DataResourceBudget _budget;
|
||||
private readonly SamplePartition? _guard;
|
||||
private readonly object? _source;
|
||||
private readonly object? _sourceGate;
|
||||
private readonly long _sourceVersion, _routingEpoch;
|
||||
private readonly long _sourceSignal;
|
||||
private long _charge;
|
||||
internal CachedSourceRead(DataResourceBudget budget, DataItemStatus status, DataReadiness readiness,
|
||||
DataSample? sample, long version, long partitionEpoch, long receivedTimestamp, long charge,
|
||||
SamplePartition? guard = null, object? source = null, object? sourceGate = null,
|
||||
long sourceVersion = 0, long sourceSignal = 0, long routingEpoch = 0)
|
||||
{ _budget = budget; Status = status; Readiness = readiness; Sample = sample; SourceVersion = version;
|
||||
PartitionEpoch = partitionEpoch; ReceivedTimestamp = receivedTimestamp; _charge = charge;
|
||||
_guard = guard; _source = source; _sourceGate = sourceGate; _sourceVersion = sourceVersion;
|
||||
_sourceSignal = sourceSignal; _routingEpoch = routingEpoch; }
|
||||
public DataItemStatus Status { get; }
|
||||
public DataReadiness Readiness { get; }
|
||||
public DataSample? Sample { get; }
|
||||
public long SourceVersion { get; }
|
||||
public long PartitionEpoch { get; }
|
||||
public long ReceivedTimestamp { get; }
|
||||
/// <summary>True only while the captured source, producer and partition fences remain current.</summary>
|
||||
public bool IsValid => Volatile.Read(ref _charge) != 0 && _guard is not null && _source is not null && _sourceGate is not null &&
|
||||
_guard.IsReadValid(_source, _sourceGate, _sourceVersion, _sourceSignal, PartitionEpoch, _routingEpoch);
|
||||
public void Dispose()
|
||||
{
|
||||
var charge = Interlocked.Exchange(ref _charge, 0);
|
||||
if (charge == 0) return;
|
||||
Sample?.Dispose(); _budget.Release(charge);
|
||||
if (_guard is not null && _source is not null) _guard.ReleaseRead(_source);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Partitioned source owner. Producer admission never waits on a worker or socket.
|
||||
/// Reads and snapshots are raw runtime acquisition state, not authorized external results.
|
||||
/// A facade must prove current catalog and authority and attach current trusted serving
|
||||
/// provenance before returning a sample; acquisitions may have zero preactivation epochs.
|
||||
/// </summary>
|
||||
public sealed class PartitionedSampleHub : ISourceSampleHub, IDisposable
|
||||
{
|
||||
internal const long SampleOverhead = 256;
|
||||
internal const long ReferenceOverhead = 256;
|
||||
private readonly DataResourceLimits _limits;
|
||||
private readonly bool _autoDrain;
|
||||
private readonly object _routingLock = new();
|
||||
private readonly ConcurrentDictionary<SnapshotLease, byte> _snapshots = new();
|
||||
private SamplePartition[] _partitions;
|
||||
private int _trackedSources;
|
||||
private int _snapshotItems;
|
||||
private long _routingEpoch = 1;
|
||||
private int _disposed;
|
||||
|
||||
public PartitionedSampleHub(DataResourceLimits limits, TimeProvider clock) : this(limits, clock, true) { }
|
||||
internal PartitionedSampleHub(DataResourceLimits limits, TimeProvider clock, bool autoDrain)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(limits); ArgumentNullException.ThrowIfNull(clock); limits.Validate();
|
||||
_limits = limits; Clock = clock; _autoDrain = autoDrain; Resources = new(limits.MaxRetainedBytes);
|
||||
_partitions = CreatePartitions(limits.PartitionCount);
|
||||
}
|
||||
public TimeProvider Clock { get; }
|
||||
public DataResourceBudget Resources { get; }
|
||||
internal DataResourceLimits Limits => _limits;
|
||||
internal long RoutingEpoch => Interlocked.Read(ref _routingEpoch);
|
||||
internal bool IsDisposed => Volatile.Read(ref _disposed) != 0;
|
||||
private SamplePartition[] CreatePartitions(int count) => Enumerable.Range(0, count).Select(i => new SamplePartition(this, i)).ToArray();
|
||||
|
||||
// Routing stays stable for this process; repartitioning resets affected epochs.
|
||||
public int GetPartition(BackingSourceKey key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
return GetPartitionFor(key, Volatile.Read(ref _partitions).Length);
|
||||
}
|
||||
private SamplePartition Partition(BackingSourceKey key) { var partitions = Volatile.Read(ref _partitions); return partitions[GetPartitionFor(key, partitions.Length)]; }
|
||||
internal static int GetPartitionFor(BackingSourceKey key, int count) => (int)(unchecked((uint)key.GetHashCode()) % (uint)count);
|
||||
internal bool TryTrackSource() { while (true) { var current = Volatile.Read(ref _trackedSources); if (current >= _limits.MaxTrackedSources) return false; if (Interlocked.CompareExchange(ref _trackedSources, current + 1, current) == current) return true; } }
|
||||
internal void UntrackSource() => Interlocked.Decrement(ref _trackedSources);
|
||||
internal bool TryTrackSnapshotItems(int count) { while (true) { var current = Volatile.Read(ref _snapshotItems); if (count > _limits.MaxSnapshotItems - current) return false; if (Interlocked.CompareExchange(ref _snapshotItems, current + count, current) == current) return true; } }
|
||||
internal void UntrackSnapshotItems(int count) => Interlocked.Add(ref _snapshotItems, -count);
|
||||
internal void ForgetSnapshot(SnapshotLease snapshot) => _snapshots.TryRemove(snapshot, out _);
|
||||
internal void Schedule(SamplePartition partition) { if (_autoDrain) partition.Schedule(); }
|
||||
|
||||
private static bool ValidKey(BackingSourceKey? key) => key is not null &&
|
||||
!string.IsNullOrWhiteSpace(key.OriginClusterId) && !string.IsNullOrWhiteSpace(key.SourceKind) &&
|
||||
!string.IsNullOrWhiteSpace(key.StableSourceId) && !string.IsNullOrWhiteSpace(key.ServingNodeId) &&
|
||||
!string.IsNullOrWhiteSpace(key.ServingIncarnation) &&
|
||||
(long)key.OriginClusterId.Length + key.SourceKind.Length + key.StableSourceId.Length + key.ServingNodeId.Length + key.ServingIncarnation.Length <= 4096;
|
||||
public bool TryBind(SourceTicket ticket) => TryBind(ticket, null);
|
||||
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryBind(ticket, fence);
|
||||
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket)
|
||||
{ if (!IsDisposed && ValidKey(key)) return Partition(key).TryGetCurrentTicket(key, out ticket); ticket = default; return false; }
|
||||
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).IsTicketCurrentNonBlocking(ticket);
|
||||
public void InvalidatePartitionFor(BackingSourceKey key, string reason)
|
||||
{ ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(key)) Partition(key).InvalidatePartition(); }
|
||||
public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation)
|
||||
{ if (!IsDisposed && ValidKey(ticket.Key)) return Partition(ticket.Key).TryReserve(ticket, estimatedRetainedBytes, out reservation); reservation = null; return false; }
|
||||
public void Invalidate(SourceTicket ticket, string reason) { ArgumentException.ThrowIfNullOrWhiteSpace(reason); if (!IsDisposed && ValidKey(ticket.Key)) Partition(ticket.Key).Invalidate(ticket); }
|
||||
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc) =>
|
||||
!IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryStatus(ticket, sequence, statusCode, sourceTimestampUtc, serverTimestampUtc);
|
||||
public bool TryRemove(SourceTicket ticket, long sequence) => !IsDisposed && ValidKey(ticket.Key) && Partition(ticket.Key).TryRemove(ticket, sequence);
|
||||
public CachedSourceRead Read(SourceTicket ticket) => IsDisposed || !ValidKey(ticket.Key) ? EmptyRead(DataItemStatus.Unavailable, DataReadiness.Unavailable, 0) : Partition(ticket.Key).Read(ticket);
|
||||
internal CachedSourceRead EmptyRead(DataItemStatus status, DataReadiness readiness, long epoch) => new(Resources, status, readiness, null, 0, epoch, 0, 0);
|
||||
internal void ProcessPending() { foreach (var partition in Volatile.Read(ref _partitions)) partition.Drain(); }
|
||||
internal void WithPartitionLockForTest(BackingSourceKey key, Action action) => Partition(key).WithLockForTest(action);
|
||||
|
||||
public bool TryCaptureSnapshot(IReadOnlyList<SourceTicket> tickets, DataBudget budget, CancellationToken cancellationToken, out SnapshotLease? snapshot)
|
||||
{
|
||||
snapshot = null; ArgumentNullException.ThrowIfNull(tickets); ArgumentNullException.ThrowIfNull(budget); budget.Validate();
|
||||
if (IsDisposed || cancellationToken.IsCancellationRequested || tickets.Count == 0 || tickets.Count > budget.MaxItems ||
|
||||
tickets.Count > _limits.MaxSnapshotItems || tickets.Any(t => !ValidKey(t.Key)) || tickets.Distinct().Count() != tickets.Count || !TryTrackSnapshotItems(tickets.Count)) return false;
|
||||
var routing = RoutingEpoch; var items = new Dictionary<SourceTicket, SnapshotItem>(); var watermarks = new Dictionary<int, long>(); var epochs = new Dictionary<int, long>();
|
||||
long charge = 0;
|
||||
try
|
||||
{
|
||||
var partitions = Volatile.Read(ref _partitions);
|
||||
foreach (var group in tickets.GroupBy(t => GetPartitionFor(t.Key, partitions.Length)))
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch ||
|
||||
!partitions[group.Key].Capture(group, items, out var watermark, out var epoch, ref charge, Math.Min(budget.MaxBytes, _limits.MaxSnapshotBytes))) return false;
|
||||
watermarks.Add(group.Key, watermark);
|
||||
epochs.Add(group.Key, epoch);
|
||||
}
|
||||
if (cancellationToken.IsCancellationRequested || routing != RoutingEpoch) return false;
|
||||
snapshot = new SnapshotLease(this, items, watermarks, epochs, partitions, routing, charge, tickets.Count,
|
||||
budget.Timeout < _limits.MaxSnapshotLifetime ? budget.Timeout : _limits.MaxSnapshotLifetime, cancellationToken);
|
||||
charge = 0; items = null!;
|
||||
_snapshots.TryAdd(snapshot, 0);
|
||||
if (!snapshot.IsReset) return true;
|
||||
snapshot.Dispose(); ForgetSnapshot(snapshot); snapshot = null; return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (items is not null) { foreach (var item in items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); } Resources.Release(charge); UntrackSnapshotItems(tickets.Count); }
|
||||
}
|
||||
}
|
||||
|
||||
public void Repartition(int count)
|
||||
{
|
||||
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));
|
||||
lock (_routingLock)
|
||||
{
|
||||
if (IsDisposed) throw new ObjectDisposedException(nameof(PartitionedSampleHub));
|
||||
Interlocked.Increment(ref _routingEpoch);
|
||||
var old = Volatile.Read(ref _partitions);
|
||||
foreach (var snapshot in _snapshots.Keys) snapshot.Dispose();
|
||||
foreach (var partition in old) partition.Dispose();
|
||||
// Retire all old binding tokens before exposing new owners; otherwise an old
|
||||
// ticket can race the swap and bind in a new partition before its fence closes.
|
||||
Volatile.Write(ref _partitions, CreatePartitions(count));
|
||||
}
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_routingLock)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
Interlocked.Increment(ref _routingEpoch);
|
||||
foreach (var snapshot in _snapshots.Keys) snapshot.Dispose();
|
||||
foreach (var partition in _partitions) partition.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>One bounded source owner; no network or caller callbacks run under its lock.</summary>
|
||||
internal sealed class SamplePartition : IDisposable
|
||||
{
|
||||
private const long SourceOverhead = 768;
|
||||
private const long ControlOverhead = 256;
|
||||
private const long ChangeOverhead = 192;
|
||||
private readonly PartitionedSampleHub _hub;
|
||||
private readonly object _gate = new();
|
||||
private readonly ConcurrentDictionary<BackingSourceKey, SourceState> _sources = new();
|
||||
private readonly Queue<Pending> _queue = new();
|
||||
private readonly Dictionary<BackingSourceKey, Pending> _dirty = new();
|
||||
private readonly Queue<(long Version, BackingSourceKey Key)> _changes = new();
|
||||
private long _epoch = 1;
|
||||
private long _cleanedEpoch = 1;
|
||||
private long _watermark;
|
||||
private long _ordinal;
|
||||
private int _queuedValues;
|
||||
private int _queuedControls;
|
||||
private int _reservations;
|
||||
private int _scheduled;
|
||||
private int _retiredSweepRequested;
|
||||
private int _reclaimRequested;
|
||||
private bool _disposed;
|
||||
|
||||
private readonly long _routingEpoch;
|
||||
internal SamplePartition(PartitionedSampleHub hub, int id) { _hub = hub; Id = id; _routingEpoch = hub.RoutingEpoch; }
|
||||
internal int Id { get; }
|
||||
internal long Epoch { get { lock (_gate) return _epoch; } }
|
||||
|
||||
private static bool Valid(SourceTicket ticket)
|
||||
{
|
||||
var k = ticket.Key;
|
||||
return k is not null && !string.IsNullOrWhiteSpace(k.OriginClusterId) && !string.IsNullOrWhiteSpace(k.SourceKind) &&
|
||||
!string.IsNullOrWhiteSpace(k.StableSourceId) && !string.IsNullOrWhiteSpace(k.ServingNodeId) &&
|
||||
!string.IsNullOrWhiteSpace(k.ServingIncarnation) && ticket.Generation.Incarnation > 0 && ticket.Generation.Lifecycle > 0 &&
|
||||
(long)k.OriginClusterId.Length + k.SourceKind.Length + k.StableSourceId.Length + k.ServingNodeId.Length + k.ServingIncarnation.Length <= 4096;
|
||||
}
|
||||
private static int Compare(SourceGeneration a, SourceGeneration b) => a.Incarnation != b.Incarnation ? a.Incarnation.CompareTo(b.Incarnation) : a.Lifecycle.CompareTo(b.Lifecycle);
|
||||
private static long SourceCharge(BackingSourceKey key) => checked(SourceOverhead + 2L * (key.OriginClusterId.Length + key.SourceKind.Length + key.StableSourceId.Length + key.ServingNodeId.Length + key.ServingIncarnation.Length));
|
||||
|
||||
internal bool TryBind(SourceTicket ticket, ProducerFence? fence)
|
||||
{
|
||||
if (!Valid(ticket) || ticket.Binding is null || ticket.Binding.IsRetired || (fence is not null && (fence.IsRetired || fence.Incarnation != ticket.Generation.Incarnation))) return false;
|
||||
if (!Monitor.TryEnter(_gate))
|
||||
{
|
||||
if (_sources.TryGetValue(ticket.Key, out var existing))
|
||||
{
|
||||
var gate = Volatile.Read(ref existing.Gate);
|
||||
if (Compare(ticket.Generation, gate.Generation) > 0) { gate.Binding.Retire(); Interlocked.Exchange(ref gate.Retired, 1); Interlocked.Increment(ref gate.Invalidated); }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (_disposed || ticket.Binding.IsRetired) return false;
|
||||
if (_sources.TryGetValue(ticket.Key, out var state))
|
||||
{
|
||||
var order = Compare(ticket.Generation, state.Generation);
|
||||
ApplyGate(state);
|
||||
ApplyPartitionEpoch(state);
|
||||
if (order == 0)
|
||||
{
|
||||
if (state.Ticket != ticket || state.Removed || Volatile.Read(ref state.Gate.Retired) != 0 || state.Fence?.IsRetired == true ||
|
||||
(state.Fence is not null && !ReferenceEquals(state.Fence, fence))) return false;
|
||||
if (state.Fence is null && fence is not null) Volatile.Write(ref state.Fence, fence);
|
||||
return state.Fence?.IsRetired != true;
|
||||
}
|
||||
if (order < 0) return false;
|
||||
state.Ticket.Binding!.Retire();
|
||||
Interlocked.Exchange(ref state.Gate.Retired, 1);
|
||||
state.Generation = ticket.Generation; state.Removed = false; state.Readiness = DataReadiness.WaitingForInitialData; Interlocked.Increment(ref state.InvalidationVersion);
|
||||
state.Ticket = ticket;
|
||||
state.Fence = fence; state.PartitionEpoch = _epoch;
|
||||
Volatile.Write(ref state.Gate, new SourceGate(ticket.Generation, ticket.Binding));
|
||||
state.AppliedInvalidations = 0;
|
||||
state.LastSubmitted = 0; state.LastApplied = 0; state.Barrier = 0; ReleaseCache(state);
|
||||
RecordChange(ticket.Key); return true;
|
||||
}
|
||||
var charge = SourceCharge(ticket.Key);
|
||||
if (!_hub.TryTrackSource()) { InvalidatePartition(); return false; }
|
||||
if (!_hub.Resources.TryReserve(charge)) { _hub.UntrackSource(); InvalidatePartition(); return false; }
|
||||
if (!_sources.TryAdd(ticket.Key, new SourceState(ticket, charge, fence, _epoch))) { _hub.Resources.Release(charge); _hub.UntrackSource(); return false; }
|
||||
return true;
|
||||
}
|
||||
finally { Monitor.Exit(_gate); }
|
||||
}
|
||||
|
||||
internal bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_disposed && _sources.TryGetValue(key, out var state))
|
||||
{ ApplyGate(state); ApplyPartitionEpoch(state); if (!state.Removed && Volatile.Read(ref state.Gate.Retired) == 0 && state.Fence?.IsRetired != true) { ticket = state.Ticket; return true; } }
|
||||
ticket = default; return false;
|
||||
}
|
||||
}
|
||||
internal bool IsTicketCurrentNonBlocking(SourceTicket ticket)
|
||||
{
|
||||
if (!_sources.TryGetValue(ticket.Key, out var state)) return false;
|
||||
var gate = Volatile.Read(ref state.Gate);
|
||||
var fence = Volatile.Read(ref state.Fence);
|
||||
return gate.Generation == ticket.Generation && ReferenceEquals(gate.Binding, ticket.Binding) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 &&
|
||||
fence?.IsRetired != true && ReferenceEquals(gate, Volatile.Read(ref state.Gate));
|
||||
}
|
||||
internal void WithLockForTest(Action action) { lock (_gate) action(); }
|
||||
private bool Current(SourceTicket ticket, out SourceState state)
|
||||
{
|
||||
if (!_sources.TryGetValue(ticket.Key, out state!)) return false;
|
||||
ApplyGate(state);
|
||||
ApplyPartitionEpoch(state);
|
||||
return !state.Removed && state.Ticket == ticket && ticket.Binding is { IsRetired: false } && Volatile.Read(ref state.Gate.Retired) == 0 && state.Fence?.IsRetired != true;
|
||||
}
|
||||
private void ApplyGate(SourceState state)
|
||||
{
|
||||
var gate = Volatile.Read(ref state.Gate);
|
||||
var signal = Volatile.Read(ref gate.Invalidated);
|
||||
if (state.AppliedInvalidations != signal)
|
||||
{
|
||||
InvalidateSource(state);
|
||||
state.AppliedInvalidations = signal;
|
||||
}
|
||||
}
|
||||
private void Signal(SourceTicket ticket, bool retired = false)
|
||||
{
|
||||
if (!_sources.TryGetValue(ticket.Key, out var state)) return;
|
||||
var gate = Volatile.Read(ref state.Gate);
|
||||
if (gate.Generation != ticket.Generation || !ReferenceEquals(gate.Binding, ticket.Binding)) return;
|
||||
if (retired)
|
||||
{
|
||||
gate.Binding.Retire();
|
||||
Interlocked.Exchange(ref gate.Retired, 1);
|
||||
Interlocked.Exchange(ref _retiredSweepRequested, 1);
|
||||
_hub.Schedule(this);
|
||||
}
|
||||
Interlocked.Increment(ref gate.Invalidated);
|
||||
}
|
||||
|
||||
internal bool TryReserve(SourceTicket ticket, long estimated, out IIngressReservation? reservation)
|
||||
{
|
||||
reservation = null;
|
||||
if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }
|
||||
try
|
||||
{
|
||||
if (_disposed || !Current(ticket, out var state)) return false;
|
||||
if (estimated <= 0 || estimated > long.MaxValue - PartitionedSampleHub.SampleOverhead ||
|
||||
Volatile.Read(ref _reservations) >= _hub.Limits.MaxIngressItemsPerPartition + _hub.Limits.MaxDirtySourcesPerPartition ||
|
||||
!_hub.Resources.TryReserve(estimated + PartitionedSampleHub.SampleOverhead))
|
||||
{ InvalidateSource(state); return false; }
|
||||
Interlocked.Increment(ref _reservations);
|
||||
Interlocked.Increment(ref state.Reservations);
|
||||
Interlocked.Increment(ref state.MetadataOwners);
|
||||
reservation = new Reservation(this, state, ticket, estimated, estimated + PartitionedSampleHub.SampleOverhead,
|
||||
state.InvalidationVersion, _epoch);
|
||||
return true;
|
||||
}
|
||||
finally { Monitor.Exit(_gate); }
|
||||
}
|
||||
private bool Commit(SourceState reservedState, SourceTicket ticket, long estimate, long charge, long invalidationVersion, long partitionEpoch, DataSample sample, long sequence)
|
||||
{
|
||||
if (!Monitor.TryEnter(_gate))
|
||||
{ ReleaseReservation(reservedState); _hub.Resources.Release(charge); Signal(ticket); return false; }
|
||||
try
|
||||
{
|
||||
ReleaseReservation(reservedState);
|
||||
if (_disposed || !Current(ticket, out var state)) { _hub.Resources.Release(charge); return false; }
|
||||
if (state.InvalidationVersion != invalidationVersion || _epoch != partitionEpoch) { _hub.Resources.Release(charge); return false; }
|
||||
try
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sample.Value);
|
||||
ArgumentNullException.ThrowIfNull(sample.Serving);
|
||||
sample.Serving.Validate(requireEpochs: false);
|
||||
if (sequence <= state.LastSubmitted || sample.Version != sequence || sample.Value.EstimatedRetainedBytes > estimate ||
|
||||
sample.Serving.NodeId != ticket.Key.ServingNodeId || sample.Serving.Incarnation != ticket.Key.ServingIncarnation)
|
||||
{ _hub.Resources.Release(charge); InvalidateSource(state); return false; }
|
||||
}
|
||||
catch (Exception e) when (e is ArgumentException or ObjectDisposedException or OverflowException)
|
||||
{ _hub.Resources.Release(charge); InvalidateSource(state); return false; }
|
||||
var pending = new Pending(ticket, sequence, ++_ordinal, sample, charge, _hub.Clock.GetTimestamp()) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch };
|
||||
if (_queuedValues < _hub.Limits.MaxIngressItemsPerPartition)
|
||||
{ _queue.Enqueue(pending); _queuedValues++; }
|
||||
else if (_dirty.TryGetValue(ticket.Key, out var previous))
|
||||
{ ReleasePending(previous); _dirty[ticket.Key] = pending; }
|
||||
else if (_dirty.Count < _hub.Limits.MaxDirtySourcesPerPartition) _dirty.Add(ticket.Key, pending);
|
||||
else { _hub.Resources.Release(charge); InvalidatePartition(); return false; }
|
||||
state.LastSubmitted = sequence;
|
||||
_hub.Schedule(this);
|
||||
return true;
|
||||
}
|
||||
finally { Monitor.Exit(_gate); }
|
||||
}
|
||||
private void ReleaseReservation(SourceState state)
|
||||
{
|
||||
Interlocked.Decrement(ref _reservations);
|
||||
var lastReservation = Interlocked.Decrement(ref state.Reservations) == 0;
|
||||
ReleaseMetadataOwner(state);
|
||||
if (lastReservation && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
||||
}
|
||||
private void Abandon(SourceState state, long charge) { ReleaseReservation(state); _hub.Resources.Release(charge); }
|
||||
internal void Invalidate(SourceTicket ticket) => Signal(ticket);
|
||||
private void InvalidateSource(SourceState state) { state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); ReleaseCache(state); }
|
||||
|
||||
internal bool TryStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server)
|
||||
{
|
||||
if (!Monitor.TryEnter(_gate)) { Signal(ticket); return false; }
|
||||
try
|
||||
{
|
||||
var partitionEpoch = Interlocked.Read(ref _epoch);
|
||||
if (_disposed || !Current(ticket, out var state) || sequence <= state.LastSubmitted) return false;
|
||||
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead)) { InvalidatePartition(); return false; }
|
||||
var wasReady = state.Readiness == DataReadiness.Ready;
|
||||
state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.Barrier = sequence; state.LastSubmitted = sequence;
|
||||
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, status, source, server, wasReady, ControlOverhead) { AdmissionEpoch = state.InvalidationVersion, PartitionEpoch = partitionEpoch }); _queuedControls++;
|
||||
_hub.Schedule(this); return true;
|
||||
}
|
||||
finally { Monitor.Exit(_gate); }
|
||||
}
|
||||
internal bool TryRemove(SourceTicket ticket, long sequence)
|
||||
{
|
||||
if (!Monitor.TryEnter(_gate)) { Signal(ticket, retired: true); return false; }
|
||||
try
|
||||
{
|
||||
// Retirement must still be able to release a source after its shared fence closed.
|
||||
if (_disposed || !_sources.TryGetValue(ticket.Key, out var state)) return false;
|
||||
ApplyGate(state); ApplyPartitionEpoch(state);
|
||||
if (state.Removed || state.Ticket != ticket || Volatile.Read(ref state.Gate.Retired) != 0 || sequence <= state.LastSubmitted) return false;
|
||||
if (_queuedControls >= _hub.Limits.MaxControlItemsPerPartition || !_hub.Resources.TryReserve(ControlOverhead))
|
||||
{ state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); RequestReclaim(); InvalidatePartition(); return false; }
|
||||
state.Removed = true; ticket.Binding!.Retire(); Interlocked.Exchange(ref state.Gate.Retired, 1); state.Readiness = DataReadiness.Invalidated; Interlocked.Increment(ref state.InvalidationVersion); state.LastSubmitted = sequence; ReleaseCache(state);
|
||||
RequestReclaim();
|
||||
_queue.Enqueue(new Pending(ticket, sequence, ++_ordinal, ControlOverhead) { PartitionEpoch = _epoch }); _queuedControls++;
|
||||
_hub.Schedule(this); return true;
|
||||
}
|
||||
finally { Monitor.Exit(_gate); }
|
||||
}
|
||||
|
||||
internal void Schedule()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _scheduled, 1) == 0)
|
||||
ThreadPool.QueueUserWorkItem(static p => ((SamplePartition)p!).Run(), this);
|
||||
}
|
||||
private void Run()
|
||||
{
|
||||
try { Drain(); }
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _scheduled, 0);
|
||||
lock (_gate) if (!_disposed && (_cleanedEpoch != _epoch || Volatile.Read(ref _retiredSweepRequested) != 0 || Volatile.Read(ref _reclaimRequested) != 0 || _queue.Count != 0 || _dirty.Count != 0)) Schedule();
|
||||
}
|
||||
}
|
||||
internal void Drain()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
CleanupInvalidatedEpoch();
|
||||
CleanupRetiredSources();
|
||||
while (!_disposed && (_queue.Count != 0 || _dirty.Count != 0))
|
||||
{
|
||||
Pending? dirty = null;
|
||||
foreach (var value in _dirty.Values) if (dirty is null || value.Ordinal < dirty.Ordinal) dirty = value;
|
||||
Pending p;
|
||||
if (dirty is not null && (_queue.Count == 0 || dirty.Ordinal < _queue.Peek().Ordinal))
|
||||
{ p = dirty; _dirty.Remove(p.Ticket.Key); }
|
||||
else
|
||||
{ p = _queue.Dequeue(); if (p.IsControl) _queuedControls--; else _queuedValues--; }
|
||||
if (p.PartitionEpoch != _epoch || !Current(p.Ticket, out var state) || p.AdmissionEpoch != state.InvalidationVersion || p.Sequence <= state.LastApplied)
|
||||
{ ReleasePending(p); continue; }
|
||||
state.LastApplied = p.Sequence;
|
||||
if (p.Sample is not null)
|
||||
{
|
||||
ReleaseCache(state); state.Sample = p.Sample; state.SampleCharge = p.Charge; state.Received = p.Received;
|
||||
state.Readiness = p.Sequence < state.Barrier ? DataReadiness.Invalidated : DataReadiness.Ready;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (p.IsStatus && state.Sample is not null)
|
||||
{
|
||||
var old = state.Sample;
|
||||
// Missing timestamps on a status-only event mean no new acquisition timestamp.
|
||||
state.Sample = old with { StatusCode = p.Status,
|
||||
SourceTimestampUtc = p.SourceTimestamp ?? old.SourceTimestampUtc,
|
||||
ServerTimestampUtc = p.ServerTimestamp ?? old.ServerTimestampUtc, Version = p.Sequence };
|
||||
state.Readiness = p.WasReady ? DataReadiness.Ready : DataReadiness.Invalidated;
|
||||
}
|
||||
else if (state.Sample is null) state.Readiness = DataReadiness.WaitingForInitialData;
|
||||
_hub.Resources.Release(p.Charge);
|
||||
}
|
||||
RecordChange(p.Ticket.Key);
|
||||
}
|
||||
ReclaimTombstones();
|
||||
}
|
||||
}
|
||||
private void RecordChange(BackingSourceKey key)
|
||||
{
|
||||
_watermark++;
|
||||
if (_changes.Count == _hub.Limits.MaxSnapshotCatchUpItems)
|
||||
{ _changes.Dequeue(); _hub.Resources.Release(ChangeOverhead); }
|
||||
if (!_hub.Resources.TryReserve(ChangeOverhead)) { InvalidatePartition(); return; }
|
||||
_changes.Enqueue((_watermark, key));
|
||||
}
|
||||
internal void InvalidatePartition()
|
||||
{
|
||||
Interlocked.Increment(ref _epoch);
|
||||
_hub.Schedule(this);
|
||||
}
|
||||
private void ApplyPartitionEpoch(SourceState state)
|
||||
{
|
||||
if (state.PartitionEpoch == _epoch) return;
|
||||
InvalidateSource(state);
|
||||
state.PartitionEpoch = _epoch;
|
||||
}
|
||||
private void CleanupInvalidatedEpoch()
|
||||
{
|
||||
var epoch = Interlocked.Read(ref _epoch);
|
||||
if (_cleanedEpoch == epoch) return;
|
||||
foreach (var pair in _sources) ApplyPartitionEpoch(pair.Value);
|
||||
while (_changes.TryDequeue(out _)) _hub.Resources.Release(ChangeOverhead);
|
||||
_cleanedEpoch = epoch;
|
||||
}
|
||||
private void CleanupRetiredSources()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _retiredSweepRequested, 0) == 0) return;
|
||||
foreach (var pair in _sources)
|
||||
{
|
||||
var state = pair.Value;
|
||||
if (Volatile.Read(ref state.Gate.Retired) == 0) continue;
|
||||
ApplyGate(state);
|
||||
state.Removed = true;
|
||||
InvalidateSource(state);
|
||||
RequestReclaim();
|
||||
}
|
||||
}
|
||||
private void RequestReclaim() { Interlocked.Exchange(ref _reclaimRequested, 1); _hub.Schedule(this); }
|
||||
private void ReclaimTombstones()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _reclaimRequested, 0) == 0) return;
|
||||
foreach (var pair in _sources)
|
||||
{
|
||||
var state = pair.Value;
|
||||
if (!state.Removed || Volatile.Read(ref state.Readers) != 0 || Volatile.Read(ref state.Reservations) != 0 || Volatile.Read(ref state.Snapshots) != 0) continue;
|
||||
if (_sources.TryRemove(pair.Key, out var removed) && ReferenceEquals(removed, state))
|
||||
RetireSourceState(state);
|
||||
}
|
||||
}
|
||||
private void RetireSourceState(SourceState state)
|
||||
{
|
||||
state.Ticket.Binding!.Retire();
|
||||
Interlocked.Exchange(ref state.Gate.Retired, 1);
|
||||
if (Interlocked.Exchange(ref state.RegistryRetired, 1) == 0) ReleaseMetadataOwner(state);
|
||||
}
|
||||
private void ReleaseMetadataOwner(SourceState state)
|
||||
{
|
||||
if (Interlocked.Decrement(ref state.MetadataOwners) != 0) return;
|
||||
_hub.Resources.Release(state.SourceCharge);
|
||||
_hub.UntrackSource();
|
||||
}
|
||||
private void ReleaseCache(SourceState state) { if (state.Sample is not null) { state.Sample.Dispose(); state.Sample = null; _hub.Resources.Release(state.SampleCharge); state.SampleCharge = 0; } }
|
||||
private void ReleasePending(Pending p) { p.Sample?.Dispose(); _hub.Resources.Release(p.Charge); }
|
||||
|
||||
internal CachedSourceRead Read(SourceTicket ticket) => Read(ticket, out _);
|
||||
internal CachedSourceRead Read(SourceTicket ticket, out long watermark)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
watermark = _watermark;
|
||||
if (_disposed || !Current(ticket, out var state)) return _hub.EmptyRead(DataItemStatus.NotFound, DataReadiness.Unavailable, _epoch);
|
||||
if (state.Readiness != DataReadiness.Ready || state.Sample is null)
|
||||
return _hub.EmptyRead(state.Readiness == DataReadiness.WaitingForInitialData ? DataItemStatus.WaitingForInitialData : DataItemStatus.Unavailable, state.Readiness, _epoch);
|
||||
var gate = Volatile.Read(ref state.Gate);
|
||||
var signal = Volatile.Read(ref gate.Invalidated);
|
||||
if (signal != state.AppliedInvalidations) return _hub.EmptyRead(DataItemStatus.Unavailable, DataReadiness.Invalidated, _epoch);
|
||||
var charge = checked(state.Sample.Value.EstimatedRetainedBytes + PartitionedSampleHub.ReferenceOverhead);
|
||||
if (!_hub.Resources.TryReserve(charge)) return _hub.EmptyRead(DataItemStatus.ResourceExhausted, DataReadiness.Unavailable, _epoch);
|
||||
Interlocked.Increment(ref state.Readers);
|
||||
Interlocked.Increment(ref state.MetadataOwners);
|
||||
return new CachedSourceRead(_hub.Resources, DataItemStatus.Good, state.Readiness,
|
||||
state.Sample with { Value = state.Sample.Value.Retain() }, state.LastApplied, state.PartitionEpoch, state.Received, charge,
|
||||
this, state, gate, Volatile.Read(ref state.InvalidationVersion), signal, _routingEpoch);
|
||||
}
|
||||
}
|
||||
internal void ReleaseRead(object source)
|
||||
{
|
||||
var state = (SourceState)source;
|
||||
var lastRead = Interlocked.Decrement(ref state.Readers) == 0;
|
||||
ReleaseMetadataOwner(state);
|
||||
if (lastRead && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
||||
}
|
||||
internal bool IsReadValid(object source, object sourceGate, long sourceVersion, long sourceSignal, long partitionEpoch, long routingEpoch)
|
||||
{
|
||||
var state = (SourceState)source;
|
||||
var gate = (SourceGate)sourceGate;
|
||||
return !_hub.IsDisposed && _hub.RoutingEpoch == routingEpoch && Interlocked.Read(ref _epoch) == partitionEpoch &&
|
||||
ReferenceEquals(gate, Volatile.Read(ref state.Gate)) && !gate.Binding.IsRetired && Volatile.Read(ref gate.Retired) == 0 &&
|
||||
Volatile.Read(ref gate.Invalidated) == sourceSignal && Volatile.Read(ref state.InvalidationVersion) == sourceVersion &&
|
||||
Volatile.Read(ref state.Fence)?.IsRetired != true;
|
||||
}
|
||||
internal bool Capture(IEnumerable<SourceTicket> tickets, Dictionary<SourceTicket, SnapshotItem> items, out long watermark, out long epoch, ref long charge, long limit)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
watermark = _watermark; epoch = _epoch;
|
||||
if (_disposed) return false;
|
||||
foreach (var ticket in tickets)
|
||||
{
|
||||
var exists = Current(ticket, out var state);
|
||||
var ready = exists && state.Readiness == DataReadiness.Ready && state.Sample is not null;
|
||||
var bytes = PartitionedSampleHub.ReferenceOverhead + (ready ? state.Sample!.Value.EstimatedRetainedBytes : 0);
|
||||
if (bytes > limit - charge || !_hub.Resources.TryReserve(bytes)) return false;
|
||||
charge += bytes;
|
||||
var sample = ready ? state.Sample! with { Value = state.Sample.Value.Retain() } : null;
|
||||
if (exists) { Interlocked.Increment(ref state.Snapshots); Interlocked.Increment(ref state.MetadataOwners); }
|
||||
items.Add(ticket, new SnapshotItem(exists ? state.Readiness : DataReadiness.Unavailable,
|
||||
exists ? (ready ? DataItemStatus.Good : DataItemStatus.Unavailable) : DataItemStatus.NotFound, sample,
|
||||
exists ? state.InvalidationVersion : -1) { Owner = exists ? this : null, Source = exists ? state : null });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
internal void ReleaseSnapshot(object source)
|
||||
{
|
||||
var state = (SourceState)source;
|
||||
var lastSnapshot = Interlocked.Decrement(ref state.Snapshots) == 0;
|
||||
ReleaseMetadataOwner(state);
|
||||
if (lastSnapshot && Volatile.Read(ref state.Gate.Retired) != 0 && !Volatile.Read(ref _disposed)) RequestReclaim();
|
||||
}
|
||||
internal bool IsSnapshotCurrent(long epoch, long watermark, IEnumerable<KeyValuePair<SourceTicket, SnapshotItem>> tickets)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || epoch != _epoch || (_changes.Count > 0 && watermark < _changes.Peek().Version - 1)) return false;
|
||||
return tickets.All(t => Current(t.Key, out var state) && state.InvalidationVersion == t.Value.InvalidationVersion);
|
||||
}
|
||||
}
|
||||
internal long CurrentWatermark { get { lock (_gate) return _watermark; } }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return; _disposed = true; InvalidatePartition(); CleanupInvalidatedEpoch();
|
||||
while (_queue.TryDequeue(out var p)) ReleasePending(p);
|
||||
foreach (var p in _dirty.Values) ReleasePending(p);
|
||||
_dirty.Clear(); _queuedValues = 0; _queuedControls = 0;
|
||||
foreach (var pair in _sources) { pair.Value.Removed = true; RetireSourceState(pair.Value); }
|
||||
_sources.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SourceGate(SourceGeneration generation, SourceBindingFence binding)
|
||||
{ public readonly SourceGeneration Generation = generation; public readonly SourceBindingFence Binding = binding; public long Invalidated; public int Retired; }
|
||||
private sealed class SourceState(SourceTicket ticket, long sourceCharge, ProducerFence? fence, long partitionEpoch)
|
||||
{
|
||||
public SourceTicket Ticket = ticket; public SourceGeneration Generation = ticket.Generation; public readonly long SourceCharge = sourceCharge;
|
||||
public SourceGate Gate = new(ticket.Generation, ticket.Binding!);
|
||||
public ProducerFence? Fence = fence; public long PartitionEpoch = partitionEpoch;
|
||||
public long AppliedInvalidations;
|
||||
// The registry owns one metadata reference; each retained read, snapshot and reservation owns one more.
|
||||
public int MetadataOwners = 1; public int RegistryRetired;
|
||||
public int Readers; public int Reservations; public int Snapshots;
|
||||
public bool Removed; public DataReadiness Readiness = DataReadiness.WaitingForInitialData;
|
||||
public DataSample? Sample; public long SampleCharge; public long Received;
|
||||
public long LastSubmitted; public long LastApplied; public long Barrier; public long InvalidationVersion;
|
||||
}
|
||||
private sealed class Pending
|
||||
{
|
||||
public Pending(SourceTicket ticket, long sequence, long ordinal, DataSample sample, long charge, long received)
|
||||
{ Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Sample = sample; Charge = charge; Received = received; }
|
||||
public Pending(SourceTicket ticket, long sequence, long ordinal, uint status, DateTimeOffset? source, DateTimeOffset? server, bool wasReady, long charge)
|
||||
{ Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Status = status; SourceTimestamp = source; ServerTimestamp = server; WasReady = wasReady; Charge = charge; IsControl = true; IsStatus = true; }
|
||||
public Pending(SourceTicket ticket, long sequence, long ordinal, long charge) { Ticket = ticket; Sequence = sequence; Ordinal = ordinal; Charge = charge; IsControl = true; }
|
||||
public SourceTicket Ticket; public long Sequence; public long Ordinal; public DataSample? Sample; public long Charge; public long Received; public long AdmissionEpoch; public long PartitionEpoch;
|
||||
public bool IsControl; public bool IsStatus; public uint Status; public DateTimeOffset? SourceTimestamp; public DateTimeOffset? ServerTimestamp; public bool WasReady;
|
||||
}
|
||||
private sealed class Reservation(SamplePartition partition, SourceState state, SourceTicket ticket, long estimate, long charge,
|
||||
long invalidationVersion, long partitionEpoch) : IIngressReservation
|
||||
{
|
||||
private int _completed;
|
||||
public bool TryCommit(DataSample owned, long sequence)
|
||||
{ ArgumentNullException.ThrowIfNull(owned); return Interlocked.Exchange(ref _completed, 1) == 0 && partition.Commit(state, ticket, estimate, charge, invalidationVersion, partitionEpoch, owned, sequence); }
|
||||
public void Dispose() { if (Interlocked.Exchange(ref _completed, 1) == 0) partition.Abandon(state, charge); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Frozen item state. Its sample belongs to the containing snapshot.</summary>
|
||||
public sealed record SnapshotItem(DataReadiness Readiness, DataItemStatus Status, DataSample? Sample, long InvalidationVersion)
|
||||
{
|
||||
internal SamplePartition? Owner { get; init; }
|
||||
internal object? Source { get; init; }
|
||||
internal void ReleaseSource() { if (Owner is not null && Source is not null) Owner.ReleaseSnapshot(Source); }
|
||||
}
|
||||
|
||||
/// <summary>Retained immutable snapshots and per-partition catch-up watermarks.</summary>
|
||||
public sealed class SnapshotLease : IDisposable
|
||||
{
|
||||
private readonly PartitionedSampleHub _hub;
|
||||
private readonly SamplePartition[] _partitions;
|
||||
private readonly long _routingEpoch;
|
||||
private readonly long _charge;
|
||||
private readonly int _itemCount;
|
||||
private readonly Dictionary<int, long> _epochs;
|
||||
private readonly Dictionary<SourceTicket, int> _owners;
|
||||
private readonly Dictionary<SourceTicket, long> _positions;
|
||||
private readonly Dictionary<SourceTicket, long> _versions;
|
||||
private readonly object _gate = new();
|
||||
private CancellationTokenRegistration _cancellation;
|
||||
private ITimer? _timer;
|
||||
private int _released;
|
||||
|
||||
internal SnapshotLease(PartitionedSampleHub hub, Dictionary<SourceTicket, SnapshotItem> items,
|
||||
Dictionary<int, long> watermarks, Dictionary<int, long> epochs, SamplePartition[] partitions,
|
||||
long routingEpoch, long charge, int itemCount, TimeSpan lifetime, CancellationToken cancellationToken)
|
||||
{
|
||||
_hub = hub; _partitions = partitions; _routingEpoch = routingEpoch; _charge = charge; _itemCount = itemCount;
|
||||
_epochs = epochs;
|
||||
Items = new ReadOnlyDictionary<SourceTicket, SnapshotItem>(items);
|
||||
Watermarks = new ReadOnlyDictionary<int, long>(watermarks);
|
||||
_owners = items.Keys.ToDictionary(t => t, t => PartitionedSampleHub.GetPartitionFor(t.Key, partitions.Length));
|
||||
_positions = items.Keys.ToDictionary(t => t, t => watermarks[_owners[t]]);
|
||||
_versions = items.ToDictionary(p => p.Key, p => p.Value.Sample?.Version ?? 0);
|
||||
_timer = hub.Clock.CreateTimer(static o => ((SnapshotLease)o!).Dispose(), this, lifetime, Timeout.InfiniteTimeSpan);
|
||||
_cancellation = cancellationToken.Register(static o => ((SnapshotLease)o!).Dispose(), this);
|
||||
}
|
||||
public IReadOnlyDictionary<SourceTicket, SnapshotItem> Items { get; }
|
||||
public IReadOnlyDictionary<int, long> Watermarks { get; }
|
||||
public bool IsReset
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_released != 0) return true;
|
||||
if (_hub.IsDisposed || _hub.RoutingEpoch != _routingEpoch) { Release(); return true; }
|
||||
foreach (var group in Items.GroupBy(p => _owners[p.Key]))
|
||||
{
|
||||
var watermark = group.Min(p => _positions[p.Key]);
|
||||
if (!_partitions[group.Key].IsSnapshotCurrent(_epochs[group.Key], watermark, group)) { Release(); return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>Returns the latest newer sample as an independently disposable, globally charged read.</summary>
|
||||
public bool TryReadDelta(SourceTicket ticket, out CachedSourceRead? delta)
|
||||
{
|
||||
delta = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (IsReset || !_owners.TryGetValue(ticket, out var owner)) return false;
|
||||
var read = _partitions[owner].Read(ticket, out var readWatermark);
|
||||
if (read.Status == DataItemStatus.ResourceExhausted) { read.Dispose(); Release(); return false; }
|
||||
if (read.Readiness != DataReadiness.Ready || read.Sample is null) { read.Dispose(); Release(); return false; }
|
||||
if (IsReset) { read.Dispose(); return false; }
|
||||
var version = read.Sample.Version;
|
||||
if (version <= _versions[ticket]) { read.Dispose(); return false; }
|
||||
_versions[ticket] = version;
|
||||
_positions[ticket] = readWatermark;
|
||||
delta = read; return true;
|
||||
}
|
||||
}
|
||||
private void Release()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) != 0) return;
|
||||
_timer?.Dispose(); _cancellation.Unregister();
|
||||
foreach (var item in Items.Values) { item.Sample?.Dispose(); item.ReleaseSource(); }
|
||||
_hub.Resources.Release(_charge); _hub.UntrackSnapshotItems(_itemCount);
|
||||
_hub.ForgetSnapshot(this);
|
||||
}
|
||||
public void Dispose() { lock (_gate) Release(); }
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Trusted acquisition shape; aliases share this source-level descriptor.</summary>
|
||||
public readonly record struct SourceValueShape(DataValueKind Kind, DataValueKind? ElementKind, int Rank)
|
||||
{
|
||||
public static SourceValueShape FromDriverType(string dataType, bool isArray)
|
||||
{
|
||||
var kind = dataType switch
|
||||
{
|
||||
"Boolean" or "Bool" => DataValueKind.Boolean,
|
||||
"SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8,
|
||||
"Int16" => DataValueKind.Int16, "UInt16" => DataValueKind.UInt16,
|
||||
"Int32" or "Int" => DataValueKind.Int32, "UInt32" or "UInt" => DataValueKind.UInt32,
|
||||
"Int64" => DataValueKind.Int64, "UInt64" => DataValueKind.UInt64,
|
||||
"Float" => DataValueKind.Float, "Double" => DataValueKind.Double,
|
||||
"String" => DataValueKind.String, "ByteString" => DataValueKind.Bytes,
|
||||
"DateTime" => DataValueKind.Timestamp, "Guid" => DataValueKind.Guid,
|
||||
_ => DataValueKind.Unspecified
|
||||
};
|
||||
return isArray ? new(DataValueKind.Array, kind, 1) : new(kind, null, -1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Constructs acquisition identities independently of catalog views and principals.</summary>
|
||||
public static class SourceKey
|
||||
{
|
||||
public static BackingSourceKey ForDriver(string cluster, string driver, string reference, string node, string incarnation) =>
|
||||
new(cluster.ToUpperInvariant(), "driver", string.Concat(driver.Length.ToString(CultureInfo.InvariantCulture), ":", driver, reference), node, incarnation);
|
||||
public static BackingSourceKey ForVirtual(string cluster, string virtualTagId, string node, string incarnation) =>
|
||||
new(cluster.ToUpperInvariant(), "virtual", virtualTagId, node, incarnation);
|
||||
|
||||
internal static bool TryDriver(BackingSourceKey key, out string driver, out string reference)
|
||||
{
|
||||
driver = reference = string.Empty;
|
||||
if (key.SourceKind != "driver") return false;
|
||||
var colon = key.StableSourceId.IndexOf(':');
|
||||
if (colon <= 0 || !int.TryParse(key.StableSourceId.AsSpan(0, colon), NumberStyles.None, CultureInfo.InvariantCulture, out var length) ||
|
||||
length < 0 || length > key.StableSourceId.Length - colon - 1) return false;
|
||||
driver = key.StableSourceId.Substring(colon + 1, length);
|
||||
reference = key.StableSourceId[(colon + 1 + length)..];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sequences source data and lifecycle changes before the asynchronous actor boundary.</summary>
|
||||
public sealed class SourceSamplePublisher
|
||||
{
|
||||
private readonly ISourceSampleHub _hub;
|
||||
private readonly Func<ServingIdentity?> _serving;
|
||||
private readonly string? _originClusterId;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<BackingSourceKey, SourceTicket> _tickets = new();
|
||||
private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new();
|
||||
private readonly Dictionary<string, BackingSourceKey> _virtuals = new(StringComparer.Ordinal);
|
||||
private sealed class SourceSlot
|
||||
{
|
||||
public readonly object Gate = new();
|
||||
public SourceBinding? Current;
|
||||
public long Sequence;
|
||||
public int RepairQueued;
|
||||
public int RepairAttempts;
|
||||
}
|
||||
private sealed class SourceBinding(SourceTicket ticket, SourceSlot slot, ProducerFence? producer, SourceValueShape? shape)
|
||||
{
|
||||
public SourceTicket Ticket { get; } = ticket;
|
||||
public SourceSlot Slot { get; } = slot;
|
||||
public ProducerFence? Producer { get; } = producer;
|
||||
public SourceValueShape? Shape { get; } = shape;
|
||||
public int InFlight;
|
||||
public bool Active => Producer is null || !Producer.IsRetired;
|
||||
}
|
||||
private readonly ConcurrentDictionary<BackingSourceKey, SourceSlot> _slots = new();
|
||||
private readonly ConcurrentDictionary<(string Driver, string Reference), SourceBinding> _driverRoutes = new();
|
||||
private readonly Dictionary<(string Driver, string Reference), SourceValueShape> _driverShapes = new();
|
||||
private const int MaxRegisteredDriverShapes = 100_000;
|
||||
private const int MaxProducerIncarnations = 100_000;
|
||||
private readonly ConcurrentDictionary<string, SourceBinding> _virtualRoutes = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, ProducerFence> _driverIncarnations = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, ProducerFence> _virtualIncarnations = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentQueue<SourceSlot> _repairQueue = new();
|
||||
private const int MaxPendingRepairs = 4096;
|
||||
private int _repairCount;
|
||||
private int _repairWorkerScheduled;
|
||||
private readonly Timer _repairTimer;
|
||||
private long _nextDriverIncarnation;
|
||||
|
||||
public SourceSamplePublisher(ISourceSampleHub hub, ServingIdentity serving) : this(hub, () => serving, null) { }
|
||||
public SourceSamplePublisher(ISourceSampleHub hub, Func<ServingIdentity?> serving, string? originClusterId = null)
|
||||
{
|
||||
_hub = hub ?? throw new ArgumentNullException(nameof(hub));
|
||||
_serving = serving ?? throw new ArgumentNullException(nameof(serving));
|
||||
_originClusterId = originClusterId;
|
||||
_repairTimer = new Timer(static state => ((SourceSamplePublisher)state!).ScheduleRepairWorker(), this,
|
||||
Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
|
||||
public SourceTicket Bind(BackingSourceKey key, SourceGeneration generation)
|
||||
{
|
||||
var ticket = new SourceTicket(key, generation);
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_slots.TryGetValue(key, out var slot)) slot = new SourceSlot();
|
||||
lock (slot.Gate)
|
||||
{
|
||||
ProducerFence? producer = null;
|
||||
if (SourceKey.TryDriver(key, out var driver, out var reference))
|
||||
_driverIncarnations.TryGetValue(driver, out producer);
|
||||
else if (key.SourceKind == "virtual")
|
||||
_virtualIncarnations.TryGetValue(key.StableSourceId, out producer);
|
||||
if (producer is not null && producer.Incarnation != generation.Incarnation) producer = null;
|
||||
if (!_hub.TryBind(ticket, producer)) throw new InvalidOperationException("The source generation could not be bound.");
|
||||
_slots.TryAdd(key, slot);
|
||||
_nextDriverIncarnation = Math.Max(_nextDriverIncarnation, generation.Incarnation);
|
||||
SourceValueShape? shape = null;
|
||||
if (SourceKey.TryDriver(key, out var shapeDriver, out var shapeRef) &&
|
||||
_driverShapes.TryGetValue((shapeDriver, shapeRef), out var registeredShape)) shape = registeredShape;
|
||||
var binding = new SourceBinding(ticket, slot, producer, shape);
|
||||
_tickets[key] = ticket;
|
||||
Volatile.Write(ref slot.Current, binding);
|
||||
if (SourceKey.TryDriver(key, out driver, out reference))
|
||||
{
|
||||
_drivers[(driver, reference)] = key;
|
||||
_driverRoutes[(driver, reference)] = binding;
|
||||
}
|
||||
else if (key.SourceKind == "virtual")
|
||||
{
|
||||
_virtuals[key.StableSourceId] = key;
|
||||
_virtualRoutes[key.StableSourceId] = binding;
|
||||
}
|
||||
return ticket;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryCapture(BackingSourceKey key, out SourceTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
if (!_slots.TryGetValue(key, out var slot)) return false;
|
||||
var binding = Volatile.Read(ref slot.Current);
|
||||
if (binding is null || !binding.Active) return false;
|
||||
ticket = binding.Ticket;
|
||||
return true;
|
||||
}
|
||||
public bool TryCaptureDriver(string driver, string reference, out SourceTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
if (!_driverRoutes.TryGetValue((driver, reference), out var binding) || !binding.Active ||
|
||||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
|
||||
ticket = binding.Ticket;
|
||||
return true;
|
||||
}
|
||||
public bool TryCaptureDriver(string driver, string reference, long incarnation, out SourceTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation || producer.IsRetired ||
|
||||
!_driverRoutes.TryGetValue((driver, reference), out var binding) || !ReferenceEquals(binding.Producer, producer) ||
|
||||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
|
||||
ticket = binding.Ticket;
|
||||
return !producer.IsRetired;
|
||||
}
|
||||
public long RegisterDriverIncarnation(string driver)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_driverIncarnations.ContainsKey(driver) && _driverIncarnations.Count >= MaxProducerIncarnations)
|
||||
throw new InvalidOperationException("Driver producer registry is full.");
|
||||
if (_driverIncarnations.TryGetValue(driver, out var old)) old.Retire();
|
||||
var token = checked(++_nextDriverIncarnation);
|
||||
_driverIncarnations[driver] = new ProducerFence(token);
|
||||
return token;
|
||||
}
|
||||
}
|
||||
public bool IsDriverIncarnationActive(string driver, long incarnation) =>
|
||||
_driverIncarnations.TryGetValue(driver, out var producer) && producer.Incarnation == incarnation && !producer.IsRetired;
|
||||
public void RetireCurrentDriver(string driver)
|
||||
{ if (_driverIncarnations.TryGetValue(driver, out var producer)) RetireDriver(driver, producer.Incarnation); }
|
||||
public bool RegisterDriverShape(string driver, string reference, SourceValueShape shape)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var key = (driver, reference);
|
||||
if (_driverShapes.TryGetValue(key, out var old) && old == shape) return true;
|
||||
if (!_driverShapes.ContainsKey(key) && _driverShapes.Count >= MaxRegisteredDriverShapes) return false;
|
||||
_driverShapes[key] = shape;
|
||||
if (_driverRoutes.TryGetValue(key, out var binding)) TryRebind(binding.Ticket, out _);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public void ForgetDriverShape(string driver, string reference)
|
||||
{ lock (_gate) _driverShapes.Remove((driver, reference)); }
|
||||
public bool EnsureDriverBinding(string cluster, string driver, string reference, long incarnation)
|
||||
{
|
||||
// A slow control-plane reconciliation or retirement must not stall legacy acquisition.
|
||||
if (!Monitor.TryEnter(_gate)) return false;
|
||||
try
|
||||
{
|
||||
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation || producer.IsRetired) return false;
|
||||
if (!_driverShapes.ContainsKey((driver, reference))) return false;
|
||||
var serving = _serving();
|
||||
if (serving is null || string.IsNullOrWhiteSpace(cluster)) return false;
|
||||
var key = SourceKey.ForDriver(cluster, driver, reference, serving.NodeId, serving.Incarnation);
|
||||
if (!_slots.TryGetValue(key, out var slot)) return EnsureBinding(key, incarnation);
|
||||
if (!Monitor.TryEnter(slot.Gate))
|
||||
{
|
||||
var binding = Volatile.Read(ref slot.Current);
|
||||
if (binding?.Producer is { } current && ReferenceEquals(current, producer) && !current.IsRetired)
|
||||
_hub.Invalidate(binding.Ticket, "source binding contention");
|
||||
return false;
|
||||
}
|
||||
try { return EnsureBinding(key, incarnation); }
|
||||
finally { Monitor.Exit(slot.Gate); }
|
||||
}
|
||||
finally { Monitor.Exit(_gate); }
|
||||
}
|
||||
public void RetireDriver(string driver, long incarnation)
|
||||
{
|
||||
// The hub sees the same fence. Reads and snapshots are denied before the slow per-tag walk.
|
||||
if (!_driverIncarnations.TryGetValue(driver, out var producer) || producer.Incarnation != incarnation) return;
|
||||
producer.Retire();
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_driverIncarnations.TryGetValue(driver, out var current) || !ReferenceEquals(current, producer)) return;
|
||||
_driverIncarnations.TryRemove(driver, out _);
|
||||
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
|
||||
if (_tickets.TryGetValue(key, out var ticket)) TryRemove(ticket);
|
||||
}
|
||||
}
|
||||
public void PublishDriverStatus(string driver, uint status)
|
||||
{
|
||||
lock (_gate)
|
||||
foreach (var key in _drivers.Where(x => x.Key.Driver == driver).Select(x => x.Value).ToArray())
|
||||
if (_tickets.TryGetValue(key, out var ticket)) TryPublishStatus(ticket, status, out _);
|
||||
}
|
||||
public bool TryCaptureVirtual(string id, out SourceTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
if (!_virtualRoutes.TryGetValue(id, out var binding) || !binding.Active ||
|
||||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
|
||||
ticket = binding.Ticket;
|
||||
return true;
|
||||
}
|
||||
public long RegisterVirtualIncarnation(string id)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_virtualIncarnations.ContainsKey(id) && _virtualIncarnations.Count >= MaxProducerIncarnations)
|
||||
throw new InvalidOperationException("Virtual producer registry is full.");
|
||||
if (_virtualIncarnations.TryGetValue(id, out var old)) RetireVirtualIncarnation(id, old.Incarnation);
|
||||
var token = checked(++_nextDriverIncarnation);
|
||||
_virtualIncarnations[id] = new ProducerFence(token);
|
||||
return token;
|
||||
}
|
||||
}
|
||||
public bool IsVirtualIncarnationActive(string id, long incarnation) =>
|
||||
_virtualIncarnations.TryGetValue(id, out var producer) && producer.Incarnation == incarnation && !producer.IsRetired;
|
||||
public void RetireCurrentVirtual(string id)
|
||||
{ if (_virtualIncarnations.TryGetValue(id, out var producer)) RetireVirtualIncarnation(id, producer.Incarnation); }
|
||||
public bool EnsureVirtualBinding(string id, long incarnation)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation || producer.IsRetired) return false;
|
||||
var serving = _serving();
|
||||
if (serving is null) return false;
|
||||
if (_virtuals.TryGetValue(id, out var existing)) return EnsureBinding(existing, incarnation);
|
||||
if (string.IsNullOrWhiteSpace(_originClusterId)) return false;
|
||||
return EnsureBinding(SourceKey.ForVirtual(_originClusterId, id, serving.NodeId, serving.Incarnation), incarnation);
|
||||
}
|
||||
}
|
||||
private bool EnsureBinding(BackingSourceKey key, long incarnation)
|
||||
{
|
||||
if (_tickets.TryGetValue(key, out var existing))
|
||||
{
|
||||
if (existing.Generation.Incarnation == incarnation && _hub.IsTicketCurrentNonBlocking(existing)) return true;
|
||||
if (existing.Generation.Incarnation == incarnation)
|
||||
{
|
||||
try { Bind(key, existing.Generation with { Lifecycle = checked(existing.Generation.Lifecycle + 1) }); return true; }
|
||||
catch (InvalidOperationException) { _hub.Invalidate(existing, "source rebind unavailable"); return false; }
|
||||
}
|
||||
// A failed removal has already retired/fenced the old generation in the hub.
|
||||
TryRemove(existing);
|
||||
}
|
||||
try { Bind(key, new SourceGeneration(incarnation, 1)); return true; }
|
||||
catch (InvalidOperationException) { return false; }
|
||||
}
|
||||
public void RetireVirtualIncarnation(string id, long incarnation)
|
||||
{
|
||||
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation) return;
|
||||
producer.Retire();
|
||||
lock (_gate)
|
||||
if (_virtualIncarnations.TryGetValue(id, out var current) && ReferenceEquals(current, producer))
|
||||
{
|
||||
_virtualIncarnations.TryRemove(id, out _);
|
||||
if (_virtualRoutes.TryGetValue(id, out var binding) && ReferenceEquals(binding.Producer, producer))
|
||||
TryRemove(binding.Ticket);
|
||||
}
|
||||
}
|
||||
public bool TryCaptureVirtual(string id, long incarnation, out SourceTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
if (!_virtualIncarnations.TryGetValue(id, out var producer) || producer.Incarnation != incarnation || producer.IsRetired ||
|
||||
!_virtualRoutes.TryGetValue(id, out var binding) || !ReferenceEquals(binding.Producer, producer) ||
|
||||
!ReferenceEquals(Volatile.Read(ref binding.Slot.Current), binding)) return false;
|
||||
ticket = binding.Ticket;
|
||||
return !producer.IsRetired;
|
||||
}
|
||||
|
||||
public bool TryPublish(SourceTicket ticket, DataValueSnapshot snapshot)
|
||||
{
|
||||
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
|
||||
var binding = Volatile.Read(ref slot.Current);
|
||||
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
|
||||
Interlocked.Increment(ref binding.InFlight);
|
||||
IIngressReservation? reservation = null;
|
||||
DataValue? value = null;
|
||||
DataSample? sample = null;
|
||||
try
|
||||
{
|
||||
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
|
||||
var size = OwnedDataSample.Estimate(snapshot.Value, binding.Shape);
|
||||
if (!_hub.TryReserveIngress(ticket, size, out reservation) || reservation is null)
|
||||
{
|
||||
_hub.Invalidate(ticket, "source ingress capacity");
|
||||
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
|
||||
return false;
|
||||
}
|
||||
value = OwnedDataSample.Copy(snapshot.Value, binding.Shape);
|
||||
if (!Monitor.TryEnter(slot.Gate))
|
||||
{ _hub.Invalidate(ticket, "source serialization contention"); return false; }
|
||||
try
|
||||
{
|
||||
if (!binding.Active || !ReferenceEquals(Volatile.Read(ref slot.Current), binding)) return false;
|
||||
var serving = _serving();
|
||||
if (serving is null || serving.NodeId != ticket.Key.ServingNodeId || serving.Incarnation != ticket.Key.ServingIncarnation ||
|
||||
string.IsNullOrWhiteSpace(serving.Role) || serving.CatalogEpoch < 0 || serving.AuthorityEpoch < 0)
|
||||
{ _hub.Invalidate(ticket, "serving identity unavailable"); return false; }
|
||||
var sequence = checked(++slot.Sequence);
|
||||
sample = new DataSample(value, snapshot.StatusCode, OwnedDataSample.Timestamp(snapshot.SourceTimestampUtc),
|
||||
OwnedDataSample.Timestamp(snapshot.ServerTimestampUtc), serving, sequence);
|
||||
value = null;
|
||||
if (!reservation.TryCommit(sample, sequence))
|
||||
{
|
||||
_hub.Invalidate(ticket, "source commit rejected");
|
||||
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
|
||||
return false;
|
||||
}
|
||||
sample = null;
|
||||
return true;
|
||||
}
|
||||
finally { Monitor.Exit(slot.Gate); }
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException)
|
||||
{ _hub.Invalidate(ticket, "unsupported or oversized source sample"); return false; }
|
||||
finally
|
||||
{
|
||||
value?.Dispose();
|
||||
sample?.Dispose();
|
||||
reservation?.Dispose();
|
||||
Interlocked.Decrement(ref binding.InFlight);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Synchronously invalidates a malformed callback's captured source generation.</summary>
|
||||
public void Invalidate(SourceTicket ticket, string reason) => _hub.Invalidate(ticket, reason);
|
||||
|
||||
private void ScheduleRepair(SourceSlot slot, SourceTicket ticket)
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref slot.RepairQueued, 1, 0) != 0) return;
|
||||
if (Interlocked.Increment(ref _repairCount) > MaxPendingRepairs)
|
||||
{
|
||||
Interlocked.Decrement(ref _repairCount);
|
||||
Volatile.Write(ref slot.RepairQueued, 0);
|
||||
_hub.InvalidatePartitionFor(ticket.Key, "source repair capacity");
|
||||
return;
|
||||
}
|
||||
Volatile.Write(ref slot.RepairAttempts, 0);
|
||||
_repairQueue.Enqueue(slot);
|
||||
ScheduleRepairWorker();
|
||||
}
|
||||
|
||||
private void ScheduleRepairWorker()
|
||||
{
|
||||
if (Interlocked.CompareExchange(ref _repairWorkerScheduled, 1, 0) == 0)
|
||||
ThreadPool.QueueUserWorkItem(static state => ((SourceSamplePublisher)state!).RunRepairs(), this);
|
||||
}
|
||||
|
||||
private void RunRepairs()
|
||||
{
|
||||
var remaining = Math.Min(64, Volatile.Read(ref _repairCount));
|
||||
while (remaining-- > 0 && _repairQueue.TryDequeue(out var slot))
|
||||
{
|
||||
var binding = Volatile.Read(ref slot.Current);
|
||||
var completed = binding is null || !binding.Active;
|
||||
if (!completed)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var current = Volatile.Read(ref slot.Current);
|
||||
completed = current is null || !current.Active ||
|
||||
EnsureBinding(current.Ticket.Key, current.Ticket.Generation.Incarnation);
|
||||
}
|
||||
}
|
||||
if (!completed && Interlocked.Increment(ref slot.RepairAttempts) >= 16)
|
||||
{
|
||||
var last = Volatile.Read(ref slot.Current);
|
||||
if (last is not null) _hub.InvalidatePartitionFor(last.Ticket.Key, "source repair exhausted");
|
||||
completed = true;
|
||||
}
|
||||
if (completed)
|
||||
{
|
||||
Volatile.Write(ref slot.RepairQueued, 0);
|
||||
Interlocked.Decrement(ref _repairCount);
|
||||
}
|
||||
else _repairQueue.Enqueue(slot);
|
||||
}
|
||||
Volatile.Write(ref _repairWorkerScheduled, 0);
|
||||
if (Volatile.Read(ref _repairCount) > 0)
|
||||
_repairTimer.Change(TimeSpan.FromMilliseconds(250), Timeout.InfiniteTimeSpan);
|
||||
}
|
||||
|
||||
public bool TryPublishStatus(SourceTicket ticket, uint status, out SourceTicket next)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
next = default;
|
||||
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
|
||||
lock (slot.Gate)
|
||||
{
|
||||
var binding = Volatile.Read(ref slot.Current);
|
||||
if (binding is null || binding.Ticket != ticket || !binding.Active) return false;
|
||||
next = ticket;
|
||||
if (Volatile.Read(ref binding.InFlight) > 0)
|
||||
{
|
||||
try { next = Bind(ticket.Key, ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) }); }
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
_hub.Invalidate(ticket, "source status fence failed");
|
||||
if (!_hub.IsTicketCurrentNonBlocking(ticket)) ScheduleRepair(slot, ticket);
|
||||
return false;
|
||||
}
|
||||
_hub.Invalidate(next, "status overtook in-flight source sample");
|
||||
}
|
||||
if (_hub.TryPublishStatus(next, checked(++slot.Sequence), status, null, null)) return true;
|
||||
_hub.Invalidate(next, "source status capacity");
|
||||
if (!_hub.IsTicketCurrentNonBlocking(next)) ScheduleRepair(slot, next);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryRemove(SourceTicket ticket)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_slots.TryGetValue(ticket.Key, out var slot)) return false;
|
||||
lock (slot.Gate)
|
||||
{
|
||||
var binding = Volatile.Read(ref slot.Current);
|
||||
if (binding is null || binding.Ticket != ticket) return false;
|
||||
Volatile.Write(ref slot.Current, null);
|
||||
_slots.TryRemove(ticket.Key, out _);
|
||||
_tickets.Remove(ticket.Key);
|
||||
if (SourceKey.TryDriver(ticket.Key, out var driver, out var reference))
|
||||
{ _drivers.Remove((driver, reference)); _driverRoutes.TryRemove((driver, reference), out _); }
|
||||
else if (ticket.Key.SourceKind == "virtual")
|
||||
{ _virtuals.Remove(ticket.Key.StableSourceId); _virtualRoutes.TryRemove(ticket.Key.StableSourceId, out _); }
|
||||
if (_hub.TryRemove(ticket, checked(++slot.Sequence))) return true;
|
||||
_hub.Invalidate(ticket, "source removal capacity");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
/// <summary>Closes an old physical binding and opens a newer, initially unready generation.</summary>
|
||||
public bool TryRebind(SourceTicket ticket, out SourceTicket next)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
next = default;
|
||||
if (!TryRemove(ticket)) return false;
|
||||
var generation = ticket.Generation with { Lifecycle = checked(ticket.Generation.Lifecycle + 1) };
|
||||
try { next = Bind(ticket.Key, generation); return true; }
|
||||
catch (InvalidOperationException) { return false; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,19 @@ public static partial class DeploymentArtifact
|
||||
|
||||
internal sealed partial class ParsedDeploymentArtifact
|
||||
{
|
||||
/// <summary>Materialize this node's eligible catalog inputs while the artifact document is alive.</summary>
|
||||
internal DraftSnapshot? ParseLocalCatalogSnapshot(string nodeId) => ReadDataProjection(nodeId)?.Snapshot;
|
||||
|
||||
/// <summary>Legacy artifacts and empty data sections do not require an activated data catalog.</summary>
|
||||
internal bool ExpectsLocalDataCatalog()
|
||||
{
|
||||
var root = Root;
|
||||
if (root.ValueKind != JsonValueKind.Object) return false;
|
||||
return new[] { "DataConnections", "DataExports", "RemoteNamespaceMappings" }
|
||||
.Any(name => root.TryGetProperty(name, out var value)
|
||||
&& (value.ValueKind != JsonValueKind.Array || value.GetArrayLength() != 0));
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions DataJsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -172,6 +185,7 @@ internal sealed partial class ParsedDeploymentArtifact
|
||||
UnsTagReferences = ReadTopology<UnsTagReference>(root, "UnsTagReferences"),
|
||||
VirtualTags = ReadTopology<VirtualTag>(root, "VirtualTags"),
|
||||
ScriptedAlarms = ReadTopology<ScriptedAlarm>(root, "ScriptedAlarms"),
|
||||
Scripts = ReadTopology<Script>(root, "Scripts"),
|
||||
DataConnections = connections,
|
||||
DataExports = exports,
|
||||
RemoteNamespaceMappings = mappings,
|
||||
|
||||
@@ -48,7 +48,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
/// </list>
|
||||
///
|
||||
/// Children (DriverInstance/VirtualTag/etc.) are fully wired: <c>DispatchDeployment</c> drives
|
||||
/// <see cref="PushDesiredSubscriptions"/> which runs the spawn-plan via <see cref="IDriverFactory"/>,
|
||||
/// <see cref="ApplyDesiredSubscriptions"/> which runs the spawn-plan via <see cref="IDriverFactory"/>,
|
||||
/// maintains the <c>FullName→NodeId</c> live-value routing map, and forwards results to the
|
||||
/// OPC UA publish actor via <c>ForwardBatchToMux</c> — one whole driver production burst per message,
|
||||
/// and the ONLY value ingress from driver children (<see cref="DriverInstanceActor"/> wraps even a
|
||||
@@ -184,6 +184,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
private readonly ITelemetryLocalHub? _telemetryHub;
|
||||
|
||||
private readonly CommonsNodeId _localNode;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? _catalogCoordinator;
|
||||
private ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.CatalogAttempt? _catalogAttempt;
|
||||
private readonly IActorRef? _ackRouter;
|
||||
private readonly IDriverFactory _driverFactory;
|
||||
|
||||
@@ -271,7 +274,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <summary>The single VirtualTag-host child that spawns/reconciles Equipment-namespace
|
||||
/// VirtualTagActors and bridges their results onto the OPC UA publish actor. Spawned in
|
||||
/// <see cref="PreStart"/> when an OPC UA publish actor is wired; receives
|
||||
/// <see cref="VirtualTagHostActor.ApplyVirtualTags"/> from <see cref="PushDesiredSubscriptions"/>.</summary>
|
||||
/// <see cref="VirtualTagHostActor.ApplyVirtualTags"/> from <see cref="ApplyDesiredSubscriptions"/>.</summary>
|
||||
private IActorRef? _virtualTagHost;
|
||||
|
||||
/// <summary>The single ScriptedAlarm-host child that owns the per-node
|
||||
@@ -279,7 +282,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// OPC UA publish actor + the cluster <c>alerts</c> topic. Spawned in <see cref="PreStart"/>
|
||||
/// alongside the VirtualTag host (requires both an OPC UA publish actor and a
|
||||
/// <see cref="ScriptRootLogger"/>); receives <see cref="ScriptedAlarmHostActor.ApplyScriptedAlarms"/>
|
||||
/// from <see cref="PushDesiredSubscriptions"/>.</summary>
|
||||
/// from <see cref="ApplyDesiredSubscriptions"/>.</summary>
|
||||
private IActorRef? _scriptedAlarmHost;
|
||||
|
||||
/// <summary>The scripted-alarm plans last sent to <see cref="_scriptedAlarmHost"/>, re-sent when it reports a
|
||||
@@ -330,7 +333,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
/// <summary>
|
||||
/// Driver live-value routing map: <c>(DriverInstanceId, RawPath) → materialised NodeId(s) (realm-tagged)</c>.
|
||||
/// Rebuilt every apply by <see cref="PushDesiredSubscriptions"/> from the composition's <c>RawTags</c>
|
||||
/// Rebuilt every apply by <see cref="ApplyDesiredSubscriptions"/> from the composition's <c>RawTags</c>
|
||||
/// ∪ <c>UnsReferenceVariables</c>, and resolved in <see cref="ForwardBatchToMux"/> so a driver value
|
||||
/// published by wire-ref RawPath fans to its raw node AND every referencing UNS node with identical
|
||||
/// value/quality/timestamp — the single-source-fan-out (no independent buffer, so no drift). A set
|
||||
@@ -342,7 +345,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// Inverse of <see cref="_nodeIdByDriverRef"/>: <c>(Realm, BARE <c>s=</c> id) → (DriverInstanceId,
|
||||
/// RawPath)</c>. v3 Batch 4: keyed by BOTH the raw NodeId (<see cref="AddressSpaceRealm.Raw"/>) AND every
|
||||
/// referencing UNS NodeId (<see cref="AddressSpaceRealm.Uns"/>) — all mapping to the same driver ref
|
||||
/// (the single value source). Rebuilt every apply by <see cref="PushDesiredSubscriptions"/> from the
|
||||
/// (the single value source). Rebuilt every apply by <see cref="ApplyDesiredSubscriptions"/> from the
|
||||
/// composition's <c>RawTags</c> ∪ <c>UnsReferenceVariables</c>, and resolved by
|
||||
/// <see cref="HandleRouteNodeWrite"/> so an inbound operator write to EITHER NodeId is forwarded to the
|
||||
/// owning driver child as a write of its wire-ref RawPath.
|
||||
@@ -405,7 +408,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Condition NodeId → (EquipmentId, tag Name, OPC UA alarm type, HistorizeToAveva) for building
|
||||
/// the AlarmTransitionEvent fan-out. Built in the same PushDesiredSubscriptions alarm branch.
|
||||
/// the AlarmTransitionEvent fan-out. Built in the same ApplyDesiredSubscriptions alarm branch.
|
||||
/// HistorizeToAveva (bool?, null ⇒ historize) is the native per-condition opt-out parsed from
|
||||
/// <c>TagConfig.alarm.historizeToAveva</c>; it is threaded onto the transition so the
|
||||
/// HistorianAdapterActor's <c>is not false</c> gate suppresses the durable AVEVA row only on an
|
||||
@@ -642,6 +645,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
private sealed record ChildEntry(IActorRef Actor, DriverInstanceSpec Spec, bool Stubbed)
|
||||
{
|
||||
public long? SourceIncarnation { get; init; }
|
||||
/// <summary>The driver's synchronous native-ack pre-check, when it offers one (lmxopcua#760).</summary>
|
||||
public IAlarmAcknowledgePreflight? AckPreflight { get; init; }
|
||||
|
||||
@@ -790,7 +794,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
TimeProvider? writeClock = null,
|
||||
IScriptRunner? scriptedAlarmRunner = null,
|
||||
TimeSpan? childShutdownTimeout = null,
|
||||
bool enforceSnapshotOrdering = false) =>
|
||||
bool enforceSnapshotOrdering = false,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = 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
|
||||
@@ -805,7 +811,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
sharesHistorizationScopeWithLocal, applyWedgeTimeout, reprovisionBackoff, commsRecoveryAuditDelay,
|
||||
sharesAlarmQueueWithLocal, applyOutcomeTimeout, captureWhilePrimaryUnreachable, historyUpdateRoleView,
|
||||
scripting, ackPreflightView, writeBounds, writeClock, scriptedAlarmRunner, childShutdownTimeout,
|
||||
enforceSnapshotOrdering));
|
||||
enforceSnapshotOrdering, sourcePublisher, catalogCoordinator));
|
||||
|
||||
/// <summary>Initializes a new DriverHostActor with the specified dependencies.</summary>
|
||||
/// <param name="dbFactory">Database context factory for configuration database access.</param>
|
||||
@@ -941,8 +947,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
TimeProvider? writeClock = null,
|
||||
IScriptRunner? scriptedAlarmRunner = null,
|
||||
TimeSpan? childShutdownTimeout = null,
|
||||
bool enforceSnapshotOrdering = false)
|
||||
bool enforceSnapshotOrdering = false,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
|
||||
{
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_catalogCoordinator = catalogCoordinator;
|
||||
_snapshotOrdering = enforceSnapshotOrdering ? new SnapshotRevisionGate() : null;
|
||||
_childShutdownTimeout = childShutdownTimeout;
|
||||
_scriptedAlarmRunner = scriptedAlarmRunner;
|
||||
@@ -1015,10 +1025,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
Context.System.EventStream.Subscribe(Self, typeof(ReconnectDriver));
|
||||
|
||||
// Spawn the VirtualTag host BEFORE Bootstrap so the bootstrap-restore path (which routes
|
||||
// through PushDesiredSubscriptions and Tells ApplyVirtualTags) has a live host to target.
|
||||
// through ApplyDesiredSubscriptions and Tells ApplyVirtualTags) has a live host to target.
|
||||
SpawnVirtualTagHost();
|
||||
// Same rationale for the ScriptedAlarm host — the bootstrap-restore path Tells it
|
||||
// ApplyScriptedAlarms through the same PushDesiredSubscriptions pass.
|
||||
// ApplyScriptedAlarms through the same ApplyDesiredSubscriptions pass.
|
||||
SpawnScriptedAlarmHost();
|
||||
StartPrimaryVerdictPublishing();
|
||||
StartReachabilityTracking();
|
||||
@@ -1208,14 +1218,14 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
return;
|
||||
}
|
||||
|
||||
if (_opcUaPublishActor is null)
|
||||
if (_opcUaPublishActor is null && _sourcePublisher is null)
|
||||
{
|
||||
_log.Debug("DriverHost {Node}: no OPC UA publish actor wired; skipping VirtualTag host spawn", _localNode);
|
||||
return;
|
||||
}
|
||||
|
||||
_virtualTagHost = Context.ActorOf(
|
||||
VirtualTagHostActor.Props(_opcUaPublishActor, _dependencyMux, _virtualTagEvaluator, _historyWriter, _telemetryHub),
|
||||
VirtualTagHostActor.Props(_opcUaPublishActor, _dependencyMux, _virtualTagEvaluator, _historyWriter, _telemetryHub, _sourcePublisher),
|
||||
"virtual-tag-host");
|
||||
}
|
||||
|
||||
@@ -1572,10 +1582,16 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// it directly. Passing only the deploymentId would drive a ConfigDb read — unreachable here by
|
||||
// definition — and the rebuild would no-op, leaving OPC UA clients browsing an empty server
|
||||
// while the drivers below poll happily. (Found on the docker-dev live gate.)
|
||||
try { PushDesiredSubscriptionsFromArtifact(deploymentId, blob); }
|
||||
catch
|
||||
{
|
||||
if (_catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: false);
|
||||
throw;
|
||||
}
|
||||
_opcUaPublishActor?.Tell(
|
||||
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob));
|
||||
|
||||
PushDesiredSubscriptionsFromArtifact(deploymentId, blob);
|
||||
new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, blob, CatalogAttempt: _catalogAttempt));
|
||||
if (_opcUaPublishActor is null && _catalogAttempt is not null)
|
||||
_catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1778,7 +1794,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// pays at most a doubling or two, which beats over-allocating on every burst that doesn't.
|
||||
writes ??= new List<ValueWrite>(count);
|
||||
foreach (var n in nodeIds)
|
||||
writes.Add(new ValueWrite(n.NodeId, item.Value, item.StatusCode, item.TimestampUtc, n.Realm));
|
||||
writes.Add(new ValueWrite(n.NodeId, item.Value, item.StatusCode, item.TimestampUtc, n.Realm,
|
||||
item.SourceTimestampUtc, item.ServerTimestampUtc));
|
||||
}
|
||||
else if (_log.IsDebugEnabled)
|
||||
{
|
||||
@@ -1856,6 +1873,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// return for exactly that reason.
|
||||
if (!msg.Connected)
|
||||
{
|
||||
if (!_retiredChildren.Contains(Sender) &&
|
||||
(msg.ProducerIncarnation is null || _sourcePublisher?.IsDriverIncarnationActive(msg.DriverInstanceId, msg.ProducerIncarnation.Value) == true))
|
||||
_sourcePublisher?.PublishDriverStatus(msg.DriverInstanceId, OpcUaStatus.BadNoCommunication);
|
||||
FanCommsLossToDependencyMux(msg.DriverInstanceId);
|
||||
// And the EXTERNAL data plane, which the dependency-mux fan-out stopped one seam short of.
|
||||
FanCommsLossToValueNodes(msg.DriverInstanceId);
|
||||
@@ -3028,7 +3048,6 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// until OpcUaPublishActor replies RebuildCompleted (HandleRebuildCompleted) or the outcome
|
||||
// timeout fires (sent degraded, "outcome unknown"). With no publish actor there is no address
|
||||
// space to wait for, so the ack goes out clean immediately — exactly the old behaviour.
|
||||
AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation);
|
||||
// Rebuild the address space + push subscriptions FROM the bytes this apply already has, so
|
||||
// nothing downstream re-reads the artifact: under FetchAndCache OpcUaPublishActor has no
|
||||
// central SQL to read at all, and under Direct a bytes-less RebuildAddressSpace would make
|
||||
@@ -3043,13 +3062,18 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// ReportOutcome: the reply (to Self — this Tell runs inside a receive, so the implicit sender is
|
||||
// this actor) releases the held ack. Plain Tell + reply message, no Ask/await, so nothing here
|
||||
// resumes off the actor thread.
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
|
||||
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true));
|
||||
// SubscribeBulk pass: hand each driver its desired tag references so live values flow into
|
||||
// the just-rebuilt address space instead of staying BadWaitingForInitialData.
|
||||
PushDesiredSubscriptionsFromParsed(msg.DeploymentId, parsed);
|
||||
// Cache the applied bytes as this node's last-known-good (idempotent store; skips empty).
|
||||
CacheAppliedArtifact(msg.DeploymentId, msg.Revision, appliedBlob, parsed);
|
||||
var catalogFailed = _opcUaPublishActor is null && _catalogAttempt is not null
|
||||
&& _catalogCoordinator is not null
|
||||
&& !_catalogCoordinator.Complete(_catalogAttempt, topologySucceeded: true)
|
||||
&& _catalogAttempt.Expected;
|
||||
AwaitAddressSpaceOutcomeThenAck(msg.DeploymentId, msg.Revision, msg.Correlation, catalogFailed);
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(
|
||||
msg.Correlation, msg.DeploymentId, appliedBlob, ReportOutcome: true, CatalogAttempt: _catalogAttempt));
|
||||
// Reaching here means the artifact came from central, so the node is no longer serving a
|
||||
// cache-sourced configuration. Note this only clears on a real apply: a dispatch of the
|
||||
// revision already booted from cache short-circuits in HandleDispatchFromSteady without
|
||||
@@ -3064,6 +3088,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: false);
|
||||
// A throw after the Applied ack was put on hold — the Failed ack below is this apply's one
|
||||
// answer, so the held Applied must never follow it when the address-space outcome lands.
|
||||
DropPendingAck(msg.Correlation);
|
||||
@@ -3101,13 +3126,13 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// With no publish actor wired (tests, a node with no OPC UA data plane) there is no outcome to wait
|
||||
/// for, so the ack is sent clean at once — byte-for-byte the earlier behaviour.
|
||||
/// </summary>
|
||||
private void AwaitAddressSpaceOutcomeThenAck(DeploymentId deploymentId, RevisionHash revision, CorrelationId correlation)
|
||||
private void AwaitAddressSpaceOutcomeThenAck(DeploymentId deploymentId, RevisionHash revision, CorrelationId correlation,
|
||||
bool catalogFailed = false)
|
||||
{
|
||||
if (_opcUaPublishActor is null)
|
||||
{
|
||||
_currentRevisionUnconfirmed = false;
|
||||
UpsertNodeDeploymentState(deploymentId, NodeDeploymentStatus.Applied, failureReason: null);
|
||||
SendAck(deploymentId, ApplyAckOutcome.Applied, failureReason: null, correlation);
|
||||
ReleasePendingAck(new PendingAck(deploymentId, revision, correlation), catalogFailed,
|
||||
catalogFailed ? "the expected local data catalog could not be activated" : null);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3262,7 +3287,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
private byte[]? ReconcileDrivers(DeploymentId deploymentId)
|
||||
{
|
||||
var blob = LoadArtifactBlob(deploymentId);
|
||||
return blob is null ? null : ReconcileDriversFromBlob(deploymentId, blob);
|
||||
return ReconcileDriversFromBlob(deploymentId, blob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -3362,6 +3387,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// children left running — the honest reading of bytes that cannot be understood.</exception>
|
||||
private ReconciledArtifact ReconcileDriversFromParsed(DeploymentId deploymentId, byte[]? blob)
|
||||
{
|
||||
BeginCatalogAttempt(blob);
|
||||
blob ??= Array.Empty<byte>();
|
||||
if (blob.Length == 0)
|
||||
{
|
||||
@@ -3376,6 +3402,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
var parsed = DeploymentArtifact.Open(blob);
|
||||
try
|
||||
{
|
||||
StageCatalog(parsed);
|
||||
ApplyDriverSpecs(parsed.ParseDriverInstances(_localNode.Value));
|
||||
}
|
||||
catch
|
||||
@@ -3396,6 +3423,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <returns>The reconciled blob, or <see langword="null"/> when it was empty.</returns>
|
||||
private byte[]? ReconcileDriversFromBlob(DeploymentId deploymentId, byte[]? blob)
|
||||
{
|
||||
BeginCatalogAttempt(blob);
|
||||
blob ??= Array.Empty<byte>();
|
||||
if (blob.Length == 0)
|
||||
{
|
||||
@@ -3411,6 +3439,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
try
|
||||
{
|
||||
using var parsed = DeploymentArtifact.Open(blob);
|
||||
StageCatalog(parsed);
|
||||
specs = parsed.ParseDriverInstances(_localNode.Value);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
@@ -3425,6 +3454,44 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
return blob;
|
||||
}
|
||||
|
||||
private void BeginCatalogAttempt(byte[]? blob)
|
||||
{
|
||||
if (_catalogCoordinator is null) return;
|
||||
var revision = blob is { Length: > 0 }
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(blob)) : "unavailable";
|
||||
_catalogAttempt = _catalogCoordinator.BeginAttempt(revision);
|
||||
}
|
||||
|
||||
private void StageCatalog(ParsedDeploymentArtifact parsed)
|
||||
{
|
||||
if (_catalogCoordinator is null || _catalogAttempt is null) return;
|
||||
_catalogAttempt.SetExpected(parsed.ExpectsLocalDataCatalog());
|
||||
try
|
||||
{
|
||||
var authority = parsed.ParseDataPlaneAuthority(_localNode.Value);
|
||||
if (!_catalogCoordinator.InstallAuthority(_catalogAttempt, authority)) return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "DriverHost {Node}: failed to install desired data authority; catalog remains closed", _localNode);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!string.Equals(_catalogCoordinator.Serving.NodeId, _localNode.Value, StringComparison.Ordinal))
|
||||
{
|
||||
_log.Error("DriverHost {Node}: data catalog serving identity names another node", _localNode);
|
||||
return;
|
||||
}
|
||||
var snapshot = parsed.ParseLocalCatalogSnapshot(_localNode.Value);
|
||||
if (snapshot is not null) _catalogCoordinator.Stage(_catalogAttempt, snapshot, _localNode.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "DriverHost {Node}: failed to stage desired data catalog; catalog remains closed", _localNode);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// No bytes is no answer, not "a configuration with no drivers". Parsing zero bytes
|
||||
/// yields zero specs, and <c>DriverSpawnPlanner</c> then plans EVERY running child for StopChild: a
|
||||
@@ -3449,7 +3516,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
var plan = DriverSpawnPlanner.Compute(snapshots, specs);
|
||||
|
||||
foreach (var id in plan.ToStop) StopChild(id);
|
||||
foreach (var spec in plan.ToSpawn) SpawnChild(spec);
|
||||
foreach (var spec in plan.ToSpawn) SpawnChild(spec, deferSubscriptions: _sourcePublisher is not null);
|
||||
|
||||
// v3: a dependency-consumer driver's declared dependency refs change when its tags/scripts are
|
||||
// edited. That edit changes its DriverConfig, which respawns it, and the respawned driver's
|
||||
@@ -3606,10 +3673,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// No re-ack: the deployment is already Applied.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Its two ConfigDb reads (<see cref="ReconcileDrivers"/> and
|
||||
/// <see cref="PushDesiredSubscriptions"/>) stay SYNCHRONOUS deliberately: this runs in
|
||||
/// <see cref="PreStart"/>, before the host has processed a single message, so there is no live
|
||||
/// traffic behind them to block — unlike the apply path, which moved its read off the mailbox.
|
||||
/// The artifact read in <see cref="ReconcileDrivers"/> stays synchronous because this runs in
|
||||
/// <see cref="PreStart"/>, before the host has processed a single message. The same bytes drive
|
||||
/// reconciliation, subscriptions and the address-space rebuild.
|
||||
/// </remarks>
|
||||
private void RestoreApplied(DeploymentId deploymentId, RevisionHash? revision)
|
||||
{
|
||||
@@ -3621,8 +3687,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// were NOT restored: the adopted revision is unconfirmed (fourth review M2), and a re-dispatch of it
|
||||
// re-applies instead of short-circuiting a clean Applied.
|
||||
if (appliedBlob is null) _currentRevisionUnconfirmed = true;
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob));
|
||||
PushDesiredSubscriptions(deploymentId);
|
||||
if (appliedBlob is not null)
|
||||
PushDesiredSubscriptionsFromArtifact(deploymentId, appliedBlob);
|
||||
if (_opcUaPublishActor is null && _catalogAttempt is not null)
|
||||
{
|
||||
var complete = _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: appliedBlob is not null) ?? false;
|
||||
if (!complete && _catalogAttempt.Expected) _currentRevisionUnconfirmed = true;
|
||||
}
|
||||
else if (_catalogAttempt?.Expected == true)
|
||||
_currentRevisionUnconfirmed = true;
|
||||
// Populate the node-local cache from the artifact this restored node is now serving. The
|
||||
// cache invariant is "holds what the node currently serves"; without this only a FRESH
|
||||
// apply (BeginDirectApply) ever wrote it, so a node whose cache was lost — a wiped/fresh volume,
|
||||
@@ -3633,10 +3706,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// it. (Found on the docker-dev live gate.)
|
||||
if (revision is { } rev)
|
||||
CacheAppliedArtifact(deploymentId, rev, appliedBlob);
|
||||
_opcUaPublishActor?.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.RebuildAddressSpace(correlation, deploymentId, appliedBlob, CatalogAttempt: _catalogAttempt));
|
||||
_log.Info("DriverHost {Node}: restored served state for applied deployment {Id} on bootstrap", _localNode, deploymentId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (_catalogAttempt is not null) _catalogCoordinator?.Complete(_catalogAttempt, topologySucceeded: false);
|
||||
// The revision was adopted from the row but its served state was NOT restored (fourth review M2): mark it
|
||||
// unconfirmed so a re-dispatch of it re-applies instead of short-circuiting a clean Applied.
|
||||
_currentRevisionUnconfirmed = true;
|
||||
@@ -3644,66 +3719,12 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SubscribeBulk pass. After an apply, read the deployment's Equipment-namespace tags,
|
||||
/// group their driver-side FullName references by driver instance, and hand each running driver
|
||||
/// child its desired subscription set via <see cref="DriverInstanceActor.SetDesiredSubscriptions"/>.
|
||||
/// The child retains the set and (re)subscribes on every Connected entry, so values stream into
|
||||
/// the OPC UA sink and resume after reconnects. Drivers with no configured tags get an empty set
|
||||
/// (which clears any stale subscription from a previous deployment).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The <b>bootstrap-restore</b> entry point only. Neither apply path reaches it any more:
|
||||
/// <see cref="HandleArtifactForApply"/> already holds the apply's single parse and calls
|
||||
/// <see cref="PushDesiredSubscriptionsFromParsed"/> directly, so this ConfigDb read exists for
|
||||
/// <see cref="RestoreApplied"/>, which restores from a deployment id recovered out of
|
||||
/// NodeDeploymentState and may hold no blob of its own.
|
||||
/// </remarks>
|
||||
private void PushDesiredSubscriptions(DeploymentId deploymentId)
|
||||
{
|
||||
// Phase 4 belt-and-suspenders: a ConfigDb read, so it can only be the restore path on a node that
|
||||
// has one (every apply path calls PushDesiredSubscriptionsFromParsed with its parse in hand).
|
||||
// No ConfigDb ⇒ nothing to load.
|
||||
if (_dbFactory is null)
|
||||
{
|
||||
_log.Warning("DriverHost {Node}: no ConfigDb to load artifact for SubscribeBulk ({Id}); skipping", _localNode, deploymentId);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] blob;
|
||||
try
|
||||
{
|
||||
// Synchronous by design: the only caller is the PreStart restore path above, where nothing
|
||||
// is queued behind this read (the apply path reads off the mailbox instead).
|
||||
using var db = _dbFactory.CreateDbContext();
|
||||
blob = db.Deployments.AsNoTracking()
|
||||
.Where(d => d.DeploymentId == deploymentId.Value)
|
||||
.Select(d => d.ArtifactBlob)
|
||||
.FirstOrDefault() ?? Array.Empty<byte>();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warning(ex, "DriverHost {Node}: failed to load artifact for SubscribeBulk ({Id})", _localNode, deploymentId);
|
||||
return;
|
||||
}
|
||||
|
||||
PushDesiredSubscriptionsFromArtifact(deploymentId, blob);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The artifact-processing half of <see cref="PushDesiredSubscriptions"/>, split out so the
|
||||
/// boot-from-cache path can drive it with bytes already in hand.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Separated because the cache path runs precisely when the ConfigDb read above cannot
|
||||
/// succeed — re-reading the artifact there would fail by definition.
|
||||
/// </remarks>
|
||||
/// <summary>Apply subscriptions from the artifact bytes already loaded for cache boot or restore.</summary>
|
||||
private void PushDesiredSubscriptionsFromArtifact(DeploymentId deploymentId, byte[] blob)
|
||||
{
|
||||
// The same "no bytes is no answer" rule as ReconcileDrivers. An empty artifact parses
|
||||
// to a composition with no raw tags, which hands every child an EMPTY desired set — and an empty set
|
||||
// drops the live subscription handle rather than re-subscribing. Reachable independently of the
|
||||
// reconcile guard: this method does its OWN ConfigDb read, so the row can go missing between the two.
|
||||
// drops the live subscription handle rather than re-subscribing.
|
||||
if (blob.Length == 0)
|
||||
{
|
||||
_log.Warning(
|
||||
@@ -3777,6 +3798,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
/// <param name="composition">The composition this node should serve.</param>
|
||||
private void ApplyDesiredSubscriptions(AddressSpaceComposition composition)
|
||||
{
|
||||
_catalogCoordinator?.BeforeSubscriptionApplyForTests?.Invoke();
|
||||
// v3 Batch 4: the driver subscribes + publishes by RawPath (the wire-ref == RawPath == RawTagPlan.NodeId
|
||||
// per the v3 identity contract). Value-subscription set = the non-alarm raw tags' RawPaths; alarm-bearing
|
||||
// raw tags are Part 9 conditions, fed via the native alarm event stream (ForwardNativeAlarm), so they are
|
||||
@@ -3817,6 +3839,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
// Rebuild the driver live-value + write routing maps from the RawTags ∪ UnsReferenceVariables pass.
|
||||
// Clear-and-repopulate every apply so renames/removals/re-points are reflected.
|
||||
var previousSourceRefs = _sourcePublisher is null ? null : _nodeIdByDriverRef.Keys.ToArray();
|
||||
_nodeIdByDriverRef.Clear();
|
||||
_driverRefByNodeId.Clear();
|
||||
_alarmNodeIdByDriverRef.Clear();
|
||||
@@ -3856,6 +3879,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
// Value tag: register the RAW NodeId (Raw realm) AND every referencing UNS NodeId (Uns realm)
|
||||
// against the SAME driver ref — the single value source fans to all of them.
|
||||
_sourcePublisher?.RegisterDriverShape(t.DriverInstanceId, t.NodeId,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceValueShape.FromDriverType(t.DataType, t.IsArray));
|
||||
if (!_nodeIdByDriverRef.TryGetValue(key, out var set))
|
||||
{
|
||||
_nodeIdByDriverRef[key] = set = new HashSet<NodeRealmRef>();
|
||||
@@ -3877,6 +3902,15 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
}
|
||||
}
|
||||
|
||||
if (previousSourceRefs is not null)
|
||||
foreach (var previous in previousSourceRefs)
|
||||
if (!_nodeIdByDriverRef.ContainsKey(previous))
|
||||
{
|
||||
if (_sourcePublisher!.TryCaptureDriver(previous.DriverInstanceId, previous.RawPath, out var ticket))
|
||||
_sourcePublisher.TryRemove(ticket);
|
||||
_sourcePublisher.ForgetDriverShape(previous.DriverInstanceId, previous.RawPath);
|
||||
}
|
||||
|
||||
// Forget the projected prior state of conditions this composition no longer carries, and keep
|
||||
// the rest. Clearing it whole on every apply made the next driver Acknowledge of a still-active alarm
|
||||
// project Active=false (the default prior), and the next Clear of an unacknowledged one project
|
||||
@@ -3916,7 +3950,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// VirtualTagActor per plan and streams their evaluated values back onto the just-rebuilt
|
||||
// address space. Runs on BOTH the fresh-apply path (HandleArtifactForApply) and the bootstrap-restore
|
||||
// path (RestoreApplied) because both call this method, so one send covers both.
|
||||
// NOTE: the Stale-recovery path (TryRecoverFromStale) does NOT call PushDesiredSubscriptions,
|
||||
// NOTE: the Stale-recovery path (TryRecoverFromStale) does NOT apply desired subscriptions,
|
||||
// so — like drivers — VirtualTags remain empty after a Stale recovery until the next
|
||||
// deployment dispatch. This is intentional and consistent with driver recovery: the Stale
|
||||
// path only restores the revision marker + NodeDeploymentState; a subsequent dispatch
|
||||
@@ -3969,7 +4003,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
return set.ValueRefs.Count;
|
||||
}
|
||||
|
||||
private void SpawnChild(DriverInstanceSpec spec)
|
||||
private void SpawnChild(DriverInstanceSpec spec, bool deferSubscriptions = false)
|
||||
{
|
||||
// An instance id removed by an earlier deployment (StopChild ⇒ Evict, which also holds back late
|
||||
// items) may come back; lift the hold BEFORE the child exists, since it publishes health as it starts.
|
||||
@@ -4014,6 +4048,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// ("actor name is not unique"). Children are tracked by the _children dict (by IActorRef), never
|
||||
// by path, so the suffix is invisible to every caller.
|
||||
var actorName = ActorNameFor(spec.DriverInstanceId, _childSpawnGeneration++);
|
||||
var sourceIncarnation = _sourcePublisher?.RegisterDriverIncarnation(spec.DriverInstanceId);
|
||||
if (stub)
|
||||
{
|
||||
child = Context.ActorOf(
|
||||
@@ -4022,7 +4057,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
reconnectInterval: null,
|
||||
startStubbed: true,
|
||||
healthPublisher: _healthPublisher,
|
||||
clusterId: clusterId),
|
||||
clusterId: clusterId, sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
|
||||
actorName);
|
||||
}
|
||||
else
|
||||
@@ -4040,7 +4075,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
invoker: invoker,
|
||||
writeTimeout: _writeBounds.Timeout,
|
||||
writeClock: _writeClock,
|
||||
shutdownTimeout: _childShutdownTimeout),
|
||||
shutdownTimeout: _childShutdownTimeout,
|
||||
sourcePublisher: _sourcePublisher, sourceIncarnation: sourceIncarnation),
|
||||
actorName);
|
||||
child.Tell(new DriverInstanceActor.InitializeRequested(spec.DriverConfig));
|
||||
}
|
||||
@@ -4048,6 +4084,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
_children[spec.DriverInstanceId] = new ChildEntry(child, spec, stub)
|
||||
{
|
||||
AckPreflight = stub ? null : driver as IAlarmAcknowledgePreflight,
|
||||
SourceIncarnation = sourceIncarnation,
|
||||
};
|
||||
PublishAckPreflight();
|
||||
|
||||
@@ -4072,7 +4109,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
// Deliberately not "fixed" by withholding the send: a child that never gets a set is the 03/S16
|
||||
// defect, and the operator-Restart and supervision paths have no bulk push coming at all.
|
||||
// Sent after InitializeRequested above, which keeps init-before-subscribe ordering.
|
||||
SendDesiredSubscriptions(child, spec.DriverInstanceId);
|
||||
if (!deferSubscriptions) SendDesiredSubscriptions(child, spec.DriverInstanceId);
|
||||
|
||||
// v3: if the (real, non-stub) driver consumes other tags' live values, spawn a mux-adapter
|
||||
// child that registers its dependency refs on the per-node dependency mux and forwards changes
|
||||
@@ -4104,6 +4141,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
{
|
||||
if (!_children.TryGetValue(driverInstanceId, out var entry)) return;
|
||||
StopDependencyAdapter(driverInstanceId);
|
||||
_sourcePublisher?.RetireCurrentDriver(driverInstanceId);
|
||||
RetireChild(entry.Actor);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(driverInstanceId);
|
||||
@@ -4222,6 +4260,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
|
||||
// Stop the existing child actor — DriverInstanceActor.PostStop calls ShutdownAsync.
|
||||
StopDependencyAdapter(msg.DriverInstanceId);
|
||||
_sourcePublisher?.RetireCurrentDriver(msg.DriverInstanceId);
|
||||
RetireChild(entry.Actor);
|
||||
Context.Stop(entry.Actor);
|
||||
_children.Remove(msg.DriverInstanceId);
|
||||
@@ -4362,7 +4401,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
|
||||
{
|
||||
_currentRevision = RevisionHash.Parse(latestSealed.RevisionHash);
|
||||
// Adopted, NOT applied (fourth review M2): Stale recovery restores only the revision marker — drivers
|
||||
// and the address space stay empty until a dispatch (see PushDesiredSubscriptions' note). Unconfirmed,
|
||||
// and the address space stay empty until a dispatch (see the stale-recovery note). Unconfirmed,
|
||||
// so a dispatch of this same revision re-applies rather than short-circuiting a clean Applied over an
|
||||
// empty address space.
|
||||
_currentRevisionUnconfirmed = true;
|
||||
|
||||
@@ -42,7 +42,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// annotates this driver's native alarm conditions' source-data Quality from it (comms lost → Bad,
|
||||
/// restored → Good) — independently of alarm transitions, since a comms-lost driver emits no alarm
|
||||
/// events. Fire-and-forget.</summary>
|
||||
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected);
|
||||
public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null);
|
||||
|
||||
/// <summary>
|
||||
/// Sent to the parent from <see cref="PostRestart"/> so the host re-provisions THIS incarnation.
|
||||
@@ -142,16 +142,19 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <para>A struct deliberately: an <c>AttributeValueItem[]</c> then holds its items inline, so a burst of
|
||||
/// N values costs one array allocation instead of one array plus N boxes. Indexed access through
|
||||
/// <see cref="IReadOnlyList{T}"/> does not box.</para></summary>
|
||||
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc);
|
||||
public readonly record struct AttributeValueItem(string FullReference, object? Value, uint StatusCode, DateTime TimestampUtc,
|
||||
DateTime? SourceTimestampUtc = null, DateTime? ServerTimestampUtc = null);
|
||||
/// <summary>The ONLY value message a driver child sends: every changed attribute of ONE driver production
|
||||
/// burst in one message (a single data change is a one-item batch). The parent fans the whole batch to the mux and the OPC UA
|
||||
/// publish path in one hop each. Status codes ride verbatim.</summary>
|
||||
public sealed record AttributeValueBatchPublished(string DriverInstanceId, IReadOnlyList<AttributeValueItem> Items);
|
||||
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot);
|
||||
private sealed record DataChangeForward(string FullReference, DataValueSnapshot Snapshot, long? ProducerIncarnation);
|
||||
/// <summary>Self-sent when a batch-capable driver (<see cref="IBatchSubscribable"/>) raises
|
||||
/// <see cref="IBatchSubscribable.OnDataChangeBatch"/> — marshals the whole burst off the driver's
|
||||
/// thread onto the actor thread in one hop. Parallels <see cref="DataChangeForward"/>.</summary>
|
||||
private sealed record DataChangeBatchForward(IReadOnlyList<DataChangeItem> Items);
|
||||
private sealed record DataChangeBatchForward(IReadOnlyList<DataChangeItem> Items, long? ProducerIncarnation);
|
||||
private sealed record RetrySourceBindings(IReadOnlyList<string> References, int Offset, bool Failed,
|
||||
int Attempt, long Version, long ProducerIncarnation);
|
||||
/// <summary>Published to the parent whenever the subscribed driver (an <see cref="IAlarmSource"/>) fires
|
||||
/// <see cref="IAlarmSource.OnAlarmEvent"/>. The parent (<see cref="DriverHostActor"/>) projects + routes it
|
||||
/// to the materialised Part 9 condition. Parallels <see cref="AttributeValueBatchPublished"/>.</summary>
|
||||
@@ -389,6 +392,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <summary>The batch data-change handler, attached INSTEAD of <see cref="_dataChangeHandler"/> when the
|
||||
/// driver is an <see cref="IBatchSubscribable"/>. Exactly one of the two is ever non-null.</summary>
|
||||
private EventHandler<DataChangeBatchEventArgs>? _batchChangeHandler;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private long? _sourceIncarnation;
|
||||
private long _sourceBindingVersion;
|
||||
private const int SourceBindingBatchSize = 128;
|
||||
private EventHandler<AlarmEventArgs>? _alarmEventHandler;
|
||||
private EventHandler<RediscoveryEventArgs>? _rediscoveryHandler;
|
||||
private EventHandler<HostStatusChangedEventArgs>? _hostStatusHandler;
|
||||
@@ -491,7 +498,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
TimeSpan? queuedWriteBudget = null,
|
||||
TimeSpan? initializeTimeout = null,
|
||||
TimeSpan? writeTimeout = null,
|
||||
TimeProvider? writeClock = null) =>
|
||||
TimeProvider? writeClock = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null) =>
|
||||
Akka.Actor.Props.Create(() => new DriverInstanceActor(
|
||||
driver,
|
||||
reconnectInterval ?? DefaultReconnectInterval,
|
||||
@@ -506,7 +515,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
queuedWriteBudget,
|
||||
initializeTimeout,
|
||||
writeTimeout,
|
||||
writeClock));
|
||||
writeClock, sourcePublisher, sourceIncarnation));
|
||||
|
||||
/// <summary>
|
||||
/// Returns true when the driver should boot in DEV-STUB mode based on host platform and
|
||||
@@ -568,8 +577,12 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
TimeSpan? queuedWriteBudget = null,
|
||||
TimeSpan? initializeTimeout = null,
|
||||
TimeSpan? writeTimeout = null,
|
||||
TimeProvider? writeClock = null)
|
||||
TimeProvider? writeClock = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null)
|
||||
{
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_sourceIncarnation = sourceIncarnation;
|
||||
_writeTimeout = writeTimeout is { } wt && wt > TimeSpan.Zero ? wt : DefaultWriteTimeout;
|
||||
_writeClock = writeClock ?? TimeProvider.System;
|
||||
_incarnation = Interlocked.Increment(ref s_initGenerationSource);
|
||||
@@ -605,6 +618,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <inheritdoc />
|
||||
protected override void PreStart()
|
||||
{
|
||||
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
|
||||
!_sourcePublisher.IsDriverIncarnationActive(_driverInstanceId, previous))
|
||||
_sourceIncarnation = _sourcePublisher.RegisterDriverIncarnation(_driverInstanceId);
|
||||
// Warm up the snapshot store immediately so AdminUI sees current state as soon as the
|
||||
// actor starts, before any state transition fires. Also start the periodic heartbeat so
|
||||
// long-lived Healthy drivers keep their snapshot fresh for newly-joined SignalR clients.
|
||||
@@ -725,7 +741,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// Announce connectivity to the host so it can clear any comms-lost Quality annotation on this
|
||||
// driver's native alarm conditions (Bad → Good). Fire-and-forget; the host defaults conditions to a
|
||||
// non-Good "waiting for initial data" quality at materialise, and this is what confirms them Good.
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true));
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation));
|
||||
|
||||
// Baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that
|
||||
// reconnects but never manages a read is measured from THIS connect, not from a stale earlier one.
|
||||
@@ -750,9 +766,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
Receive<WriteCompleted>(OnWriteCompleted);
|
||||
ReceiveAsync<RouteAlarmAck>(HandleAcknowledgeAsync);
|
||||
ReceiveAsync<Subscribe>(HandleSubscribeAsync);
|
||||
ReceiveAsync<Unsubscribe>(_ => UnsubscribeAsync());
|
||||
ReceiveAsync<Unsubscribe>(_ => { CancelSourceBindingRetry(); return UnsubscribeAsync(); });
|
||||
Receive<RetrySourceBindings>(RetrySourceBindingBatch);
|
||||
Receive<SetDesiredSubscriptions>(msg =>
|
||||
{
|
||||
CancelSourceBindingRetry();
|
||||
StoreDesiredSubscriptions(msg);
|
||||
if (_desiredRefs.Count > 0) Self.Tell(new Subscribe(_desiredRefs, _desiredInterval));
|
||||
else if (_subscriptionHandle is not null) Self.Tell(new Unsubscribe());
|
||||
@@ -967,7 +985,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
{
|
||||
// Announce comms loss to the host so it annotates this driver's native alarm conditions Bad
|
||||
// (a comms-lost driver emits no alarm events, so this is the ONLY signal that the source is unreachable).
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false));
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false, ProducerIncarnation: _sourceIncarnation));
|
||||
|
||||
// Tear the dead transport down before re-initialising, or every retry leaks one.
|
||||
Receive<RetryConnect>(_ => InitializeAsync(_currentConfigJson ?? "{}", teardownFirst: true));
|
||||
@@ -1467,6 +1485,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// in this handler so continuations resume on the actor context.
|
||||
var replyTo = Sender;
|
||||
var self = Self;
|
||||
CancelSourceBindingRetry();
|
||||
var sourceBindingVersion = _sourceBindingVersion;
|
||||
if (_driver is not ISubscribable subscribable)
|
||||
{
|
||||
replyTo.Tell(new SubscriptionFailed("Driver does not implement ISubscribable"));
|
||||
@@ -1480,6 +1500,14 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
|
||||
try
|
||||
{
|
||||
var sourceBindingNeedsRetry = false;
|
||||
if (_sourcePublisher is not null && _sourceIncarnation is { } incarnation)
|
||||
{
|
||||
var count = Math.Min(msg.FullReferences.Count, SourceBindingBatchSize);
|
||||
for (var i = 0; i < count; i++)
|
||||
sourceBindingNeedsRetry |= !TryEnsureSourceBinding(msg.FullReferences[i], incarnation);
|
||||
sourceBindingNeedsRetry |= count < msg.FullReferences.Count;
|
||||
}
|
||||
// EXACTLY ONE of the two data-change events is subscribed. An IBatchSubscribable driver raises
|
||||
// OnDataChangeBatch once per production burst AND the per-tag OnDataChange for every item in
|
||||
// that same burst (the per-tag event is kept for legacy consumers — Galaxy cold reads, driver
|
||||
@@ -1492,13 +1520,30 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// A null/empty raise from a buggy driver must never enter the mailbox: an unguarded null
|
||||
// would throw in the handler, restart the actor, and tear down the driver transport.
|
||||
if (args?.Items is not { Count: > 0 }) return;
|
||||
self.Tell(new DataChangeBatchForward(args.Items));
|
||||
var owned = new DataChangeItem[args.Items.Count];
|
||||
for (var i = 0; i < owned.Length; i++)
|
||||
{
|
||||
var item = args.Items[i];
|
||||
if (item is null) { owned[i] = null!; continue; }
|
||||
PublishSource(item.FullReference, item.Snapshot);
|
||||
owned[i] = new DataChangeItem(item.FullReference, CopyLegacySnapshot(item.Snapshot));
|
||||
}
|
||||
self.Tell(new DataChangeBatchForward(owned, _sourceIncarnation));
|
||||
};
|
||||
batchable.OnDataChangeBatch += _batchChangeHandler;
|
||||
}
|
||||
else
|
||||
{
|
||||
_dataChangeHandler = (_, args) => self.Tell(new DataChangeForward(args.FullReference, args.Snapshot));
|
||||
_dataChangeHandler = (_, args) =>
|
||||
{
|
||||
if (args is null)
|
||||
{
|
||||
self.Tell(new DataChangeForward(string.Empty, null!, _sourceIncarnation));
|
||||
return;
|
||||
}
|
||||
PublishSource(args.FullReference, args.Snapshot);
|
||||
self.Tell(new DataChangeForward(args.FullReference, CopyLegacySnapshot(args.Snapshot), _sourceIncarnation));
|
||||
};
|
||||
subscribable.OnDataChange += _dataChangeHandler;
|
||||
}
|
||||
|
||||
@@ -1511,6 +1556,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
async ct => await subscribable.SubscribeAsync(msg.FullReferences, msg.PublishingInterval, ct),
|
||||
cts.Token);
|
||||
|
||||
if (sourceBindingNeedsRetry && _sourceIncarnation is { } retryIncarnation)
|
||||
Timers.StartSingleTimer("source-binding-retry", new RetrySourceBindings(msg.FullReferences,
|
||||
0, false, 0, sourceBindingVersion, retryIncarnation), TimeSpan.FromMilliseconds(250));
|
||||
|
||||
replyTo.Tell(new SubscriptionEstablished(_subscriptionHandle.DiagnosticId, msg.FullReferences.Count));
|
||||
_log.Info("DriverInstance {Id}: subscribed to {Count} refs ({Diag})",
|
||||
_driverInstanceId, msg.FullReferences.Count, _subscriptionHandle.DiagnosticId);
|
||||
@@ -1523,6 +1572,44 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
}
|
||||
|
||||
private void CancelSourceBindingRetry()
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
_sourceBindingVersion++;
|
||||
}
|
||||
|
||||
private bool TryEnsureSourceBinding(string reference, long incarnation)
|
||||
{
|
||||
try { return _sourcePublisher?.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, incarnation) == true; }
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warning(ex, "DriverInstance {Id}: source binding unavailable; legacy subscription remains active", _driverInstanceId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RetrySourceBindingBatch(RetrySourceBindings retry)
|
||||
{
|
||||
if (retry.Version != _sourceBindingVersion || _sourceIncarnation != retry.ProducerIncarnation || _subscriptionHandle is null)
|
||||
return;
|
||||
var end = Math.Min(retry.References.Count, retry.Offset + SourceBindingBatchSize);
|
||||
var failed = retry.Failed;
|
||||
for (var i = retry.Offset; i < end; i++)
|
||||
failed |= !TryEnsureSourceBinding(retry.References[i], retry.ProducerIncarnation);
|
||||
if (end < retry.References.Count)
|
||||
{
|
||||
Timers.StartSingleTimer("source-binding-retry", retry with { Offset = end, Failed = failed }, TimeSpan.FromMilliseconds(1));
|
||||
return;
|
||||
}
|
||||
if (failed)
|
||||
{
|
||||
var attempt = Math.Min(retry.Attempt + 1, 7);
|
||||
var delayMs = Math.Min(30_000, 250 * (1 << attempt));
|
||||
Timers.StartSingleTimer("source-binding-retry", retry with { Offset = 0, Failed = false, Attempt = attempt },
|
||||
TimeSpan.FromMilliseconds(delayMs));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UnsubscribeAsync()
|
||||
{
|
||||
if (_driver is not ISubscribable subscribable || _subscriptionHandle is null)
|
||||
@@ -1557,6 +1644,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// instead.</para></summary>
|
||||
private void DetachSubscription()
|
||||
{
|
||||
CancelSourceBindingRetry();
|
||||
DetachDataSubscription();
|
||||
DetachAlarmSource();
|
||||
}
|
||||
@@ -1895,12 +1983,44 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// 3-state Good/Uncertain/Bad enum here, which the node manager then re-expanded to a bare
|
||||
/// <c>0x80000000</c> — so no driver's sub-code ever reached a client, and the status constants each
|
||||
/// driver maintains were diagnostic in logs only.</para></summary>
|
||||
private void PublishSource(string reference, DataValueSnapshot? snapshot)
|
||||
{
|
||||
if (_sourcePublisher is null) return;
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceTicket ticket = default;
|
||||
var found = false;
|
||||
try
|
||||
{
|
||||
found = _sourceIncarnation is { } incarnation
|
||||
? _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, incarnation, out ticket)
|
||||
: _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, out ticket);
|
||||
if (!found && snapshot is not null && _sourceIncarnation is { } current &&
|
||||
_sourcePublisher.EnsureDriverBinding(_clusterId, _driverInstanceId, reference, current))
|
||||
found = _sourcePublisher.TryCaptureDriver(_driverInstanceId, reference, current, out ticket);
|
||||
if (!found) return;
|
||||
if (snapshot is null) _sourcePublisher.Invalidate(ticket, "malformed driver callback");
|
||||
else _sourcePublisher.TryPublish(ticket, snapshot);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (found) _sourcePublisher.Invalidate(ticket, "source callback failed");
|
||||
_log.Warning(ex, "DriverInstance {Id}: source callback unavailable; legacy publication continues", _driverInstanceId);
|
||||
}
|
||||
}
|
||||
|
||||
// A malformed snapshot still crosses the mailbox in an incarnation-tagged envelope. The actor's
|
||||
// existing supervision path handles it; the producer's callback thread must never throw for it.
|
||||
private static DataValueSnapshot CopyLegacySnapshot(DataValueSnapshot? snapshot) => snapshot is null
|
||||
? null!
|
||||
: snapshot with { Value = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.CopyLegacy(snapshot.Value) };
|
||||
|
||||
private void OnDataChangeForward(DataChangeForward msg)
|
||||
{
|
||||
var ts = msg.Snapshot.SourceTimestampUtc ?? msg.Snapshot.ServerTimestampUtc;
|
||||
if (msg.ProducerIncarnation != _sourceIncarnation) return;
|
||||
var ts = msg.Snapshot.SourceTimestampUtc ?? msg.Snapshot.ServerTimestampUtc ?? DateTime.MinValue;
|
||||
Context.Parent.Tell(new AttributeValueBatchPublished(
|
||||
_driverInstanceId,
|
||||
new[] { new AttributeValueItem(msg.FullReference, msg.Snapshot.Value, msg.Snapshot.StatusCode, ts) }));
|
||||
new[] { new AttributeValueItem(msg.FullReference, msg.Snapshot.Value, msg.Snapshot.StatusCode, ts,
|
||||
msg.Snapshot.SourceTimestampUtc, msg.Snapshot.ServerTimestampUtc) }));
|
||||
}
|
||||
|
||||
/// <summary>Forward one batch-capable driver production burst to the parent as a single message.
|
||||
@@ -1909,12 +2029,14 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// driver's snapshot, never from this actor's clock).</para></summary>
|
||||
private void OnDataChangeBatchForward(DataChangeBatchForward msg)
|
||||
{
|
||||
if (msg.ProducerIncarnation != _sourceIncarnation) return;
|
||||
var items = new AttributeValueItem[msg.Items.Count];
|
||||
for (var i = 0; i < msg.Items.Count; i++)
|
||||
{
|
||||
var item = msg.Items[i];
|
||||
var ts = item.Snapshot.SourceTimestampUtc ?? item.Snapshot.ServerTimestampUtc;
|
||||
items[i] = new AttributeValueItem(item.FullReference, item.Snapshot.Value, item.Snapshot.StatusCode, ts);
|
||||
var ts = item.Snapshot.SourceTimestampUtc ?? item.Snapshot.ServerTimestampUtc ?? DateTime.MinValue;
|
||||
items[i] = new AttributeValueItem(item.FullReference, item.Snapshot.Value, item.Snapshot.StatusCode, ts,
|
||||
item.Snapshot.SourceTimestampUtc, item.Snapshot.ServerTimestampUtc);
|
||||
}
|
||||
Context.Parent.Tell(new AttributeValueBatchPublished(_driverInstanceId, items));
|
||||
}
|
||||
@@ -2040,6 +2162,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// <inheritdoc />
|
||||
protected override void PostStop()
|
||||
{
|
||||
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireDriver(_driverInstanceId, incarnation);
|
||||
// Archreview 03/S15 — announce comms loss on the way out. Every OTHER route into Reconnecting
|
||||
// (watchdog trip, failed initial connect, Force Reconnect) announces it from the Reconnecting
|
||||
// entry; stopping did not, so an operator's Restart and a supervision respawn tore this child down
|
||||
@@ -2052,7 +2175,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
// overwriting it would claim an outage that never happened.
|
||||
if (_connectedSinceUtc != default)
|
||||
{
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false));
|
||||
Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: false, ProducerIncarnation: _sourceIncarnation));
|
||||
}
|
||||
|
||||
DetachSubscription();
|
||||
|
||||
@@ -108,7 +108,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// </param>
|
||||
public sealed record RebuildAddressSpace(
|
||||
CorrelationId Correlation, DeploymentId? DeploymentId = null, byte[]? Artifact = null,
|
||||
bool ReportOutcome = false);
|
||||
bool ReportOutcome = false, DataConnections.CatalogAttempt? CatalogAttempt = null,
|
||||
bool StageCatalog = false);
|
||||
|
||||
/// <summary>
|
||||
/// the reply to a <see cref="RebuildAddressSpace"/> carrying
|
||||
@@ -166,6 +167,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
private readonly object _incarnation = new();
|
||||
private readonly TestHooks? _hooks;
|
||||
private readonly DataConnections.CatalogActivation _dataCatalog;
|
||||
private readonly DataConnections.LocalCatalogCoordinator? _catalogCoordinator;
|
||||
private long _dataCatalogEpoch;
|
||||
|
||||
/// <summary>
|
||||
@@ -335,7 +337,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
IOpcUaEndpointState? endpointState = null,
|
||||
WarmRedundancySettings? redundancy = null,
|
||||
IStandbyProjection? standbyProjection = null,
|
||||
DataConnections.CatalogActivation? dataCatalog = null) =>
|
||||
DataConnections.CatalogActivation? dataCatalog = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
|
||||
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
|
||||
sink ?? NullOpcUaAddressSpaceSink.Instance,
|
||||
serviceLevel ?? NullServiceLevelPublisher.Instance,
|
||||
@@ -352,7 +355,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
utcNow,
|
||||
endpointState,
|
||||
redundancy,
|
||||
standbyProjection, dataCatalog)).WithDispatcher(DispatcherId);
|
||||
standbyProjection, dataCatalog, catalogCoordinator)).WithDispatcher(DispatcherId);
|
||||
|
||||
/// <summary>Test-only Props that omits the pinned-dispatcher requirement and skips the
|
||||
/// DPS subscribe so unit tests can spin up the actor on a vanilla TestKit cluster.</summary>
|
||||
@@ -399,7 +402,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
IOpcUaEndpointState? endpointState = null,
|
||||
WarmRedundancySettings? redundancy = null,
|
||||
IStandbyProjection? standbyProjection = null,
|
||||
DataConnections.CatalogActivation? dataCatalog = null) =>
|
||||
DataConnections.CatalogActivation? dataCatalog = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
|
||||
Akka.Actor.Props.Create(() => new OpcUaPublishActor(
|
||||
sink ?? NullOpcUaAddressSpaceSink.Instance,
|
||||
serviceLevel ?? NullServiceLevelPublisher.Instance,
|
||||
@@ -416,7 +420,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
utcNow,
|
||||
endpointState,
|
||||
redundancy,
|
||||
standbyProjection, dataCatalog));
|
||||
standbyProjection, dataCatalog, catalogCoordinator));
|
||||
|
||||
/// <summary>Test-only Props exposing the deferred-write bound and the plan-step seams.</summary>
|
||||
internal static Props PropsForTests(
|
||||
@@ -425,12 +429,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
TestHooks? hooks,
|
||||
int deferredWriteCapacity = DefaultDeferredWriteCapacity,
|
||||
NodeId? localNode = null,
|
||||
IDataPlaneAuthoritySink? dataPlaneAuthority = null) =>
|
||||
IDataPlaneAuthoritySink? dataPlaneAuthority = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null) =>
|
||||
// CreateBy, not Create(expression): Akka's expression path activates through a PUBLIC constructor, and the
|
||||
// seam-carrying constructor is internal so the test seams stay off the public API (review M3).
|
||||
Akka.Actor.Props.CreateBy(new TestProducer(() => new OpcUaPublishActor(
|
||||
sink, NullServiceLevelPublisher.Instance, false, localNode, null, applier, null, null, null, null,
|
||||
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null)));
|
||||
false, dataPlaneAuthority, null, deferredWriteCapacity, hooks, endpointState: null,
|
||||
catalogCoordinator: catalogCoordinator)));
|
||||
|
||||
/// <summary>Produces the actor through its internal (seam-carrying) constructor, for <see cref="PropsForTests(IOpcUaAddressSpaceSink, AddressSpaceApplier?, TestHooks?, int, NodeId?, IDataPlaneAuthoritySink?)"/>.</summary>
|
||||
private sealed class TestProducer(Func<OpcUaPublishActor> create) : IIndirectActorProducer
|
||||
@@ -480,10 +486,11 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
IOpcUaEndpointState? endpointState = null,
|
||||
WarmRedundancySettings? redundancy = null,
|
||||
IStandbyProjection? standbyProjection = null,
|
||||
DataConnections.CatalogActivation? dataCatalog = null)
|
||||
DataConnections.CatalogActivation? dataCatalog = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
|
||||
: this(sink, serviceLevel, subscribeRedundancyTopic, localNode, dbFactory, applier, dbHealthProbe, staleWindow,
|
||||
probeFreshnessWindow, healthTickInterval, dbLess, dataPlaneAuthority, utcNow, DefaultDeferredWriteCapacity, hooks: null,
|
||||
endpointState, redundancy, standbyProjection, dataCatalog)
|
||||
endpointState, redundancy, standbyProjection, dataCatalog, catalogCoordinator)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -510,12 +517,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
IOpcUaEndpointState? endpointState,
|
||||
WarmRedundancySettings? redundancy = null,
|
||||
IStandbyProjection? standbyProjection = null,
|
||||
DataConnections.CatalogActivation? dataCatalog = null)
|
||||
DataConnections.CatalogActivation? dataCatalog = null,
|
||||
DataConnections.LocalCatalogCoordinator? catalogCoordinator = null)
|
||||
{
|
||||
_redundancy = redundancy ?? WarmRedundancySettings.Unset;
|
||||
_standbyProjection = standbyProjection;
|
||||
_deferred = new DeferredWrites(Math.Max(1, deferredWriteCapacity));
|
||||
_hooks = hooks;
|
||||
_catalogCoordinator = catalogCoordinator;
|
||||
_dataCatalog = dataCatalog ?? hooks?.DataCatalog ?? new DataConnections.CatalogActivation();
|
||||
_sink = sink;
|
||||
_dataPlaneAuthority = dataPlaneAuthority;
|
||||
@@ -743,10 +752,44 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
|
||||
private void HandleRebuild(RebuildAddressSpace msg)
|
||||
{
|
||||
if (_catalogCoordinator is not null && msg.CatalogAttempt is null)
|
||||
{
|
||||
var revision = msg.Artifact is { Length: > 0 } bytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)) : "unavailable";
|
||||
msg = msg with { CatalogAttempt = _catalogCoordinator.BeginAttempt(revision), StageCatalog = true };
|
||||
}
|
||||
if (msg.Artifact is { Length: > 0 } artifact) CheckRedundancyMode(artifact);
|
||||
StartRebuild(msg, Sender);
|
||||
}
|
||||
|
||||
private void StageStandaloneCatalog(RebuildAddressSpace msg, ParsedDeploymentArtifact parsed)
|
||||
{
|
||||
if (_catalogCoordinator is null || msg.CatalogAttempt is null) return;
|
||||
msg.CatalogAttempt.SetExpected(parsed.ExpectsLocalDataCatalog());
|
||||
if (_localNode is null) return;
|
||||
try
|
||||
{
|
||||
var authority = _hooks?.ParseAuthority is { } parse
|
||||
? parse(parsed, _localNode.Value.Value) : parsed.ParseDataPlaneAuthority(_localNode.Value.Value);
|
||||
if (!_catalogCoordinator.InstallAuthority(msg.CatalogAttempt, authority)) return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "OpcUaPublish: standalone data authority could not be installed");
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
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);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "OpcUaPublish: standalone data catalog could not be staged");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The entry half of a rebuild, on the actor thread. The raw-sink fallback (no applier) and the
|
||||
/// no-artifact case complete synchronously; otherwise the artifact parse, the cluster-scoped composition
|
||||
@@ -771,13 +814,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
var desiredRevision = msg.Artifact is { Length: > 0 } desiredBytes
|
||||
? Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(desiredBytes))
|
||||
: "unavailable";
|
||||
_dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
|
||||
if (_catalogCoordinator is null) _dataCatalogEpoch = _dataCatalog.Begin(desiredRevision);
|
||||
|
||||
// Only a node with NO applier at all (the F10b/dev seam) falls back to the raw-sink rebuild — and that
|
||||
// fallback WIPES the served address space without re-materialising, so it must NEVER be reached by a
|
||||
// real driver node that has an applier (that node diff-and-applies from its in-hand bytes below).
|
||||
if (_applier is null)
|
||||
{
|
||||
if (msg.StageCatalog && msg.Artifact is { Length: > 0 } standaloneBytes)
|
||||
{
|
||||
try { using var parsed = DeploymentArtifact.Open(standaloneBytes); StageStandaloneCatalog(msg, parsed); }
|
||||
catch (Exception ex) { _log.Error(ex, "OpcUaPublish: unable to stage standalone data catalog"); }
|
||||
}
|
||||
// Every rebuild is traced, whichever path completes it: the applier path opens its span in ApplyPlan
|
||||
// (the actor-thread half), the two synchronous completions below open their own.
|
||||
using var span = OtOpcUaTelemetry.StartAddressSpaceRebuildSpan();
|
||||
@@ -825,7 +873,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
var artifact = msg.Artifact;
|
||||
var baseComposition = _lastApplied;
|
||||
var nodeId = _localNode?.Value;
|
||||
var wantAuthority = _dataPlaneAuthority is not null;
|
||||
var wantAuthority = _dataPlaneAuthority is not null && _catalogCoordinator is null;
|
||||
var incarnation = _incarnation;
|
||||
var hooks = _hooks;
|
||||
Task.Run<object>(() =>
|
||||
@@ -835,6 +883,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
// result — and an empty composition is not a benign no-op here (see the no-bytes guard above). The
|
||||
// throw lands in PlanFailed: logged at Error, _lastApplied untouched, last-known-good still served.
|
||||
using var parsed = DeploymentArtifact.Open(artifact);
|
||||
if (msg.StageCatalog) StageStandaloneCatalog(msg, parsed);
|
||||
// The authority parse is isolated from the address-space plan (review fix I2): before the plan moved
|
||||
// off-thread a throw here was contained by FeedDataPlaneAuthority's own catch; it must not now
|
||||
// become PlanFailed and degrade an apply whose topology is perfectly readable.
|
||||
@@ -1048,6 +1097,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
public object? Value;
|
||||
public uint Status;
|
||||
public DateTime TimestampUtc;
|
||||
public DateTime? OriginalSourceTimestampUtc;
|
||||
public DateTime? OriginalServerTimestampUtc;
|
||||
}
|
||||
|
||||
private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new();
|
||||
@@ -1069,6 +1120,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
_variables[key] = new VariableEntry
|
||||
{
|
||||
HasValue = true, Value = write.Value, Status = write.StatusCode, TimestampUtc = write.SourceTimestampUtc,
|
||||
OriginalSourceTimestampUtc = write.OriginalSourceTimestampUtc,
|
||||
OriginalServerTimestampUtc = write.OriginalServerTimestampUtc,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
@@ -1110,7 +1163,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
foreach (var ((realm, id), e) in _variables)
|
||||
{
|
||||
if (!include((realm, id))) continue;
|
||||
if (e.HasValue) values.Add(new ValueWrite(id, e.Value, e.Status, e.TimestampUtc, realm));
|
||||
if (e.HasValue) values.Add(new ValueWrite(id, e.Value, e.Status, e.TimestampUtc, realm,
|
||||
e.OriginalSourceTimestampUtc, e.OriginalServerTimestampUtc));
|
||||
else statuses.Add(new StatusWrite(id, e.Status, e.TimestampUtc, realm));
|
||||
}
|
||||
|
||||
@@ -1154,6 +1208,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "OpcUaPublish: sink.CompleteAddressSpaceApply threw (correlation={Correlation})", msg.Correlation);
|
||||
outcome = (true, $"address-space completion threw: {ex.Message}");
|
||||
}
|
||||
|
||||
// Land what arrived while the plan was in flight on the nodes the apply just created — before the answer,
|
||||
@@ -1161,6 +1216,13 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
ReplayDeferredWrites(_replayScope);
|
||||
_replayScope = ReplayScope.Nothing;
|
||||
|
||||
if (msg.CatalogAttempt is not null && _catalogCoordinator is not null)
|
||||
{
|
||||
var activated = _catalogCoordinator.Complete(msg.CatalogAttempt, topologySucceeded: !outcome.Degraded);
|
||||
if (!activated && msg.CatalogAttempt.Expected && !outcome.Degraded)
|
||||
outcome = (true, "the expected local data catalog could not be activated");
|
||||
}
|
||||
|
||||
if (msg.ReportOutcome)
|
||||
requester.Tell(new RebuildCompleted(msg.Correlation, msg.DeploymentId, outcome.Degraded, outcome.Reason));
|
||||
}
|
||||
@@ -1174,7 +1236,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
try
|
||||
{
|
||||
var result = ApplyPlanCore(ready, out var rebuilt);
|
||||
_dataCatalog.Complete(_dataCatalogEpoch, !result.Degraded && ready.AuthorityError is null);
|
||||
if (_catalogCoordinator is null)
|
||||
_dataCatalog.Complete(_dataCatalogEpoch, !result.Degraded && ready.AuthorityError is null);
|
||||
// What this apply created or reset (see _replayScope). A throwing pass still scopes to what it did.
|
||||
var conditions = AddedConditions(previous, ready.Composition);
|
||||
if (rebuilt)
|
||||
|
||||
@@ -56,10 +56,14 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
/// §9): re-evaluate once against the latest inputs. Private to the actor.
|
||||
/// </summary>
|
||||
private sealed class RunnerRecovered { public static readonly RunnerRecovered Instance = new(); private RunnerRecovered() { } }
|
||||
private sealed class RetrySourceBinding { public static readonly RetrySourceBinding Instance = new(); private RetrySourceBinding() { } }
|
||||
private ICancelable? _sourceBindingRetry;
|
||||
|
||||
/// <summary>The asynchronous evaluation started by <see cref="Evaluate"/> finished. Private to the actor.</summary>
|
||||
private sealed record EvaluationCompleted(
|
||||
Task<VirtualTagEvalResult> Evaluation, uint WorstInputStatus, DateTime TimestampUtc);
|
||||
Task<VirtualTagEvalResult> Evaluation, uint WorstInputStatus, DateTime TimestampUtc, long ActorIncarnation);
|
||||
private static long s_actorIncarnation;
|
||||
private readonly long _actorIncarnation = Interlocked.Increment(ref s_actorIncarnation);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IStash Stash { get; set; } = null!;
|
||||
@@ -101,9 +105,12 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
/// publishes it (to repair the reset OPC UA node) but must NOT re-record it to the historian — it is a
|
||||
/// stale value stamped with a fresh deploy-time timestamp, never a real evaluation sample. Defaults to
|
||||
/// <c>false</c> so every existing construction site stays source-compatible.</param>
|
||||
public sealed record EvaluationResult(string VirtualTagId, object? Value, DateTime TimestampUtc, CorrelationId Correlation, uint StatusCode = OpcUaStatus.Good, bool IsReassert = false);
|
||||
public sealed record EvaluationResult(string VirtualTagId, object? Value, DateTime TimestampUtc, CorrelationId Correlation,
|
||||
uint StatusCode = OpcUaStatus.Good, bool IsReassert = false, bool SourceHandled = false);
|
||||
|
||||
private readonly string _virtualTagId;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private long? _sourceIncarnation;
|
||||
private readonly string _scriptId;
|
||||
private readonly string _expression;
|
||||
private readonly IVirtualTagEvaluator _evaluator;
|
||||
@@ -162,7 +169,9 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
ITelemetryLocalHub? telemetryHub = null,
|
||||
ScriptLogRateLimiter? failureLogLimiter = null,
|
||||
bool changeTriggered = true,
|
||||
int? timerIntervalMs = null) =>
|
||||
int? timerIntervalMs = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null) =>
|
||||
Akka.Actor.Props.Create(() => new VirtualTagActor(
|
||||
virtualTagId, expression,
|
||||
evaluator ?? NullVirtualTagEvaluator.Instance,
|
||||
@@ -173,7 +182,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
telemetryHub,
|
||||
failureLogLimiter,
|
||||
changeTriggered,
|
||||
timerIntervalMs));
|
||||
timerIntervalMs, sourcePublisher, sourceIncarnation));
|
||||
|
||||
/// <summary>Initializes a virtual tag actor with the given configuration and dependencies.</summary>
|
||||
/// <param name="virtualTagId">Unique identifier for the virtual tag.</param>
|
||||
@@ -202,8 +211,12 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
ITelemetryLocalHub? telemetryHub = null,
|
||||
ScriptLogRateLimiter? failureLogLimiter = null,
|
||||
bool changeTriggered = true,
|
||||
int? timerIntervalMs = null)
|
||||
int? timerIntervalMs = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null,
|
||||
long? sourceIncarnation = null)
|
||||
{
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_sourceIncarnation = sourceIncarnation;
|
||||
_changeTriggered = changeTriggered;
|
||||
_timerIntervalMs = timerIntervalMs is > 0 ? Math.Max(timerIntervalMs.Value, MinTimerIntervalMs) : null;
|
||||
_virtualTagId = virtualTagId;
|
||||
@@ -219,6 +232,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
Receive<DependencyValueChanged>(OnDependencyChanged);
|
||||
Receive<DependencyValueBatch>(OnDependencyBatch);
|
||||
Receive<ReassertValue>(_ => OnReassertValue());
|
||||
Receive<RetrySourceBinding>(_ => RetrySource());
|
||||
Receive<TimerTick>(_ => Evaluate(DateTime.UtcNow));
|
||||
Receive<RunnerRecovered>(_ =>
|
||||
{
|
||||
@@ -233,6 +247,13 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
/// <inheritdoc />
|
||||
protected override void PreStart()
|
||||
{
|
||||
if (_sourcePublisher is not null && _sourceIncarnation is { } previous &&
|
||||
!_sourcePublisher.IsVirtualIncarnationActive(_virtualTagId, previous))
|
||||
{
|
||||
var current = _sourcePublisher.RegisterVirtualIncarnation(_virtualTagId);
|
||||
_sourceIncarnation = current;
|
||||
if (!_sourcePublisher.EnsureVirtualBinding(_virtualTagId, current)) ScheduleSourceRetry();
|
||||
}
|
||||
if (_timerIntervalMs is { } ms)
|
||||
{
|
||||
// lmxopcua#783: timer-driven evaluation. Cancelled in PostStop, so a stop / redeploy respawn
|
||||
@@ -252,10 +273,27 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
/// <inheritdoc />
|
||||
protected override void PostStop()
|
||||
{
|
||||
if (_sourceIncarnation is { } incarnation) _sourcePublisher?.RetireVirtualIncarnation(_virtualTagId, incarnation);
|
||||
_sourceBindingRetry?.Cancel();
|
||||
_timer?.Cancel();
|
||||
_mux?.Tell(new DependencyMuxActor.UnregisterInterest(Self));
|
||||
}
|
||||
|
||||
private void ScheduleSourceRetry()
|
||||
{
|
||||
_sourceBindingRetry?.Cancel();
|
||||
_sourceBindingRetry = Context.System.Scheduler.ScheduleTellOnceCancelable(
|
||||
TimeSpan.FromMilliseconds(250), Self, RetrySourceBinding.Instance, Self);
|
||||
}
|
||||
|
||||
private void RetrySource()
|
||||
{
|
||||
_sourceBindingRetry = null;
|
||||
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation) return;
|
||||
if (!_sourcePublisher.EnsureVirtualBinding(_virtualTagId, incarnation)) { ScheduleSourceRetry(); return; }
|
||||
if (AllDependenciesArrived()) Evaluate(DateTime.UtcNow);
|
||||
}
|
||||
|
||||
/// <summary>Re-emit the last emitted value/quality to the parent bridge, bypassing the value dedup, so a
|
||||
/// deploy that re-materialised our published UNS node to <c>BadWaitingForInitialData</c> recovers even when
|
||||
/// the recomputed value is unchanged (permanent Bad otherwise, with a static dependency). No-op until the
|
||||
@@ -353,14 +391,15 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
if (evaluation.IsCompleted)
|
||||
{
|
||||
// Synchronous evaluators (passthrough, null evaluator, fakes) and cheap failures: same turn, as before.
|
||||
ApplyEvaluation(evaluation, worst, timestampUtc);
|
||||
ApplyEvaluation(FreezeEvaluation(evaluation), worst, timestampUtc);
|
||||
return;
|
||||
}
|
||||
|
||||
// A real script run is in flight: free the dispatcher thread, hold every later input until it lands.
|
||||
var self = Self;
|
||||
var actorIncarnation = _actorIncarnation;
|
||||
evaluation.ContinueWith(
|
||||
t => self.Tell(new EvaluationCompleted(t, worst, timestampUtc)),
|
||||
t => self.Tell(new EvaluationCompleted(FreezeEvaluation(t), worst, timestampUtc, actorIncarnation)),
|
||||
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
|
||||
BecomeStacked(Evaluating);
|
||||
}
|
||||
@@ -371,6 +410,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
{
|
||||
Receive<EvaluationCompleted>(msg =>
|
||||
{
|
||||
if (msg.ActorIncarnation != _actorIncarnation) return;
|
||||
UnbecomeStacked();
|
||||
ApplyEvaluation(msg.Evaluation, msg.WorstInputStatus, msg.TimestampUtc);
|
||||
Stash.UnstashAll();
|
||||
@@ -381,6 +421,24 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
ReceiveAny(_ => Stash.Stash());
|
||||
}
|
||||
|
||||
private static Task<VirtualTagEvalResult> FreezeEvaluation(Task<VirtualTagEvalResult> task)
|
||||
{
|
||||
if (!task.IsCompletedSuccessfully || !task.Result.Success || ReferenceEquals(task.Result, VirtualTagEvalResult.NoChange))
|
||||
return task;
|
||||
try
|
||||
{
|
||||
var result = task.Result;
|
||||
return Task.FromResult(result with
|
||||
{
|
||||
Value = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.OwnedDataSample.CopyLegacy(result.Value)
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Task.FromException<VirtualTagEvalResult>(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A runner failure (BadResourceUnavailable) carries the task that completes when the runner is back: evaluate
|
||||
/// again then, with whatever inputs are current, instead of holding the Bad until the next input change — which,
|
||||
@@ -434,6 +492,10 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
return;
|
||||
}
|
||||
|
||||
// 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.
|
||||
PublishSource(result.Value, worst, timestampUtc);
|
||||
|
||||
// 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
|
||||
// back usually produces, and the node then stays Bad forever.
|
||||
@@ -450,7 +512,7 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
// reaches here — it was held above).
|
||||
_lastPublishedStatus = worst;
|
||||
OtOpcUaTelemetry.VirtualTagEval.Add(1, new KeyValuePair<string, object?>("outcome", "ok"));
|
||||
var evalResult = new EvaluationResult(_virtualTagId, result.Value, timestampUtc, CorrelationId.NewId(), worst);
|
||||
var evalResult = new EvaluationResult(_virtualTagId, result.Value, timestampUtc, CorrelationId.NewId(), worst, SourceHandled: _sourcePublisher is not null);
|
||||
Context.Parent.Tell(evalResult);
|
||||
}
|
||||
|
||||
@@ -490,8 +552,9 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
|
||||
_hasPublished = true;
|
||||
_lastPublishedStatus = worstInputStatus;
|
||||
PublishSourceStatus(worstInputStatus);
|
||||
Context.Parent.Tell(new EvaluationResult(
|
||||
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), worstInputStatus));
|
||||
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), worstInputStatus, SourceHandled: _sourcePublisher is not null));
|
||||
}
|
||||
|
||||
/// <summary>02/S13 failure tail shared by the evaluator-threw catch and the <c>!Success</c> branch.
|
||||
@@ -528,8 +591,23 @@ public sealed class VirtualTagActor : ReceiveActor, IWithUnboundedStash
|
||||
|
||||
_hasPublished = true;
|
||||
_lastPublishedStatus = badStatus;
|
||||
PublishSourceStatus(badStatus);
|
||||
Context.Parent.Tell(new EvaluationResult(
|
||||
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), badStatus));
|
||||
_virtualTagId, _hasLastValue ? _lastValue : null, timestampUtc, CorrelationId.NewId(), badStatus, SourceHandled: _sourcePublisher is not null));
|
||||
}
|
||||
|
||||
private void PublishSource(object? value, uint status, DateTime timestamp)
|
||||
{
|
||||
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation ||
|
||||
!_sourcePublisher.TryCaptureVirtual(_virtualTagId, incarnation, out var ticket)) return;
|
||||
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(value, status, timestamp, timestamp));
|
||||
}
|
||||
|
||||
private void PublishSourceStatus(uint status)
|
||||
{
|
||||
if (_sourcePublisher is null || _sourceIncarnation is not { } incarnation ||
|
||||
!_sourcePublisher.TryCaptureVirtual(_virtualTagId, incarnation, out var ticket)) return;
|
||||
_sourcePublisher.TryPublishStatus(ticket, status, out _);
|
||||
}
|
||||
|
||||
/// <summary>Inputs-ready gate (the retired cascade engine's rule): true once
|
||||
|
||||
@@ -38,15 +38,19 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
||||
/// feedback storm.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class VirtualTagHostActor : ReceiveActor
|
||||
public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
{
|
||||
public ITimerScheduler Timers { get; set; } = null!;
|
||||
/// <summary>Reconciles the live VirtualTag children to exactly the supplied desired set:
|
||||
/// stops children whose vtagId is gone, spawns children for new vtagIds, and rebuilds the
|
||||
/// vtagId→NodeId map so renames are reflected.</summary>
|
||||
/// <param name="Plans">The desired Equipment-namespace VirtualTag plans.</param>
|
||||
public sealed record ApplyVirtualTags(IReadOnlyList<EquipmentVirtualTagPlan> Plans);
|
||||
|
||||
private readonly IActorRef _publishActor;
|
||||
private readonly IActorRef? _publishActor;
|
||||
private readonly ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? _sourcePublisher;
|
||||
private readonly HashSet<string> _publishedVirtualIds = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, long> _virtualSourceIncarnations = new(StringComparer.Ordinal);
|
||||
private readonly IActorRef? _mux;
|
||||
private readonly IVirtualTagEvaluator _evaluator;
|
||||
// Sink for historized VirtualTag results (plans with Historize=true). NullHistoryWriter when no
|
||||
@@ -80,9 +84,10 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
/// <param name="telemetryHub">Optional node-local live-telemetry hub passed to each spawned child so
|
||||
/// its script-log entries also emit to the live-telemetry hub; null (tests) skips the emit.</param>
|
||||
/// <returns>The <see cref="Props"/> used to spawn a <see cref="VirtualTagHostActor"/>.</returns>
|
||||
public static Props Props(IActorRef publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
|
||||
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null) =>
|
||||
Akka.Actor.Props.Create(() => new VirtualTagHostActor(publishActor, mux, evaluator, historyWriter, telemetryHub));
|
||||
public static Props Props(IActorRef? publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
|
||||
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null) =>
|
||||
Akka.Actor.Props.Create(() => new VirtualTagHostActor(publishActor, mux, evaluator, historyWriter, telemetryHub, sourcePublisher));
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="VirtualTagHostActor"/> class.</summary>
|
||||
/// <param name="publishActor">The OPC UA publish actor results are bridged to.</param>
|
||||
@@ -91,12 +96,13 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
/// <param name="historyWriter">Sink for historized results; null ⇒ <see cref="NullHistoryWriter.Instance"/>.</param>
|
||||
/// <param name="telemetryHub">Optional node-local live-telemetry hub passed to each spawned child so
|
||||
/// its script-log entries also emit to the live-telemetry hub; null (tests) skips the emit.</param>
|
||||
public VirtualTagHostActor(IActorRef publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
|
||||
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null)
|
||||
public VirtualTagHostActor(IActorRef? publishActor, IActorRef? mux, IVirtualTagEvaluator evaluator,
|
||||
IHistoryWriter? historyWriter = null, ITelemetryLocalHub? telemetryHub = null,
|
||||
ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.SourceSamplePublisher? sourcePublisher = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(publishActor);
|
||||
ArgumentNullException.ThrowIfNull(evaluator);
|
||||
_publishActor = publishActor;
|
||||
_sourcePublisher = sourcePublisher;
|
||||
_mux = mux;
|
||||
_evaluator = evaluator;
|
||||
_history = historyWriter ?? NullHistoryWriter.Instance;
|
||||
@@ -109,6 +115,15 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
|
||||
private void OnApply(ApplyVirtualTags msg)
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
var virtualIds = msg.Plans.Select(p => p.VirtualTagId).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var id in _publishedVirtualIds.Where(id => !virtualIds.Contains(id)))
|
||||
{
|
||||
if (_virtualSourceIncarnations.Remove(id, out _)) _sourcePublisher?.RetireCurrentVirtual(id);
|
||||
if (_sourcePublisher?.TryCaptureVirtual(id, out var ticket) == true) _sourcePublisher.TryRemove(ticket);
|
||||
}
|
||||
_publishedVirtualIds.Clear();
|
||||
_publishedVirtualIds.UnionWith(virtualIds);
|
||||
// Apply-boundary compile-cache drop (gated — 02/P7): the production evaluator roots one
|
||||
// collectible AssemblyLoadContext per compiled expression, so a changed script set must drop the
|
||||
// stale ALCs. But clearing on EVERY apply forces a full recompilation even on a byte-identical
|
||||
@@ -143,6 +158,7 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
// PostStop, which unregisters its interest from the mux.
|
||||
foreach (var vtagId in _children.Keys.Where(id => !desired.Contains(id)).ToList())
|
||||
{
|
||||
if (_virtualSourceIncarnations.Remove(vtagId, out _)) _sourcePublisher?.RetireCurrentVirtual(vtagId);
|
||||
Context.Stop(_children[vtagId]);
|
||||
_children.Remove(vtagId);
|
||||
}
|
||||
@@ -158,6 +174,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
&& _planByVtag.TryGetValue(p.VirtualTagId, out var prev)
|
||||
&& !prev.Equals(p))
|
||||
{
|
||||
if (_virtualSourceIncarnations.Remove(p.VirtualTagId, out _)) _sourcePublisher?.RetireCurrentVirtual(p.VirtualTagId);
|
||||
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
|
||||
_sourcePublisher.TryRebind(ticket, out _);
|
||||
Context.Stop(_children[p.VirtualTagId]); // PostStop unregisters the old mux interest.
|
||||
_children.Remove(p.VirtualTagId);
|
||||
}
|
||||
@@ -191,6 +210,22 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
|
||||
// Auto-name the child: vtagIds can contain characters illegal in actor names, so let Akka
|
||||
// assign a safe unique name. The child self-registers with the mux in PreStart.
|
||||
long? sourceIncarnation = null;
|
||||
if (_sourcePublisher is not null)
|
||||
{
|
||||
if (!_virtualSourceIncarnations.TryGetValue(p.VirtualTagId, out var currentToken))
|
||||
currentToken = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
|
||||
sourceIncarnation = currentToken;
|
||||
}
|
||||
if (sourceIncarnation is { } token)
|
||||
{
|
||||
_virtualSourceIncarnations[p.VirtualTagId] = token;
|
||||
if (!_sourcePublisher!.EnsureVirtualBinding(p.VirtualTagId, token))
|
||||
{
|
||||
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
var child = Context.ActorOf(VirtualTagActor.Props(
|
||||
virtualTagId: p.VirtualTagId,
|
||||
expression: p.Expression,
|
||||
@@ -201,7 +236,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
mux: _mux,
|
||||
telemetryHub: _telemetryHub,
|
||||
changeTriggered: p.ChangeTriggered,
|
||||
timerIntervalMs: p.TimerIntervalMs));
|
||||
timerIntervalMs: p.TimerIntervalMs,
|
||||
sourcePublisher: _sourcePublisher,
|
||||
sourceIncarnation: sourceIncarnation));
|
||||
Context.Watch(child);
|
||||
_children[p.VirtualTagId] = child;
|
||||
newlySpawned.Add(p.VirtualTagId);
|
||||
@@ -246,9 +283,19 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
// reports BadOutOfService instead of serving a value computed from a stale input.
|
||||
foreach (var p in msg.Plans.Where(p => !p.Enabled))
|
||||
{
|
||||
if (_sourcePublisher is not null && !_virtualSourceIncarnations.ContainsKey(p.VirtualTagId))
|
||||
{
|
||||
var token = _sourcePublisher.RegisterVirtualIncarnation(p.VirtualTagId);
|
||||
_virtualSourceIncarnations[p.VirtualTagId] = token;
|
||||
}
|
||||
if (_sourcePublisher is not null &&
|
||||
!_sourcePublisher.EnsureVirtualBinding(p.VirtualTagId, _virtualSourceIncarnations[p.VirtualTagId]))
|
||||
Timers.StartSingleTimer("source-binding-retry", msg, TimeSpan.FromMilliseconds(250));
|
||||
var nodeId = NodeIdFor(p);
|
||||
var now = DateTime.UtcNow;
|
||||
_publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate(
|
||||
if (_sourcePublisher?.TryCaptureVirtual(p.VirtualTagId, out var ticket) == true)
|
||||
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(null, OpcUaStatus.BadOutOfService, null, null));
|
||||
_publishActor?.Tell(new OpcUaPublishActor.AttributeValueUpdate(
|
||||
nodeId, null, OpcUaStatus.BadOutOfService, now, AddressSpaceRealm.Uns));
|
||||
_mux?.Tell(new DependencyMuxActor.VirtualTagOutput(nodeId, null, now, OpcUaStatus.BadOutOfService));
|
||||
}
|
||||
@@ -302,7 +349,9 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
// failure/timeout) carrying the last-known value. Bridge result.StatusCode through verbatim; the
|
||||
// sink maps it to StatusCodes.Good/Bad on the node so a broken script no longer freezes Good.
|
||||
// VirtualTags materialise as equipment nodes in the UNS realm — publish there.
|
||||
_publishActor.Tell(new OpcUaPublishActor.AttributeValueUpdate(
|
||||
if (!result.IsReassert && !result.SourceHandled && _sourcePublisher?.TryCaptureVirtual(result.VirtualTagId, out var ticket) == true)
|
||||
_sourcePublisher.TryPublish(ticket, new DataValueSnapshot(result.Value, result.StatusCode, result.TimestampUtc, result.TimestampUtc));
|
||||
_publishActor?.Tell(new OpcUaPublishActor.AttributeValueUpdate(
|
||||
nodeId, result.Value, result.StatusCode, result.TimestampUtc, AddressSpaceRealm.Uns));
|
||||
|
||||
// lmxopcua#791: feed the VirtualTags (and Calculation tags / scripted alarms) that read this one. A
|
||||
@@ -331,6 +380,8 @@ public sealed class VirtualTagHostActor : ReceiveActor
|
||||
var stale = _children.Where(kv => kv.Value.Equals(msg.ActorRef)).Select(kv => kv.Key).ToList();
|
||||
foreach (var id in stale)
|
||||
{
|
||||
_sourcePublisher?.RetireCurrentVirtual(id);
|
||||
_virtualSourceIncarnations.Remove(id);
|
||||
_children.Remove(id);
|
||||
// Keep _planByVtag in lock-step with _children so it never holds a plan for a dead child.
|
||||
// (The next apply also resets it, and the change-detect guard short-circuits on the missing
|
||||
|
||||
@@ -431,7 +431,7 @@ internal sealed class WorkerHost
|
||||
VariantCodec.Decode(input.Value),
|
||||
input.StatusCode,
|
||||
input.SourceTsTicks == 0 ? null : new DateTime(input.SourceTsTicks, DateTimeKind.Utc),
|
||||
new DateTime(input.ServerTsTicks, DateTimeKind.Utc));
|
||||
input.ServerTsTicks == 0 ? null : new DateTime(input.ServerTsTicks, DateTimeKind.Utc));
|
||||
}
|
||||
|
||||
// ctx.Now follows the HOST clock (design §4.3) but keeps ticking: a fixed instant would never let a script
|
||||
|
||||
+15
@@ -53,6 +53,21 @@ public sealed class GrpcDataContractsTests
|
||||
sample.StatusCode.ShouldBe(0x80000001u);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retained_size_covers_payload_and_shape_without_returning_mutable_storage()
|
||||
{
|
||||
using var bytes = DataValue.FromBytes(new byte[10]);
|
||||
using var text = DataValue.FromScalar(DataValueKind.String, "abcd");
|
||||
using var array = DataValue.FromArray(DataValueKind.String, new object[] { "abc", "de" }, new[] { 2 });
|
||||
bytes.EstimatedRetainedBytes.ShouldBe(298);
|
||||
text.EstimatedRetainedBytes.ShouldBe(296);
|
||||
array.EstimatedRetainedBytes.ShouldBe(498);
|
||||
using var lease = array.Retain();
|
||||
lease.EstimatedRetainedBytes.ShouldBe(array.EstimatedRetainedBytes);
|
||||
lease.Dispose();
|
||||
Should.Throw<ObjectDisposedException>(() => lease.EstimatedRetainedBytes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Lease_deadline_is_anchored_to_request_start_and_bounded()
|
||||
{
|
||||
|
||||
+3
-2
@@ -149,8 +149,9 @@ public sealed class MTConnectObservationIndexTests
|
||||
var snap = idx.Get("dev1_pos");
|
||||
|
||||
snap.SourceTimestampUtc.ShouldBe(new DateTime(2026, 7, 24, 12, 0, 0, 200, DateTimeKind.Utc));
|
||||
snap.ServerTimestampUtc.ShouldBeGreaterThan(snap.SourceTimestampUtc!.Value);
|
||||
snap.ServerTimestampUtc.Kind.ShouldBe(DateTimeKind.Utc);
|
||||
snap.ServerTimestampUtc.ShouldNotBeNull();
|
||||
snap.ServerTimestampUtc!.Value.ShouldBeGreaterThan(snap.SourceTimestampUtc!.Value);
|
||||
snap.ServerTimestampUtc!.Value.Kind.ShouldBe(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
/// <summary>A Float64-authored SAMPLE coerces to a real double, not the raw text.</summary>
|
||||
|
||||
+3
-2
@@ -89,8 +89,9 @@ public sealed class OpcUaClientSdkValueBoundaryTests
|
||||
snapshot.Value?.GetType().ShouldBe(expected?.GetType());
|
||||
snapshot.StatusCode.ShouldBe(StatusCodes.UncertainLastUsableValue.Code);
|
||||
snapshot.SourceTimestampUtc.ShouldBeNull();
|
||||
snapshot.ServerTimestampUtc.ShouldBeGreaterThanOrEqualTo(before);
|
||||
snapshot.ServerTimestampUtc.Kind.ShouldBe(DateTimeKind.Utc);
|
||||
snapshot.ServerTimestampUtc.ShouldNotBeNull();
|
||||
snapshot.ServerTimestampUtc!.Value.ShouldBeGreaterThanOrEqualTo(before);
|
||||
snapshot.ServerTimestampUtc!.Value.Kind.ShouldBe(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataCachedReadTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Prepared_response_is_fenced_before_send_after_ingress_invalidation_or_authority_change()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
var lease = results[0].ResourceLease.ShouldBeAssignableTo<IDataPublicationLease>();
|
||||
lease!.IsValid.ShouldBeTrue();
|
||||
fixture.Hub.Invalidate(fixture.Ticket, "overflow before serialization");
|
||||
lease!.IsValid.ShouldBeFalse();
|
||||
((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeTrue();
|
||||
fixture.Activation.Begin("revocation");
|
||||
((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Returned_value_holds_its_global_resource_charge_until_recipient_disposes_it()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
var baseline = fixture.Hub.Resources.RetainedBytes;
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
|
||||
results[0].Dispose();
|
||||
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Initial_stale_and_invalidated_cached_reads_have_distinct_readiness()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var request = new ReadRequest([new("read", fixture.Raw, TimeSpan.FromSeconds(2))], LocalDataFixture.Budget);
|
||||
var initial = await connection.ReadAsync(request, TestContext.Current.CancellationToken);
|
||||
using (initial[0]) initial[0].Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
|
||||
fixture.Publish(42);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
|
||||
var stale = await connection.ReadAsync(request, TestContext.Current.CancellationToken);
|
||||
using (stale[0])
|
||||
{
|
||||
stale[0].Status.ShouldBe(DataItemStatus.Stale);
|
||||
stale[0].Age.ShouldBe(TimeSpan.FromSeconds(3));
|
||||
stale[0].Sample!.SourceTimestampUtc.ShouldBeNull();
|
||||
stale[0].Sample!.StatusCode.ShouldBe(0x00000400u);
|
||||
}
|
||||
fixture.Hub.Invalidate(fixture.Ticket, "overflow");
|
||||
var invalidated = await connection.ReadAsync(request, TestContext.Current.CancellationToken);
|
||||
using (invalidated[0])
|
||||
{
|
||||
invalidated[0].Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
invalidated[0].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Shared_backing_cache_does_not_share_authorization_between_Raw_and_Uns_aliases()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
var results = await connection.ReadAsync(new([new("raw", fixture.Raw, null), new("uns", fixture.Uns, null),
|
||||
new("forged", fixture.Raw with { Subject = "other" }, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0]) using (results[1]) using (results[2])
|
||||
{
|
||||
results.Select(x => x.CorrelationId).ShouldBe(["raw", "uns", "forged"]);
|
||||
results.Select(x => x.Status).ShouldBe([DataItemStatus.Good, DataItemStatus.Denied, DataItemStatus.Denied]);
|
||||
results[1].Sample!.ShouldBeNull();
|
||||
results[2].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Activation_invalidates_cached_payload_without_a_new_sample()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
fixture.Activation.Begin("new-authority");
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
results[0].Status.ShouldBe(DataItemStatus.Unavailable);
|
||||
results[0].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Original_credential_expiry_denies_a_quiet_cached_value_without_a_deploy()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
fixture.Clock.Advance(TimeSpan.FromMinutes(11));
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
results[0].Status.ShouldBe(DataItemStatus.Denied);
|
||||
results[0].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Quiet_initial_acquisition_gets_current_serving_header_without_changing_its_age_or_timestamps()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7, beforeActivation: true);
|
||||
var acquired = fixture.Clock.GetUtcNow();
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
|
||||
await using var connection = fixture.Connection();
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
results[0].Status.ShouldBe(DataItemStatus.Good);
|
||||
results[0].Sample!.Serving.ShouldBe(fixture.Serving);
|
||||
results[0].Sample!.Version.ShouldBe(1);
|
||||
results[0].Sample!.SourceTimestampUtc.ShouldBeNull();
|
||||
results[0].Sample!.ServerTimestampUtc.ShouldBe(acquired);
|
||||
results[0].Age.ShouldBe(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
+564
@@ -0,0 +1,564 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Akka.Actor;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
[Collection("opcua-publish-meters")]
|
||||
public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
{
|
||||
private static readonly NodeId Node = NodeId.Parse("node-a");
|
||||
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 A_new_attempt_closes_a_completed_catalog_even_when_authority_revision_is_unchanged()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var activation = new CatalogActivation();
|
||||
var coordinator = NewCoordinator(authority, activation);
|
||||
var bytes = Artifact();
|
||||
var first = Prepare(coordinator, bytes);
|
||||
coordinator.Current.ShouldBeNull();
|
||||
coordinator.Complete(first, topologySucceeded: true).ShouldBeTrue();
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
old.IsActive.ShouldBeTrue();
|
||||
var oldAuthority = authority.Current.GenerationId;
|
||||
|
||||
var second = coordinator.BeginAttempt(Hash(bytes));
|
||||
old.IsActive.ShouldBeFalse();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
coordinator.InstallAuthority(second, DeploymentArtifact.ParseDataPlaneAuthority(bytes, Node.Value)).ShouldBeTrue();
|
||||
authority.Current.GenerationId.ShouldBe(oldAuthority); // The authority store deduplicates identical bytes.
|
||||
using var parsed = DeploymentArtifact.Open(bytes);
|
||||
coordinator.Stage(second, parsed.ParseLocalCatalogSnapshot(Node.Value)!).ShouldBeTrue();
|
||||
coordinator.Complete(second, topologySucceeded: true).ShouldBeTrue();
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
coordinator.Current!.Serving.CatalogEpoch.ShouldBeGreaterThan(old.Serving.CatalogEpoch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Stale_attempt_cannot_install_older_authority_or_publish_its_catalog()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var olderBytes = Artifact();
|
||||
var older = Prepare(coordinator, olderBytes);
|
||||
var revokedBytes = Artifact(revoked: true);
|
||||
var newer = Prepare(coordinator, revokedBytes);
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
var newerGeneration = authority.Current.GenerationId;
|
||||
|
||||
coordinator.InstallAuthority(older, DeploymentArtifact.ParseDataPlaneAuthority(olderBytes, Node.Value)).ShouldBeFalse();
|
||||
coordinator.Complete(older, topologySucceeded: true).ShouldBeFalse();
|
||||
authority.Current.GenerationId.ShouldBe(newerGeneration);
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
coordinator.Complete(newer, topologySucceeded: true).ShouldBeTrue();
|
||||
coordinator.Current.ShouldNotBeNull().Serving.AuthorityEpoch.ShouldBe(newerGeneration);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Failed_topology_never_publishes_the_staged_catalog_or_rolls_back_revocation()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var first = Prepare(coordinator, Artifact());
|
||||
coordinator.Complete(first, topologySucceeded: true).ShouldBeTrue();
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
|
||||
var next = Prepare(coordinator, Artifact(revoked: true));
|
||||
coordinator.Complete(next, topologySucceeded: false).ShouldBeFalse();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
coordinator.Complete(next, topologySucceeded: true).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Headless_fetch_apply_serves_an_authorized_local_catalog_without_a_mount()
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var acknowledgments = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acknowledgments.Ref);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
|
||||
acknowledgments.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
var catalog = coordinator.Current.ShouldNotBeNull();
|
||||
catalog.IsActive.ShouldBeTrue();
|
||||
catalog.Serving.NodeId.ShouldBe(Node.Value);
|
||||
catalog.Serving.Incarnation.ShouldBe(BootIdentity.Incarnation);
|
||||
catalog.Serving.CatalogEpoch.ShouldBeGreaterThan(0);
|
||||
catalog.Serving.AuthorityEpoch.ShouldBeGreaterThan(0);
|
||||
|
||||
using var hub = HubTest.Create();
|
||||
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", () => coordinator.Current!.Serving,
|
||||
() => coordinator.Current?.IsActive == true, limits);
|
||||
var services = new LocalDataServices(() => coordinator.Current, hub,
|
||||
new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, hub.Clock), hub.Clock),
|
||||
capabilities, hub.Clock);
|
||||
var key = authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
var context = new DataAuthenticatedContext("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key),
|
||||
DateTimeOffset.UtcNow.AddMinutes(10), authority.Current.GenerationId);
|
||||
await using var connection = services.Create(context, new(DataTargetMode.Node, "cluster", Node.Value));
|
||||
var root = LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw);
|
||||
var page = await connection.BrowseAsync(new(root, null, null, Budget), TestContext.Current.CancellationToken);
|
||||
page.Status.ShouldBe(DataItemStatus.Good);
|
||||
page.Items.Select(x => x.BrowseName).ShouldContain("Plant");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_closes_the_old_catalog_before_creating_a_replacement_driver()
|
||||
{
|
||||
var firstBytes = Artifact();
|
||||
var nextBytes = Artifact(includeDriver: true);
|
||||
var fetcher = new MutableFetcher(firstBytes);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var acks = CreateTestProbe();
|
||||
var factory = new ObservingFactory(() => coordinator.Current?.IsActive == true);
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref, factory);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(firstBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
old.IsActive.ShouldBeTrue();
|
||||
|
||||
fetcher.Bytes = nextBytes;
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(nextBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
factory.Called.ShouldBeTrue();
|
||||
factory.CatalogWasActive.ShouldBeFalse();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Invalid_catalog_still_installs_independent_revocation_before_driver_reconciliation()
|
||||
{
|
||||
var firstBytes = Artifact();
|
||||
var badBytes = Artifact(revoked: true, includeDriver: true, invalidExport: true);
|
||||
var fetcher = new MutableFetcher(firstBytes);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var acks = CreateTestProbe();
|
||||
var factory = new ObservingFactory(() => authority.Current.FindUsableKey("peer-key", DateTime.UtcNow) is not null);
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref, factory);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(firstBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
fetcher.Bytes = badBytes;
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(badBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
factory.Called.ShouldBeTrue();
|
||||
factory.CatalogWasActive.ShouldBeFalse(); // The callback observes that the key is already revoked.
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Malformed_desired_artifact_closes_the_old_catalog_before_parsing()
|
||||
{
|
||||
var firstBytes = Artifact();
|
||||
var malformed = Encoding.UTF8.GetBytes("{bad-json");
|
||||
var fetcher = new MutableFetcher(firstBytes);
|
||||
var coordinator = NewCoordinator(new DataPlaneAuthorityState(), new CatalogActivation());
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(firstBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
old.IsActive.ShouldBeTrue();
|
||||
|
||||
fetcher.Bytes = malformed;
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(malformed), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Failed);
|
||||
coordinator.Current.ShouldBeNull();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_and_publish_actor_join_one_attempt_and_wait_for_successful_topology()
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var activation = new CatalogActivation();
|
||||
var coordinator = NewCoordinator(authority, activation);
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var sink = NullOpcUaAddressSpaceSink.Instance;
|
||||
var hooks = new OpcUaPublishActor.TestHooks { BeforeComposition = () => { entered.Set(); release.Wait(); } };
|
||||
var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
|
||||
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
|
||||
dataPlaneAuthority: authority, catalogCoordinator: coordinator));
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acks.Ref, publish: publish);
|
||||
try
|
||||
{
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
|
||||
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
||||
activation.Current.CatalogEpoch.ShouldBe(1);
|
||||
activation.Current.IsReady.ShouldBeFalse();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
release.Set();
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
activation.Current.CatalogEpoch.ShouldBe(1);
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
}
|
||||
finally { release.Set(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Role_transition_reuses_the_adjusted_catalog_and_does_not_freshen_the_cached_acquisition()
|
||||
{
|
||||
var role = "Primary";
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
|
||||
() => BootIdentity with { Role = role });
|
||||
var attempt = Prepare(coordinator, Artifact(includeDriver: true, includeTag: true));
|
||||
coordinator.Complete(attempt, topologySucceeded: true).ShouldBeTrue();
|
||||
var original = coordinator.Current.ShouldNotBeNull();
|
||||
var source = original.Nodes.Single(x => x.EntityKind == "RawTag").Source.ShouldNotBeNull();
|
||||
using var hub = HubTest.Create();
|
||||
var ticket = new SourceTicket(source, new SourceGeneration(1, 1));
|
||||
hub.TryBind(ticket).ShouldBeTrue();
|
||||
var timestamp = DateTimeOffset.Parse("2026-01-02T03:04:05Z");
|
||||
hub.TryReserveIngress(ticket, 512, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, timestamp, timestamp,
|
||||
coordinator.Serving, 7);
|
||||
if (!reservation!.TryCommit(sample, 7)) { sample.Dispose(); throw new InvalidOperationException(); }
|
||||
}
|
||||
hub.ProcessPending();
|
||||
using var before = hub.Read(ticket);
|
||||
before.Sample.ShouldNotBeNull();
|
||||
|
||||
role = "Secondary";
|
||||
var secondary = coordinator.Current.ShouldNotBeNull();
|
||||
secondary.Serving.Role.ShouldBe("Secondary");
|
||||
ReferenceEquals(secondary, coordinator.Current).ShouldBeTrue();
|
||||
ReferenceEquals(secondary.Nodes, original.Nodes).ShouldBeTrue();
|
||||
coordinator.Serving.ShouldBe(secondary.Serving);
|
||||
using var after = hub.Read(ticket);
|
||||
after.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
after.Sample.ShouldNotBeNull().SourceTimestampUtc.ShouldBe(timestamp);
|
||||
after.Sample!.Version.ShouldBe(7);
|
||||
after.ReceivedTimestamp.ShouldBe(before.ReceivedTimestamp);
|
||||
secondary.Serving.CatalogEpoch.ShouldBe(original.Serving.CatalogEpoch);
|
||||
secondary.Serving.AuthorityEpoch.ShouldBe(original.Serving.AuthorityEpoch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_rejects_a_catalog_stamped_with_a_different_serving_node()
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
|
||||
() => BootIdentity with { NodeId = "node-b" });
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acks.Ref);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
|
||||
var ack = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
(ack.Outcome == ApplyAckOutcome.Failed || ack.Degraded).ShouldBeTrue();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Expected_catalog_failure_is_degraded_and_same_revision_dispatch_retries(bool withPublisher)
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var fetcher = new MutableFetcher(bytes);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var activation = new CatalogActivation();
|
||||
var identityAvailable = false;
|
||||
var coordinator = new LocalCatalogCoordinator(activation, authority, () => Volatile.Read(ref identityAvailable)
|
||||
? BootIdentity : throw new InvalidOperationException("temporary provenance failure"));
|
||||
IActorRef? publish = null;
|
||||
if (withPublisher)
|
||||
{
|
||||
var sink = NullOpcUaAddressSpaceSink.Instance;
|
||||
publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
|
||||
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks: null,
|
||||
localNode: Node, dataPlaneAuthority: authority, catalogCoordinator: coordinator));
|
||||
}
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref, publish: publish);
|
||||
var revision = Revision(bytes);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var first = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
(first.Outcome == ApplyAckOutcome.Failed || first.Degraded).ShouldBeTrue();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
var epoch = activation.Current.CatalogEpoch;
|
||||
|
||||
Volatile.Write(ref identityAvailable, true);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var repaired = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
repaired.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
repaired.Degraded.ShouldBeFalse();
|
||||
fetcher.Calls.ShouldBe(2);
|
||||
activation.Current.CatalogEpoch.ShouldBeGreaterThan(epoch);
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Legacy_artifact_without_data_configuration_remains_clean(bool withCoordinator)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes("{\"DriverInstances\":[]}");
|
||||
var fetcher = new MutableFetcher(bytes);
|
||||
var acks = CreateTestProbe();
|
||||
var coordinator = withCoordinator ? NewCoordinator(new DataPlaneAuthorityState(), new CatalogActivation()) : null;
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: Node, ackRouter: acks.Ref,
|
||||
localRoles: new HashSet<string> { "driver" }, fetchAndCacheMode: true, artifactFetcher: fetcher,
|
||||
catalogCoordinator: coordinator));
|
||||
var revision = Revision(bytes);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var first = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
first.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
first.Degraded.ShouldBeFalse();
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var second = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
second.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
second.Degraded.ShouldBeFalse();
|
||||
fetcher.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(true, true)]
|
||||
[InlineData(false, false)]
|
||||
[InlineData(false, true)]
|
||||
public async Task Cache_and_restore_wait_for_subscription_work_before_sending_the_catalog_to_the_publisher(bool cacheBoot, bool fail)
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var deployment = DeploymentId.NewId();
|
||||
var revision = Revision(bytes);
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> db;
|
||||
IDeploymentArtifactCache? cache = null;
|
||||
if (cacheBoot)
|
||||
{
|
||||
db = new ThrowingDbFactory();
|
||||
cache = new BootCache(new(deployment.ToString(), revision.Value, bytes, DateTimeOffset.UtcNow));
|
||||
}
|
||||
else
|
||||
{
|
||||
db = NewInMemoryDbFactory();
|
||||
using var context = db.CreateDbContext();
|
||||
context.Deployments.Add(new Deployment { DeploymentId = deployment.Value, RevisionHash = revision.Value,
|
||||
Status = DeploymentStatus.Sealed, CreatedBy = "test", SealedAtUtc = DateTime.UtcNow, ArtifactBlob = bytes });
|
||||
context.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = Node.Value, DeploymentId = deployment.Value,
|
||||
Status = NodeDeploymentStatus.Applied, StartedAtUtc = DateTime.UtcNow });
|
||||
context.SaveChanges();
|
||||
}
|
||||
var catalog = NewCoordinator(new DataPlaneAuthorityState(), new CatalogActivation());
|
||||
var publish = CreateTestProbe();
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var cancellationToken = TestContext.Current.CancellationToken;
|
||||
catalog.BeforeSubscriptionApplyForTests = () =>
|
||||
{
|
||||
entered.Set();
|
||||
release.Wait(cancellationToken);
|
||||
if (fail) throw new InvalidOperationException("subscription work failed");
|
||||
};
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(db, Node, localRoles: new HashSet<string> { "driver" },
|
||||
deploymentArtifactCache: cache, opcUaPublishActor: publish.Ref, catalogCoordinator: catalog));
|
||||
try
|
||||
{
|
||||
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
||||
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
release.Set();
|
||||
if (fail)
|
||||
{
|
||||
await host.Ask<ActorIdentity>(new Identify("started"), PresenceBudget, cancellationToken);
|
||||
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
catalog.Current.ShouldBeNull();
|
||||
}
|
||||
else
|
||||
{
|
||||
var rebuild = publish.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(PresenceBudget,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
rebuild.Artifact.ShouldBe(bytes);
|
||||
rebuild.CatalogAttempt.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
finally { release.Set(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Direct_restore_uses_the_loaded_artifact_to_subscribe_the_real_deferred_driver_without_a_third_db_read()
|
||||
{
|
||||
var bytes = Artifact(includeDriver: true, includeTag: true);
|
||||
var deployment = DeploymentId.NewId();
|
||||
var revision = Revision(bytes);
|
||||
var underlying = NewInMemoryDbFactory();
|
||||
using (var context = underlying.CreateDbContext())
|
||||
{
|
||||
context.Deployments.Add(new Deployment { DeploymentId = deployment.Value, RevisionHash = revision.Value,
|
||||
Status = DeploymentStatus.Sealed, CreatedBy = "test", SealedAtUtc = DateTime.UtcNow, ArtifactBlob = bytes });
|
||||
context.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = Node.Value, DeploymentId = deployment.Value,
|
||||
Status = NodeDeploymentStatus.Applied, StartedAtUtc = DateTime.UtcNow });
|
||||
context.SaveChanges();
|
||||
}
|
||||
var db = new TwoReadDbFactory(underlying);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var catalog = NewCoordinator(authority, new CatalogActivation());
|
||||
using var hub = HubTest.Create(bytes: 1_000_000);
|
||||
var publisher = new SourceSamplePublisher(hub, () => catalog.Serving, "cluster");
|
||||
var factory = new RecordingSubscribableDriverFactory("Modbus");
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(db, Node, driverFactory: factory,
|
||||
localRoles: new HashSet<string> { "driver" }, sourcePublisher: publisher, catalogCoordinator: catalog));
|
||||
|
||||
await host.Ask<ActorIdentity>(new Identify("started"), PresenceBudget, TestContext.Current.CancellationToken);
|
||||
db.Calls.ShouldBe(2); // Bootstrap and artifact load; any third read would have thrown.
|
||||
catalog.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
var driver = factory.Created.ShouldHaveSingleItem();
|
||||
driver.LastSubscribedRefs.ShouldNotBeNull().ShouldContain("Plant/Driver/Device/Speed");
|
||||
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private static LocalCatalogCoordinator NewCoordinator(DataPlaneAuthorityState authority, CatalogActivation activation) =>
|
||||
new(activation, authority, () => BootIdentity);
|
||||
|
||||
private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, byte[] bytes)
|
||||
{
|
||||
var attempt = coordinator.BeginAttempt(Hash(bytes));
|
||||
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, Node.Value)).ShouldBeTrue();
|
||||
using var parsed = DeploymentArtifact.Open(bytes);
|
||||
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot(Node.Value)!).ShouldBeTrue();
|
||||
return attempt;
|
||||
}
|
||||
|
||||
private IActorRef NewHost(byte[] bytes, LocalCatalogCoordinator coordinator, IActorRef acks,
|
||||
IDriverFactory? factory = null, IActorRef? publish = null) =>
|
||||
NewHost(new MutableFetcher(bytes), coordinator, acks, factory, publish);
|
||||
|
||||
private IActorRef NewHost(MutableFetcher fetcher, LocalCatalogCoordinator coordinator, IActorRef acks,
|
||||
IDriverFactory? factory = null, IActorRef? publish = null) => Sys.ActorOf(DriverHostActor.Props(
|
||||
dbFactory: null, localNode: Node, ackRouter: acks, driverFactory: factory,
|
||||
localRoles: new HashSet<string> { "driver" }, fetchAndCacheMode: true, artifactFetcher: fetcher,
|
||||
opcUaPublishActor: publish, catalogCoordinator: coordinator));
|
||||
|
||||
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
private static RevisionHash Revision(byte[] bytes) => RevisionHash.Parse(Hash(bytes));
|
||||
|
||||
private static byte[] Artifact(bool revoked = false, bool includeDriver = false, bool invalidExport = false, bool includeTag = false)
|
||||
{
|
||||
var root = JsonNode.Parse("""
|
||||
{
|
||||
"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":3}],
|
||||
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
|
||||
"DriverInstances":[],"Devices":[],"TagGroups":[],"Tags":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
|
||||
"DataConnections":[],"RemoteNamespaceMappings":[],
|
||||
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":7}]
|
||||
}
|
||||
""")!.AsObject();
|
||||
root["ApiKeys"]![0]!["Enabled"] = !revoked;
|
||||
if (includeDriver)
|
||||
root["DriverInstances"]!.AsArray().Add(JsonNode.Parse("""
|
||||
{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}
|
||||
"""));
|
||||
if (includeTag)
|
||||
{
|
||||
root["Devices"]!.AsArray().Add(JsonNode.Parse("""
|
||||
{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}
|
||||
"""));
|
||||
root["Tags"]!.AsArray().Add(JsonNode.Parse("""
|
||||
{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":0,"TagConfig":"{}"}
|
||||
"""));
|
||||
}
|
||||
if (invalidExport) root["DataExports"]![0]!["RootEntityId"] = "missing";
|
||||
return Encoding.UTF8.GetBytes(root.ToJsonString());
|
||||
}
|
||||
|
||||
private sealed class MutableFetcher(byte[] bytes) : IDeploymentArtifactFetcher
|
||||
{
|
||||
private int _calls;
|
||||
public byte[] Bytes { get; set; } = bytes;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public Task<byte[]?> FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return Task.FromResult<byte[]?>(Bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingDbFactory : IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
public OtOpcUaConfigDbContext CreateDbContext() => throw new InvalidOperationException("ConfigDb unreachable");
|
||||
}
|
||||
|
||||
private sealed class TwoReadDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
private int _calls;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public OtOpcUaConfigDbContext CreateDbContext()
|
||||
{
|
||||
if (Interlocked.Increment(ref _calls) > 2) throw new InvalidOperationException("unexpected third ConfigDb read");
|
||||
return inner.CreateDbContext();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class BootCache(CachedDeploymentArtifact artifact) : IDeploymentArtifactCache
|
||||
{
|
||||
public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, byte[] bytes, CancellationToken ct = default) => Task.CompletedTask;
|
||||
public Task<CachedDeploymentArtifact?> GetCurrentAsync(string clusterId, CancellationToken ct = default) => Task.FromResult<CachedDeploymentArtifact?>(artifact);
|
||||
public Task<CachedDeploymentArtifact?> GetCurrentUnkeyedAsync(CancellationToken ct = default) => Task.FromResult<CachedDeploymentArtifact?>(artifact);
|
||||
}
|
||||
|
||||
private sealed class ObservingFactory(Func<bool> observe) : IDriverFactory
|
||||
{
|
||||
public bool Called { get; private set; }
|
||||
public bool CatalogWasActive { get; private set; }
|
||||
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
|
||||
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
|
||||
{
|
||||
Called = true;
|
||||
CatalogWasActive = observe();
|
||||
return null; // The real host still creates its normal stub child.
|
||||
}
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
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("Feature", "GrpcData")]
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataIngressOverflowTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(true, true)]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(false, true)]
|
||||
[InlineData(false, false)]
|
||||
public void Repartition_retains_old_source_quota_until_the_last_owner_releases_it(bool holdRead, bool limitSourceCount)
|
||||
{
|
||||
// Both keys are large enough that source metadata, rather than just a scalar lease,
|
||||
// determines admission under the byte-limited cases.
|
||||
using var hub = HubTest.Create(partitions: 1, bytes: limitSourceCount ? 100_000 : 10_000,
|
||||
maxSources: limitSourceCount ? 1 : 10);
|
||||
var old = HubTest.Ticket("driver", new string('a', 2000));
|
||||
var replacement = HubTest.Ticket("driver", new string('b', 2000));
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
|
||||
using var heldRead = holdRead ? hub.Read(old) : null;
|
||||
IIngressReservation? heldReservation = null;
|
||||
if (holdRead) heldRead!.IsValid.ShouldBeTrue();
|
||||
else hub.TryReserveIngress(old, 288, out heldReservation).ShouldBeTrue();
|
||||
using (heldReservation)
|
||||
{
|
||||
hub.Repartition(2);
|
||||
if (holdRead) heldRead!.IsValid.ShouldBeFalse();
|
||||
hub.Resources.RetainedBytes.ShouldBeGreaterThan(4_000);
|
||||
hub.TryBind(replacement).ShouldBeFalse();
|
||||
|
||||
if (holdRead) heldRead!.Dispose();
|
||||
else
|
||||
{
|
||||
using var stale = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2);
|
||||
heldReservation!.TryCommit(stale, 2).ShouldBeFalse();
|
||||
}
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(replacement).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repartition_retires_the_old_ticket_even_after_its_partition_is_disposed()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 10);
|
||||
var old = HubTest.Ticket("driver", new string('a', 1000));
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.Repartition(2);
|
||||
hub.TryBind(old).ShouldBeFalse();
|
||||
hub.TryReserveIngress(old, 288, out _).ShouldBeFalse();
|
||||
var fresh = new SourceTicket(old.Key, old.Generation);
|
||||
hub.TryBind(fresh).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removed_source_churn_reclaims_bounded_registry_without_resurrecting_old_tickets()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, bytes: 100_000, maxSources: 2);
|
||||
var retired = new List<SourceTicket>();
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
var source = HubTest.Ticket("driver", $"churn-{i}");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
HubTest.Publish(hub, source, 1, i);
|
||||
hub.ProcessPending();
|
||||
hub.TryRemove(source, 2).ShouldBeTrue();
|
||||
hub.ProcessPending(); // worker has an opportunity to reclaim safe tombstones
|
||||
retired.Add(source);
|
||||
}
|
||||
foreach (var old in retired)
|
||||
hub.TryReserveIngress(old, 288, out _).ShouldBeFalse();
|
||||
hub.TryBind(HubTest.Ticket("driver", "live")).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reclaimed_binding_cannot_be_repaired_or_target_a_fresh_binding_with_the_same_generation()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var old = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var oldRead = hub.Read(old);
|
||||
hub.TryRemove(old, 2).ShouldBeTrue();
|
||||
oldRead.IsValid.ShouldBeFalse();
|
||||
oldRead.Dispose();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(old).ShouldBeFalse(); // even while no replacement source exists
|
||||
var replacement = new SourceTicket(old.Key, old.Generation);
|
||||
hub.TryBind(replacement).ShouldBeTrue();
|
||||
hub.TryGetCurrentTicket(old.Key, out var resolved).ShouldBeTrue();
|
||||
resolved.ShouldBe(replacement);
|
||||
resolved.ShouldNotBe(old);
|
||||
HubTest.Publish(hub, replacement, 1, 2);
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(old).ShouldBeFalse();
|
||||
hub.TryReserveIngress(old, 288, out _).ShouldBeFalse();
|
||||
hub.Invalidate(old, "late callback");
|
||||
using var current = hub.Read(replacement);
|
||||
current.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
current.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reclamation_waits_for_snapshot_references_to_release()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var old = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([old], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
hub.TryRemove(old, 2).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
var other = HubTest.Ticket("driver", "other");
|
||||
hub.TryBind(other).ShouldBeFalse();
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
snapshot.Dispose();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(other).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reclamation_waits_for_disposal_of_outstanding_ingress_and_read_leases()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var old = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
var read = hub.Read(old);
|
||||
hub.TryReserveIngress(old, 288, out var reservation).ShouldBeTrue();
|
||||
hub.TryRemove(old, 2).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
var other = HubTest.Ticket("driver", "other");
|
||||
hub.TryBind(other).ShouldBeFalse();
|
||||
read.Dispose();
|
||||
reservation!.Dispose();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(other).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registry_overflow_invalidates_in_constant_producer_work_and_defers_cache_cleanup()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, bytes: 100_000, maxSources: 32);
|
||||
var sources = Enumerable.Range(0, 32).Select(i => HubTest.Ticket("driver", $"tag-{i}")).ToArray();
|
||||
foreach (var source in sources)
|
||||
{
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
}
|
||||
var chargedBeforeOverflow = hub.Resources.RetainedBytes;
|
||||
hub.TryBind(HubTest.Ticket("driver", "overflow")).ShouldBeFalse();
|
||||
// No source cache was scanned or released by the producer's failed bind.
|
||||
hub.Resources.RetainedBytes.ShouldBe(chargedBeforeOverflow);
|
||||
hub.ProcessPending();
|
||||
hub.Resources.RetainedBytes.ShouldBeLessThan(chargedBeforeOverflow);
|
||||
foreach (var source in sources)
|
||||
{
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deferred_partition_cleanup_preserves_a_fresh_post_overflow_sample()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.InvalidatePartitionFor(source.Key, "bounded recovery overflow");
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
read.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admission_and_retirement_do_not_wait_for_a_busy_partition()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var cancellationToken = TestContext.Current.CancellationToken;
|
||||
var owner = Task.Run(() => hub.WithPartitionLockForTest(source.Key, () => { entered.Set(); release.Wait(cancellationToken); }), cancellationToken);
|
||||
try
|
||||
{
|
||||
entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue();
|
||||
var producer = Task.Run(() =>
|
||||
{
|
||||
hub.TryReserveIngress(source, 288, out _).ShouldBeFalse();
|
||||
hub.TryRemove(source, 2).ShouldBeFalse();
|
||||
hub.IsTicketCurrentNonBlocking(source).ShouldBeFalse();
|
||||
}, cancellationToken);
|
||||
await producer.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
release.Set();
|
||||
await owner.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
|
||||
}
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void In_flight_copy_cannot_restore_readiness_after_an_overflow_fence()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryReserveIngress(source, 288, out var oldReservation).ShouldBeTrue();
|
||||
hub.Invalidate(source, "overflow");
|
||||
HubTest.Publish(hub, source, 3, 3);
|
||||
hub.ProcessPending();
|
||||
using (oldReservation!)
|
||||
using (var old = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2))
|
||||
oldReservation!.TryCommit(old, 2).ShouldBeFalse();
|
||||
using var current = hub.Read(source);
|
||||
current.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
current.Sample!.Value.GetScalar().ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Understated_reservation_is_rejected_without_transferring_sample_ownership()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryReserveIngress(source, 287, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
using (var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, null, HubTest.Serving, 1))
|
||||
{
|
||||
reservation!.TryCommit(sample, 1).ShouldBeFalse();
|
||||
sample.Value.GetScalar().ShouldBe(7); // failed commit leaves ownership with caller
|
||||
}
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Source_registry_reuses_capacity_after_tombstone_cleanup()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var first = HubTest.Ticket("driver", "first");
|
||||
var second = HubTest.Ticket("driver", "second");
|
||||
HubTest.BindAndPublish(hub, first, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryRemove(first, 2).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(second).ShouldBeTrue();
|
||||
hub.TryGetCurrentTicket(first.Key, out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Admission_rejects_before_copy_and_synchronously_invalidates_previously_good_cache()
|
||||
{
|
||||
using var hub = HubTest.Create(bytes: 1700);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 7);
|
||||
hub.ProcessPending();
|
||||
var copied = false;
|
||||
if (hub.TryReserveIngress(source, 288, out var reservation))
|
||||
{
|
||||
using (reservation!) copied = true; // production copies only after successful admission
|
||||
}
|
||||
copied.ShouldBeFalse();
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
read.Status.ShouldNotBe(DataItemStatus.Good);
|
||||
// Recreating a consumer cannot turn the old cache into a fresh Good snapshot.
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!) snapshot!.Items[source].Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Abandoned_reservation_releases_global_quota_exactly_once()
|
||||
{
|
||||
using var hub = HubTest.Create(bytes: 1700);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
var before = hub.Resources.RetainedBytes;
|
||||
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBeGreaterThan(before);
|
||||
reservation!.Dispose();
|
||||
reservation.Dispose();
|
||||
hub.Resources.RetainedBytes.ShouldBe(before);
|
||||
hub.TryReserveIngress(source, 288, out var replacement).ShouldBeTrue();
|
||||
replacement!.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dirty_table_exhaustion_invalidates_partition_and_resets_existing_consumers()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, ingress: 1, dirty: 1);
|
||||
var a = HubTest.Ticket("driver", "a");
|
||||
var b = HubTest.Ticket("driver", "b");
|
||||
var c = HubTest.Ticket("driver", "c");
|
||||
foreach (var source in new[] { a, b, c })
|
||||
{
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
}
|
||||
hub.TryCaptureSnapshot([a, b, c], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
HubTest.Publish(hub, a, 2, 2); // fills ingress
|
||||
HubTest.Publish(hub, b, 2, 2); // fills the one-entry coalescing table
|
||||
var admitted = hub.TryReserveIngress(c, 288, out var reservation);
|
||||
if (admitted)
|
||||
{
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2);
|
||||
var committed = reservation!.TryCommit(sample, 2);
|
||||
if (!committed) sample.Dispose();
|
||||
committed.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
foreach (var source in new[] { a, b, c })
|
||||
{
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
hub.ProcessPending();
|
||||
// Only a fresh retained sample after invalidation may restore readiness.
|
||||
using var stale = hub.Read(c);
|
||||
stale.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Status_control_overtaking_queued_value_never_resurrects_good_quality()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.TryPublishStatus(source, 3, 0x80310000u, null, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
if (read.Sample is not null) read.Sample.StatusCode.ShouldBe(0x80310000u);
|
||||
else read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void New_dirty_generation_is_seen_after_a_previous_delta_was_consumed()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
snapshot!.TryReadDelta(source, out var first).ShouldBeTrue();
|
||||
using (first!) first!.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
HubTest.Publish(hub, source, 3, 3);
|
||||
hub.ProcessPending();
|
||||
snapshot.TryReadDelta(source, out var second).ShouldBeTrue();
|
||||
using (second!) second!.Sample!.Value.GetScalar().ShouldBe(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataLocalConnectionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var result = await connection.GetMetadataAsync(new([fixture.Raw with { Subject = "bootstrap" },
|
||||
fixture.Uns with { Subject = fixture.Raw.Subject }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
result[0].Status.ShouldBe(DataItemStatus.Good);
|
||||
result[0].Value!.View.ShouldBe(fixture.Raw);
|
||||
result[1].Status.ShouldBe(DataItemStatus.Denied);
|
||||
result[1].Value.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Browse_continuation_is_bound_to_the_original_query_and_retains_bounded_scan_progress()
|
||||
{
|
||||
using var fixture = new LocalDataFixture(additionalRawNodes: 2);
|
||||
await using var connection = fixture.Connection();
|
||||
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
|
||||
var page = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken);
|
||||
page.Items.Count.ShouldBe(1);
|
||||
page.Complete.ShouldBeFalse();
|
||||
page.Continuation.ShouldNotBeNull();
|
||||
var changed = await connection.BrowseAsync(new(fixture.Root, "changed", page.Continuation, budget), TestContext.Current.CancellationToken);
|
||||
changed.Status.ShouldBe(DataItemStatus.InvalidContinuation);
|
||||
var tampered = await connection.BrowseAsync(new(fixture.Root, null, page.Continuation + "!", budget), TestContext.Current.CancellationToken);
|
||||
tampered.Status.ShouldBe(DataItemStatus.InvalidContinuation);
|
||||
var next = await connection.BrowseAsync(new(fixture.Root, null, page.Continuation, budget), TestContext.Current.CancellationToken);
|
||||
next.Status.ShouldBe(DataItemStatus.Good);
|
||||
next.Items.ShouldHaveSingleItem().View.ShouldNotBe(page.Items[0].View);
|
||||
var filtered = await connection.BrowseAsync(new(fixture.Root, "absent", null, budget), TestContext.Current.CancellationToken);
|
||||
filtered.Items.ShouldBeEmpty();
|
||||
filtered.Complete.ShouldBeFalse("filtering still scans only the admitted page window");
|
||||
filtered.Continuation.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Direct_local_api_browses_and_reads_without_a_namespace_mount()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var browse = await connection.BrowseAsync(new(fixture.Root, null, null, LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
browse.Status.ShouldBe(DataItemStatus.Good);
|
||||
browse.Items.ShouldHaveSingleItem().View.ShouldBe(fixture.Raw);
|
||||
var metadata = await connection.GetMetadataAsync(new([fixture.Raw], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
metadata.ShouldHaveSingleItem().Value!.ValueKind.ShouldBe(DataValueKind.Int32);
|
||||
fixture.Publish(42);
|
||||
var results = await connection.ReadAsync(new([new("first", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using var result = results.ShouldHaveSingleItem();
|
||||
result.CorrelationId.ShouldBe("first");
|
||||
result.Status.ShouldBe(DataItemStatus.Good);
|
||||
result.Sample!.Value.GetScalar().ShouldBe(42);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Unwired_write_and_subscription_ports_are_not_advertised_or_reported_successful()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var capabilities = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, TestContext.Current.CancellationToken);
|
||||
(capabilities.Operations & (DataOperations.Write | DataOperations.Subscribe)).ShouldBe(DataOperations.None);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 5);
|
||||
var results = await connection.WriteAsync(new([new("write", "operation", fixture.Raw, value, 1,
|
||||
fixture.Serving.Incarnation, TimeSpan.FromSeconds(1))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
results.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.SubscribeAsync(TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Factory_rejects_wrong_target_and_forged_authenticated_context()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
Should.Throw<ArgumentException>(() => fixture.Services.Create(fixture.Context,
|
||||
new(DataTargetMode.Node, "other-cluster", "node-a")));
|
||||
Should.Throw<UnauthorizedAccessException>(() => fixture.Services.Create(fixture.Context with { PrincipalId = "forged" },
|
||||
new(DataTargetMode.Node, "cluster", "node-a")));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class LocalDataFixture : IDisposable
|
||||
{
|
||||
internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000);
|
||||
internal readonly ManualTimeProvider Clock = new();
|
||||
internal readonly ServingIdentity Serving = new("node-a", "serving-1", "Primary", 1, 1);
|
||||
internal readonly DataPlaneAuthorityState Authority = new();
|
||||
internal readonly CatalogActivation Activation = new();
|
||||
internal readonly PartitionedSampleHub Hub;
|
||||
internal readonly SourceTicket Ticket = new(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", "node-a", "serving-1"), new(1, 1));
|
||||
internal readonly DataView Root = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant"), DataRealm.Raw, null, 0, "Plant");
|
||||
internal readonly DataView Raw = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant/Driver/Device/Speed"), DataRealm.Raw, null, 0, "Plant/Driver/Device/Speed");
|
||||
internal readonly DataView Uns = new(new("cluster", "https://zb.com/otopcua/uns", "string", "Area/Line/Equipment/Speed"), DataRealm.Uns, null, 0, "Area/Line/Equipment/Speed");
|
||||
internal readonly LocalDataServices Services;
|
||||
internal readonly LocalExportCatalog Catalog;
|
||||
internal readonly DataAuthenticatedContext Context;
|
||||
|
||||
internal LocalDataFixture(int additionalRawNodes = 0)
|
||||
{
|
||||
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 Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
||||
var epoch = Activation.Begin("first");
|
||||
Activation.AuthorityInstalled(epoch, Authority.Current.GenerationId);
|
||||
Activation.Complete(epoch, true);
|
||||
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
|
||||
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
|
||||
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 nodes = new List<LocalDataNode>
|
||||
{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)};
|
||||
for (var i = 0; i < additionalRawNodes; i++)
|
||||
{
|
||||
var view = Raw with { Address = Raw.Address with { Identifier = Raw.Address.Identifier + i }, Subject = Raw.Subject + i };
|
||||
nodes.Add(new("RawTag", "extra-" + i, rawMetadata with { View = view, BrowseName = "Speed" + i },
|
||||
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed" + i] }, Root, Ticket.Key));
|
||||
}
|
||||
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 }]);
|
||||
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,
|
||||
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock);
|
||||
}
|
||||
|
||||
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", "node-a"));
|
||||
internal void Publish(int value, bool beforeActivation = false)
|
||||
{
|
||||
using var owned = DataValue.FromScalar(DataValueKind.Int32, value);
|
||||
Hub.TryReserveIngress(Ticket, owned.EstimatedRetainedBytes, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(owned.Retain(), 0x00000400u, null, Clock.GetUtcNow(),
|
||||
beforeActivation ? Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 } : Serving, 1);
|
||||
if (!reservation!.TryCommit(sample, 1)) { sample.Dispose(); throw new InvalidOperationException(); }
|
||||
}
|
||||
Hub.ProcessPending();
|
||||
}
|
||||
public void Dispose() => Hub.Dispose();
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataLocalExportCatalogTests
|
||||
{
|
||||
[Fact]
|
||||
public void Deployed_origin_catalog_uses_actual_Uns_folder_ids_and_one_backing_source_for_both_realms()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var snapshot = new DraftSnapshot
|
||||
{
|
||||
GenerationId = 1, ClusterId = "cluster",
|
||||
ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }],
|
||||
RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }],
|
||||
DriverInstances = [new() { DriverInstanceId = "driver", ClusterId = "cluster", RawFolderId = "folder", Name = "Driver", DriverType = "ModbusTcp", DriverConfig = "{}" }],
|
||||
Devices = [new() { DeviceId = "device", DriverInstanceId = "driver", Name = "Device", DeviceConfig = "{}" }],
|
||||
Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" }],
|
||||
UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }],
|
||||
UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }],
|
||||
Equipment = [new() { EquipmentId = "equipment-id", UnsLineId = "line-id", Name = "Equipment", MachineCode = "E" }],
|
||||
UnsTagReferences = [new() { UnsTagReferenceId = "reference", EquipmentId = "equipment-id", TagId = "tag" }],
|
||||
DataExports = [new() { DataExportId = "raw", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw,
|
||||
RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read },
|
||||
new() { DataExportId = "uns", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns,
|
||||
RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read }]
|
||||
};
|
||||
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
|
||||
var raw = catalog.Nodes.Single(x => x.EntityKind == "RawTag");
|
||||
var uns = catalog.Nodes.Single(x => x.EntityKind == "UnsTagReference");
|
||||
raw.Source.ShouldBe(uns.Source);
|
||||
raw.Source.ShouldBe(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", "node-a", "serving-1"));
|
||||
var area = catalog.Nodes.Single(x => x.EntityKind == "UnsArea");
|
||||
area.Metadata.View.Address.Identifier.ShouldBe("area-id");
|
||||
area.Scope.Segments.ShouldBe(["Area"]);
|
||||
uns.Metadata.View.Address.Identifier.ShouldBe("Area/Line/Equipment/Speed");
|
||||
catalog.Nodes.ShouldNotContain(x => x.EntityKind == "RemoteNamespaceMapping");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void Catalog_rejects_projected_or_foreign_nodes_as_origin_local_exports(bool projected)
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var valid = fixture.Catalog.Nodes.First();
|
||||
var invalidView = projected
|
||||
? valid.Metadata.View with { MappingId = "remote", MappingRevision = 1 }
|
||||
: valid.Metadata.View with { Address = valid.Metadata.View.Address with { OriginClusterId = "foreign" } };
|
||||
var invalid = valid with { Metadata = valid.Metadata with { View = invalidView } };
|
||||
Should.Throw<ArgumentException>(() => new LocalExportCatalog("cluster", fixture.Serving,
|
||||
fixture.Activation.CaptureAuthority(), [invalid], []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Catalog_token_is_invalidated_by_a_new_desired_revision()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Catalog.IsActive.ShouldBeTrue();
|
||||
fixture.Activation.Begin("next");
|
||||
fixture.Catalog.IsActive.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Catalog_metadata_and_read_batch_limits_are_checked_before_response_allocation()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
|
||||
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => connection.GetMetadataAsync(new([fixture.Raw, fixture.Uns], budget), TestContext.Current.CancellationToken));
|
||||
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => connection.ReadAsync(new([new("a", fixture.Raw, null), new("b", fixture.Uns, null)], budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataPartitionTests
|
||||
{
|
||||
[Fact]
|
||||
public void Retiring_producer_fences_all_its_sources_and_existing_snapshots_immediately()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var first = HubTest.Ticket("driver", "first");
|
||||
var second = HubTest.Ticket("driver", "second");
|
||||
var independent = HubTest.Ticket("other", "tag");
|
||||
var fence = new ProducerFence(1);
|
||||
hub.TryBind(first, fence).ShouldBeTrue();
|
||||
hub.TryBind(second, fence).ShouldBeTrue();
|
||||
HubTest.Publish(hub, first, 1, 10);
|
||||
HubTest.Publish(hub, second, 1, 20);
|
||||
HubTest.BindAndPublish(hub, independent, 1, 30);
|
||||
hub.ProcessPending();
|
||||
using var captured = hub.Read(first);
|
||||
captured.IsValid.ShouldBeTrue();
|
||||
hub.TryCaptureSnapshot([first, second], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
fence.Retire();
|
||||
captured.IsValid.ShouldBeFalse();
|
||||
hub.IsTicketCurrentNonBlocking(first).ShouldBeFalse();
|
||||
hub.TryGetCurrentTicket(second.Key, out _).ShouldBeFalse();
|
||||
using var rejected = hub.Read(first);
|
||||
rejected.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
hub.TryRemove(first, 2).ShouldBeTrue(); // closed producer still permits deferred tombstone cleanup
|
||||
using var unaffected = hub.Read(independent);
|
||||
unaffected.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
unaffected.Sample!.Value.GetScalar().ShouldBe(30);
|
||||
hub.TryBind(first, new ProducerFence(1)).ShouldBeFalse();
|
||||
var replacement = new SourceTicket(first.Key, new SourceGeneration(2, 1));
|
||||
hub.TryBind(replacement, new ProducerFence(2)).ShouldBeTrue();
|
||||
HubTest.Publish(hub, replacement, 1, 40);
|
||||
hub.ProcessPending();
|
||||
using var rebound = hub.Read(replacement);
|
||||
rebound.Sample!.Value.GetScalar().ShouldBe(40);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retained_read_validity_survives_new_values_but_not_source_invalidation_or_disposal()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
var other = HubTest.Ticket("driver", "other");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
HubTest.BindAndPublish(hub, other, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
read.IsValid.ShouldBeTrue();
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
hub.Invalidate(other, "unrelated source");
|
||||
read.IsValid.ShouldBeTrue();
|
||||
read.Sample!.Value.GetScalar().ShouldBe(1);
|
||||
hub.Invalidate(source, "source overload");
|
||||
read.IsValid.ShouldBeFalse();
|
||||
read.Dispose();
|
||||
read.IsValid.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retained_read_validity_tracks_partition_reset_removal_and_repartition()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var beforeReset = hub.Read(source);
|
||||
hub.InvalidatePartitionFor(source.Key, "overload");
|
||||
beforeReset.IsValid.ShouldBeFalse();
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
using var beforeRemove = hub.Read(source);
|
||||
beforeRemove.IsValid.ShouldBeTrue();
|
||||
hub.TryRemove(source, 3).ShouldBeTrue();
|
||||
beforeRemove.IsValid.ShouldBeFalse();
|
||||
var next = new SourceTicket(source.Key, new SourceGeneration(1, 2));
|
||||
hub.TryBind(next).ShouldBeTrue();
|
||||
HubTest.Publish(hub, next, 1, 3);
|
||||
hub.ProcessPending();
|
||||
using var beforeRepartition = hub.Read(next);
|
||||
beforeRepartition.IsValid.ShouldBeTrue();
|
||||
hub.Repartition(2);
|
||||
beforeRepartition.IsValid.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Quiet_initial_acquisition_is_retained_before_catalog_activation_without_inventing_epochs()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "quiet");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var serving = HubTest.Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 };
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 23), 0, null, null, serving, 1);
|
||||
reservation!.TryCommit(sample, 1).ShouldBeTrue();
|
||||
}
|
||||
hub.ProcessPending();
|
||||
using var acquisition = hub.Read(source);
|
||||
acquisition.Sample!.Value.GetScalar().ShouldBe(23);
|
||||
acquisition.Sample.Serving.CatalogEpoch.ShouldBe(0);
|
||||
acquisition.Sample.Serving.AuthorityEpoch.ShouldBe(0);
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => acquisition.Sample.Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Views_share_the_backing_sample_but_distinct_acquisitions_and_replicas_do_not()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver-a", "tag");
|
||||
var otherAcquisition = HubTest.Ticket("driver-b", "tag");
|
||||
var otherReplica = HubTest.Ticket("driver-a", "tag", "node-b");
|
||||
HubTest.BindAndPublish(hub, source, 1, 42);
|
||||
hub.TryBind(otherAcquisition).ShouldBeTrue();
|
||||
hub.TryBind(otherReplica).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
|
||||
// Both view descriptors resolve to the same explicit catalog source; a view is never a cache key.
|
||||
var raw = new DataView(HubTest.Address, DataRealm.Raw, null, 0, "raw/tag");
|
||||
var uns = new DataView(HubTest.Address, DataRealm.Uns, null, 0, "uns/tag");
|
||||
raw.Realm.ShouldNotBe(uns.Realm);
|
||||
using var rawRead = hub.Read(source);
|
||||
using var unsRead = hub.Read(source);
|
||||
using var acquisitionRead = hub.Read(otherAcquisition);
|
||||
using var replicaRead = hub.Read(otherReplica);
|
||||
rawRead.Sample!.Value.GetScalar().ShouldBe(42);
|
||||
unsRead.Sample!.Value.GetScalar().ShouldBe(42);
|
||||
acquisitionRead.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
|
||||
replicaRead.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removal_fences_queued_values_and_rebind_rejects_old_ticket_without_harming_new_sample()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var first = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, first, 1, 10);
|
||||
hub.ProcessPending();
|
||||
HubTest.Publish(hub, first, 2, 20); // remains queued while the removal is admitted
|
||||
hub.TryRemove(first, 3).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using (var removed = hub.Read(first)) removed.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
hub.TryGetCurrentTicket(first.Key, out _).ShouldBeFalse();
|
||||
|
||||
var next = new SourceTicket(first.Key, new SourceGeneration(1, 2));
|
||||
hub.TryBind(next).ShouldBeTrue();
|
||||
hub.TryGetCurrentTicket(next.Key, out var resolved).ShouldBeTrue();
|
||||
resolved.ShouldBe(next);
|
||||
HubTest.Publish(hub, next, 4, 30);
|
||||
hub.ProcessPending();
|
||||
hub.Invalidate(first, "late callback");
|
||||
hub.TryReserveIngress(first, 288, out _).ShouldBeFalse();
|
||||
using var current = hub.Read(next);
|
||||
current.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
current.Sample!.Value.GetScalar().ShouldBe(30);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Status_is_ordered_and_retains_payload_without_manufacturing_a_good_initial_sample()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryPublishStatus(source, 1, 0x80000000u, null, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using (var initial = hub.Read(source))
|
||||
{
|
||||
initial.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
initial.Sample.ShouldBeNull();
|
||||
}
|
||||
HubTest.Publish(hub, source, 2, 12);
|
||||
hub.ProcessPending();
|
||||
var timestamp = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
hub.TryPublishStatus(source, 3, 0x80310001u, timestamp, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var status = hub.Read(source);
|
||||
status.Sample!.Value.GetScalar().ShouldBe(12);
|
||||
status.Sample.StatusCode.ShouldBe(0x80310001u);
|
||||
status.Sample.SourceTimestampUtc.ShouldBe(timestamp);
|
||||
status.Sample.ServerTimestampUtc.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Synthetic_status_preserves_original_acquisition_timestamps()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
var sourceTime = new DateTimeOffset(2026, 2, 1, 2, 3, 4, TimeSpan.Zero);
|
||||
var serverTime = sourceTime.AddMilliseconds(37);
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 12), 0,
|
||||
sourceTime, serverTime, HubTest.Serving, 1);
|
||||
reservation!.TryCommit(sample, 1).ShouldBeTrue();
|
||||
}
|
||||
hub.ProcessPending();
|
||||
hub.TryPublishStatus(source, 2, 0x80310000u, null, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
read.Sample!.Value.GetScalar().ShouldBe(12);
|
||||
read.Sample.StatusCode.ShouldBe(0x80310000u);
|
||||
read.Sample.SourceTimestampUtc.ShouldBe(sourceTime);
|
||||
read.Sample.ServerTimestampUtc.ShouldBe(serverTime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repartition_resets_existing_snapshots_and_does_not_make_old_values_fresh()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 42);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
hub.Repartition(3);
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class HubTest
|
||||
{
|
||||
internal static readonly DataAddress Address = new("cluster", "urn:raw", "string", "tag");
|
||||
internal static readonly DataBudget Budget = new(TimeSpan.FromMinutes(1), 100, 100_000);
|
||||
internal static readonly ServingIdentity Serving = new("node-a", "serving-1", "Primary", 1, 1);
|
||||
|
||||
internal static PartitionedSampleHub Create(int partitions = 2, long bytes = 10_000,
|
||||
int ingress = 10, int dirty = 10, TimeProvider? clock = null, int maxSources = 100) =>
|
||||
new(new DataResourceLimits
|
||||
{
|
||||
PartitionCount = partitions, MaxRetainedBytes = bytes, MaxTrackedSources = maxSources,
|
||||
MaxIngressItemsPerPartition = ingress, MaxDirtySourcesPerPartition = dirty,
|
||||
MaxControlItemsPerPartition = 10, MaxSnapshotItems = 100,
|
||||
MaxSnapshotBytes = 10_000, MaxSnapshotCatchUpItems = 1,
|
||||
MaxSnapshotLifetime = TimeSpan.FromMinutes(1)
|
||||
}, clock ?? new ManualTimeProvider(), autoDrain: false);
|
||||
|
||||
internal static SourceTicket Ticket(string driver, string tag, string node = "node-a") =>
|
||||
new(new BackingSourceKey("cluster", "driver", $"{driver.Length}:{driver}{tag.Length}:{tag}", node, "serving-1"),
|
||||
new SourceGeneration(1, 1));
|
||||
|
||||
internal static void BindAndPublish(PartitionedSampleHub hub, SourceTicket ticket, long version, int value)
|
||||
{
|
||||
hub.TryBind(ticket).ShouldBeTrue();
|
||||
Publish(hub, ticket, version, value);
|
||||
}
|
||||
|
||||
internal static void Publish(PartitionedSampleHub hub, SourceTicket ticket, long version, int value)
|
||||
{
|
||||
hub.TryReserveIngress(ticket, 288, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var serving = Serving with { NodeId = ticket.Key.ServingNodeId, Incarnation = ticket.Key.ServingIncarnation };
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, value), 0, null, null, serving, version);
|
||||
if (!reservation!.TryCommit(sample, version)) { sample.Dispose(); throw new InvalidOperationException("Commit rejected"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
using Akka.Actor;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P04")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataSampleOwnershipTests : RuntimeActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public async Task Single_callback_copies_bytes_before_the_producer_reuses_them()
|
||||
{
|
||||
var driver = new CallbackDriver();
|
||||
var parent = CreateTestProbe();
|
||||
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
||||
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver), TestContext.Current.CancellationToken);
|
||||
await Subscribe(actor, driver);
|
||||
|
||||
var bytes = new byte[] { 1, 2, 3 };
|
||||
driver.Fire("source", new DataValueSnapshot(bytes, OpcUaStatus.Good, null, null));
|
||||
Array.Fill(bytes, (byte)99);
|
||||
|
||||
var item = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(
|
||||
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Items.Single();
|
||||
item.Value.ShouldBeOfType<byte[]>().ShouldBe(new byte[] { 1, 2, 3 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Batch_callback_copies_the_collection_and_each_mutable_array()
|
||||
{
|
||||
var driver = new BatchCallbackDriver();
|
||||
var parent = CreateTestProbe();
|
||||
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
||||
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver), TestContext.Current.CancellationToken);
|
||||
await Subscribe(actor, driver);
|
||||
|
||||
var numbers = new[] { 10, 20 };
|
||||
var bytes = new byte[] { 4, 5 };
|
||||
var items = new[]
|
||||
{
|
||||
new DataChangeItem("numbers", new DataValueSnapshot(numbers, OpcUaStatus.Good, null, null)),
|
||||
new DataChangeItem("bytes", new DataValueSnapshot(bytes, OpcUaStatus.Good, null, null)),
|
||||
};
|
||||
driver.Fire(items);
|
||||
numbers[0] = 999;
|
||||
bytes[0] = 99;
|
||||
items[1] = new DataChangeItem("replacement", new DataValueSnapshot(0, OpcUaStatus.Good, null, null));
|
||||
|
||||
var batch = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(
|
||||
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
batch.Items.Count.ShouldBe(2);
|
||||
batch.Items[0].Value.ShouldBeOfType<int[]>().ShouldBe(new[] { 10, 20 });
|
||||
batch.Items[1].FullReference.ShouldBe("bytes");
|
||||
batch.Items[1].Value.ShouldBeOfType<byte[]>().ShouldBe(new byte[] { 4, 5 });
|
||||
}
|
||||
|
||||
private async Task Subscribe(IActorRef actor, StubDriver driver)
|
||||
{
|
||||
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
||||
AwaitCondition(() => driver.InitializeCount > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
|
||||
new DriverInstanceActor.Subscribe(new[] { "source", "numbers", "bytes" }, TimeSpan.FromMilliseconds(100)),
|
||||
PresenceBudget, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private sealed class CallbackDriver : StubDriver, ISubscribable
|
||||
{
|
||||
private readonly StubHandle _handle = new();
|
||||
public event EventHandler<DataChangeEventArgs>? OnDataChange;
|
||||
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) => Task.FromResult<ISubscriptionHandle>(_handle);
|
||||
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
||||
public void Fire(string reference, DataValueSnapshot snapshot) => OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, reference, snapshot));
|
||||
}
|
||||
|
||||
private sealed class BatchCallbackDriver : StubDriver, IBatchSubscribable
|
||||
{
|
||||
private readonly StubHandle _handle = new();
|
||||
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
|
||||
public event EventHandler<DataChangeBatchEventArgs>? OnDataChangeBatch;
|
||||
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) => Task.FromResult<ISubscriptionHandle>(_handle);
|
||||
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
||||
public void Fire(IReadOnlyList<DataChangeItem> items) => OnDataChangeBatch?.Invoke(this, new DataChangeBatchEventArgs(_handle, items));
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataSnapshotTests
|
||||
{
|
||||
[Fact]
|
||||
public void Snapshot_freezes_samples_and_its_watermarks_cover_every_participating_partition()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 2);
|
||||
var first = HubTest.Ticket("driver", "a");
|
||||
var second = Enumerable.Range(0, 1000).Select(i => HubTest.Ticket("driver", $"other-{i}"))
|
||||
.First(t => hub.GetPartition(t.Key) != hub.GetPartition(first.Key));
|
||||
HubTest.BindAndPublish(hub, first, 1, 10);
|
||||
HubTest.BindAndPublish(hub, second, 1, 20);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([first, second], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
snapshot!.Watermarks.Count.ShouldBe(2);
|
||||
snapshot.Items[first].Sample!.Value.GetScalar().ShouldBe(10);
|
||||
snapshot.Items[second].Sample!.Value.GetScalar().ShouldBe(20);
|
||||
HubTest.Publish(hub, first, 2, 11);
|
||||
hub.ProcessPending();
|
||||
snapshot.Items[first].Sample!.Value.GetScalar().ShouldBe(10);
|
||||
snapshot.TryReadDelta(first, out var delta).ShouldBeTrue();
|
||||
using (delta!) delta!.Sample!.Value.GetScalar().ShouldBe(11);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Racing_registration_and_update_cannot_lose_the_newer_value()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "race");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
SnapshotLease? snapshot = null;
|
||||
var captured = false;
|
||||
var accepted = false;
|
||||
Parallel.Invoke(
|
||||
() => captured = hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out snapshot),
|
||||
() =>
|
||||
{
|
||||
if (hub.TryReserveIngress(source, 288, out var reservation))
|
||||
{
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2);
|
||||
accepted = reservation!.TryCommit(sample, 2);
|
||||
if (!accepted) sample.Dispose();
|
||||
}
|
||||
}
|
||||
hub.ProcessPending();
|
||||
});
|
||||
if (!accepted)
|
||||
{
|
||||
if (captured) { snapshot!.IsReset.ShouldBeTrue(); snapshot.Dispose(); }
|
||||
using var invalidated = hub.Read(source);
|
||||
invalidated.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
return;
|
||||
}
|
||||
if (!captured) return; // a reset during registration is an explicit retry boundary
|
||||
using (snapshot!)
|
||||
{
|
||||
var capturedValue = (int)snapshot!.Items[source].Sample!.Value.GetScalar();
|
||||
if (capturedValue == 1)
|
||||
{
|
||||
snapshot.TryReadDelta(source, out var delta).ShouldBeTrue();
|
||||
using (delta!) delta!.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
}
|
||||
else capturedValue.ShouldBe(2);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cancellation_and_deadline_actively_release_all_snapshot_resources()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
using var hub = HubTest.Create(clock: clock);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 9);
|
||||
hub.ProcessPending();
|
||||
var baseline = hub.Resources.RetainedBytes;
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, cancellation.Token, out var canceled).ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
|
||||
cancellation.Cancel();
|
||||
canceled!.IsReset.ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
canceled.Dispose(); // cancellation and explicit disposal are idempotent
|
||||
hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
|
||||
var shortBudget = HubTest.Budget with { Timeout = TimeSpan.FromSeconds(2) };
|
||||
hub.TryCaptureSnapshot([source], shortBudget, CancellationToken.None, out var expired).ShouldBeTrue();
|
||||
clock.Advance(TimeSpan.FromSeconds(2));
|
||||
expired!.IsReset.ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
expired.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Snapshot_admission_is_global_and_rejects_before_retaining_more_payload()
|
||||
{
|
||||
using var hub = HubTest.Create(bytes: 1700);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 5);
|
||||
hub.ProcessPending();
|
||||
var before = hub.Resources.RetainedBytes;
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var rejected).ShouldBeFalse();
|
||||
rejected.ShouldBeNull();
|
||||
hub.Resources.RetainedBytes.ShouldBe(before);
|
||||
using var read = hub.Read(source);
|
||||
read.Status.ShouldBe(DataItemStatus.ResourceExhausted);
|
||||
read.Sample.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Catch_up_overflow_resets_snapshot_instead_of_silently_losing_deltas()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var first = HubTest.Ticket("driver", "first");
|
||||
var second = HubTest.Ticket("driver", "second");
|
||||
HubTest.BindAndPublish(hub, first, 1, 1);
|
||||
HubTest.BindAndPublish(hub, second, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([first, second], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
HubTest.Publish(hub, first, 2, 2);
|
||||
HubTest.Publish(hub, second, 2, 2);
|
||||
hub.ProcessPending();
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1011
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user