diff --git a/docs/plans/evidence/grpc-data/README.md b/docs/plans/evidence/grpc-data/README.md index bdfbba558..45ce52e61 100644 --- a/docs/plans/evidence/grpc-data/README.md +++ b/docs/plans/evidence/grpc-data/README.md @@ -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 diff --git a/docs/plans/evidence/grpc-data/p04-publication-astra-review.md b/docs/plans/evidence/grpc-data/p04-publication-astra-review.md new file mode 100644 index 000000000..e76817224 --- /dev/null +++ b/docs/plans/evidence/grpc-data/p04-publication-astra-review.md @@ -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. diff --git a/scripts/validation/grpc-data/run-unit-phase.py b/scripts/validation/grpc-data/run-unit-phase.py index c96fd0b41..551c393f7 100644 --- a/scripts/validation/grpc-data/run-unit-phase.py +++ b/scripts/validation/grpc-data/run-unit-phase.py @@ -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 diff --git a/scripts/validation/grpc-data/test_unit_phase_runner.py b/scripts/validation/grpc-data/test_unit_phase_runner.py index 4f848d6de..dc169b991 100644 --- a/scripts/validation/grpc-data/test_unit_phase_runner.py +++ b/scripts/validation/grpc-data/test_unit_phase_runner.py @@ -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", diff --git a/scripts/validation/grpc-data/unit-phases.json b/scripts/validation/grpc-data/unit-phases.json index 16717596b..e3193e30f 100644 --- a/scripts/validation/grpc-data/unit-phases.json +++ b/scripts/validation/grpc-data/unit-phases.json @@ -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" ] } ], diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs index 918926023..adce29fbc 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaAddressSpaceSink.cs @@ -246,7 +246,8 @@ public interface IOpcUaAddressSpaceSink /// One value write within a batch. /// Same semantics per field as (status verbatim). 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); /// One status-only write within a batch: the /// node's current VALUE is retained and only + diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index 9af7f87d1..fe2ebe89f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -19,6 +19,28 @@ public sealed class DataValue : IDisposable { Kind = kind; _payload = payload; Dimensions = dimensions; } public DataValueKind Kind { get; } public IReadOnlyList? Dimensions { get; } + /// A conservative, allocation-free estimate of retained value storage, in bytes. + 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) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataConnection.cs index fdce2317a..3ffa5e179 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataConnection.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataConnection.cs @@ -43,3 +43,9 @@ public interface IDataConnectionFactory { IDataConnection Create(DataAuthenticatedContext context, DataTarget target); } + +/// Final-send guard for metadata and values prepared by a caller-bound connection. +public interface IDataConnectionPublicationGate +{ + bool CanPublish(ServingIdentity expectedServing); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index 8d3fd910f..99406cfd0 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -1,14 +1,24 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +/// A retained response's live publication fence and resource ownership. +public interface IDataPublicationLease : IDisposable +{ + bool IsValid { get; } +} + public sealed record BrowseRequest(DataView Parent, string? Filter, string? Continuation, DataBudget Budget); public sealed record MetadataRequest(IReadOnlyList Views, DataBudget Budget); public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? MaximumAge); public sealed record ReadRequest(IReadOnlyList Items, DataBudget Budget); /// Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality. 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); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataValueSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataValueSnapshot.cs index 9da533729..05a420364 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataValueSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataValueSnapshot.cs @@ -9,9 +9,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; /// The raw value; null when indicates Bad. /// OPC UA status code (numeric value matches the OPC UA spec). /// Driver-side timestamp when the value was sampled at the source. Null if unavailable. -/// Driver-side timestamp when the driver received / processed the value. +/// Driver-side timestamp when the driver received / processed the value, or null if unavailable. public sealed record DataValueSnapshot( object? Value, uint StatusCode, DateTime? SourceTimestampUtc, - DateTime ServerTimestampUtc); + DateTime? ServerTimestampUtc); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs index 740bd84bf..cd20b44c7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs @@ -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; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs index 3bda1808b..690b6bda9 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs @@ -20,6 +20,8 @@ public sealed record DataCallerIdentity(string Principal, string? ApiKeyId, stri /// Transport-independent data-plane grant and credential policy. public sealed class DataOperationPolicy { + /// The currently installed local authority generation, rechecked at publication boundaries. + public long AuthorityEpoch => _authority.Current.GenerationId; private readonly IDataPlaneAuthoritySource _authority; private readonly IPermissionEvaluator _evaluator; private readonly TimeProvider _clock; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataScopeSubjects.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataScopeSubjects.cs new file mode 100644 index 000000000..5c4e357ab --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataScopeSubjects.cs @@ -0,0 +1,10 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Authorization; + +/// Shared placement of equipment-owned values that are not raw-tag references. +public static class DataScopeSubjects +{ + /// Cannot match an authored name or inherit tag-only browse transit. + public const string OwnedNodeSegment = "\u0000owned"; + public static NodeScope Owned(NodeScope owner) => owner with + { Segments = Array.AsReadOnly(owner.Segments.Append(OwnedNodeSegment).ToArray()) }; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 518645561..dc9664ce0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -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); /// public override void CreateAddressSpace(IDictionary> externalReferences) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs index 09e24b6c8..947b38839 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs @@ -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. /// - internal const string OwnedNodeSegment = "\u0000owned"; + internal const string OwnedNodeSegment = DataScopeSubjects.OwnedNodeSegment; /// /// The single segment, directly under the UNS realm, that an identifier no live node holds is placed at diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/CatalogActivation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/CatalogActivation.cs index 7eba36551..d600ef054 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/CatalogActivation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/CatalogActivation.cs @@ -18,6 +18,27 @@ public sealed class CatalogActivation return new CapturedAuthority(this, current); } + /// Create an initially inactive token for a staged, not-yet-published catalog. + 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; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs new file mode 100644 index 000000000..d0234be58 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataCapabilitiesProvider.cs @@ -0,0 +1,34 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Live process provenance and implemented capability limits, independent of any mount. +public sealed class DataCapabilitiesProvider +{ + private readonly Func _serving; + private readonly Func _ready; + public DataCapabilitiesProvider(string clusterId, Func serving, Func 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().Where(x => x != DataValueKind.Unspecified).ToHashSet(), + limits, true, 1, ClusterId); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs new file mode 100644 index 000000000..910860269 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataResourceBudget.cs @@ -0,0 +1,51 @@ +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Node-wide admission limits for the source cache and retained work. +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)); + } +} + +/// Atomic accounting shared by partitions, reservations, snapshots and readers. +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."); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs new file mode 100644 index 000000000..6d4698737 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalCatalogCoordinator.cs @@ -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; + +/// Identifies one deployment attempt, including retries of the same artifact. +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); +} + +/// Coordinates desired authority, private catalog staging and served topology activation. +public sealed class LocalCatalogCoordinator +{ + private readonly object _gate = new(); + private readonly CatalogActivation _activation; + private readonly DataPlaneAuthorityState _authority; + private readonly Func _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 serving) + { + _activation = activation ?? throw new ArgumentNullException(nameof(activation)); + _authority = authority ?? throw new ArgumentNullException(nameof(authority)); + _serving = serving ?? throw new ArgumentNullException(nameof(serving)); + } + + /// Only a matching, activated candidate may be observed by data facades. + 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; + } + } + + /// Live process provenance for producers; epochs remain zero while no catalog is served. + 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; + } + } + + /// Install independently readable credentials even when catalog topology is invalid. + 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; + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs new file mode 100644 index 000000000..4c98bcd52 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs @@ -0,0 +1,30 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Strictly caller-bound local data facade; it creates no namespace projection. +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 GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) + { Check(); return _services.GetCapabilitiesAsync(_context, budget, cancellationToken); } + public Task BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) + { Check(); return _services.BrowseAsync(_context, request, cancellationToken); } + public Task>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) + { Check(); return _services.GetMetadataAsync(_context, request, cancellationToken); } + public Task> ReadAsync(ReadRequest request, CancellationToken cancellationToken) + { Check(); return _services.ReadAsync(_context, request, cancellationToken); } + public Task> WriteAsync(WriteBatch request, CancellationToken cancellationToken) + { Check(); return _services.WriteAsync(_context, request, cancellationToken); } + public Task SubscribeAsync(CancellationToken cancellationToken) + { Check(); return _services.SubscribeAsync(_context, cancellationToken); } + public ValueTask DisposeAsync() { Interlocked.Exchange(ref _disposed, 1); return ValueTask.CompletedTask; } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs new file mode 100644 index 000000000..5af31e9a9 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -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; + +/// Origin-local cached data ports; every facade retains its authenticated caller. +public sealed class LocalDataServices : IDataConnectionFactory +{ + private readonly Func _catalog; + private readonly PartitionedSampleHub _hub; + private readonly DataOperationPolicy _policy; + private readonly DataCapabilitiesProvider _capabilities; + private readonly Func? _writes; + private readonly Func? _subscriptions; + private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32); + private readonly ConditionalWeakTable _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 catalog, PartitionedSampleHub hub, + DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, + Func? writes = null, + Func? 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 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 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>> 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>>(request.Views.Select((_, i) => + new DataItemResult(i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Unavailable, null, null)).ToArray()); + var start = Clock.GetTimestamp(); + var results = new List>(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>>(results.Select(x => x with + { Status = !Ready(catalog) ? DataItemStatus.Unavailable : DataItemStatus.Denied, Value = null }).ToArray()); + return Task.FromResult>>(results); + } + + internal Task> 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>(request.Items.Select(item => + new ReadResult(item.CorrelationId, DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null)).ToArray()); + var start = Clock.GetTimestamp(); + var results = new List(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>(results); + } + catch { foreach (var result in results) result.Dispose(); throw; } + } + + internal Task 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(); + 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> 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(); var indexes = new List(); + 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 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(payload); + } + catch (Exception ex) when (ex is FormatException or JsonException) { return null; } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs new file mode 100644 index 000000000..1a6681113 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -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 +{ + /// Stable data-service realm root; its identifier kind cannot collide with an SDK string NodeId. + 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"); + } + + /// Compile origin views from the deployed snapshot using the same identity and ACL producers as the SDK. + 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((int)count); + var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>(); + var rawViewsByPath = new Dictionary(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(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 + }; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs new file mode 100644 index 000000000..62de6615b --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -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; + +/// An origin-owned view, with policy placement separate from its backing acquisition. +public sealed record LocalDataNode(string EntityKind, string EntityId, DataMetadata Metadata, + NodeScope Scope, DataView? Parent, BackingSourceKey? Source, bool Supported = true, bool SourceEnabled = true); + +/// Immutable origin-only catalog. Projected peer nodes cannot become export authority. +public sealed partial class LocalExportCatalog +{ + private readonly Dictionary<(DataAddress Address, DataRealm Realm), LocalDataNode> _nodes = new(); + private readonly Dictionary _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 nodes, IEnumerable 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(); + 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(); + 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(_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 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; + } + + /// A role-only transition changes serving provenance without freshening source acquisitions. + 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 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); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OwnedDataSample.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OwnedDataSample.cs new file mode 100644 index 000000000..b1fe1097f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OwnedDataSample.cs @@ -0,0 +1,122 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Validates borrowed driver values before creating the immutable data-plane value. +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(ReferenceEqualityComparer.Instance)) : value; + + private static Array CopyLegacyArray(Array original, Dictionary 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; +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs new file mode 100644 index 000000000..ae4806dca --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/PartitionedSampleHub.cs @@ -0,0 +1,219 @@ +using System.Collections.Concurrent; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Canonical acquisition identity, independent of any authorized view or principal. +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); +} +/// An individual binding; two bindings of the same key and generation remain distinct. +public readonly record struct SourceTicket(BackingSourceKey Key, SourceGeneration Generation) +{ + internal SourceBindingFence? Binding { get; } = new(); +} + +/// Shared producer lifetime; retirement immediately fences every source bound to this token. +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 +{ + /// On success transfers the sample; on failure it remains owned by the caller. + 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); +} + +/// A recipient-owned cache read. Dispose releases its independent sample lease and admission charge. +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; } + /// True only while the captured source, producer and partition fences remain current. + 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); + } +} + +/// +/// 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. +/// +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 _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 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(); var watermarks = new Dictionary(); var epochs = new Dictionary(); + 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(); + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs new file mode 100644 index 000000000..61e1420db --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SamplePartition.cs @@ -0,0 +1,486 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using System.Collections.Concurrent; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// One bounded source owner; no network or caller callbacks run under its lock. +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 _sources = new(); + private readonly Queue _queue = new(); + private readonly Dictionary _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 tickets, Dictionary 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> 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); } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs new file mode 100644 index 000000000..e24d8d2ab --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SnapshotLease.cs @@ -0,0 +1,91 @@ +using System.Collections.ObjectModel; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// Frozen item state. Its sample belongs to the containing snapshot. +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); } +} + +/// Retained immutable snapshots and per-partition catch-up watermarks. +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 _epochs; + private readonly Dictionary _owners; + private readonly Dictionary _positions; + private readonly Dictionary _versions; + private readonly object _gate = new(); + private CancellationTokenRegistration _cancellation; + private ITimer? _timer; + private int _released; + + internal SnapshotLease(PartitionedSampleHub hub, Dictionary items, + Dictionary watermarks, Dictionary 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(items); + Watermarks = new ReadOnlyDictionary(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 Items { get; } + public IReadOnlyDictionary 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; + } + } + } + /// Returns the latest newer sample as an independently disposable, globally charged read. + 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(); } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs new file mode 100644 index 000000000..ba45ea526 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/SourceSamplePublisher.cs @@ -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; + +/// Trusted acquisition shape; aliases share this source-level descriptor. +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); + } +} + +/// Constructs acquisition identities independently of catalog views and principals. +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; + } +} + +/// Sequences source data and lifecycle changes before the asynchronous actor boundary. +public sealed class SourceSamplePublisher +{ + private readonly ISourceSampleHub _hub; + private readonly Func _serving; + private readonly string? _originClusterId; + private readonly object _gate = new(); + private readonly Dictionary _tickets = new(); + private readonly Dictionary<(string Driver, string Reference), BackingSourceKey> _drivers = new(); + private readonly Dictionary _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 _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 _virtualRoutes = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _driverIncarnations = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _virtualIncarnations = new(StringComparer.Ordinal); + private readonly ConcurrentQueue _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 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); + } + } + + /// Synchronously invalidates a malformed callback's captured source generation. + 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; + } + } + } + /// Closes an old physical binding and opens a newer, initially unready generation. + 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; } + } + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs index 603fe32a9..8a45295ad 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DeploymentArtifact.DataConnections.cs @@ -36,6 +36,19 @@ public static partial class DeploymentArtifact internal sealed partial class ParsedDeploymentArtifact { + /// Materialize this node's eligible catalog inputs while the artifact document is alive. + internal DraftSnapshot? ParseLocalCatalogSnapshot(string nodeId) => ReadDataProjection(nodeId)?.Snapshot; + + /// Legacy artifacts and empty data sections do not require an activated data catalog. + 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(root, "UnsTagReferences"), VirtualTags = ReadTopology(root, "VirtualTags"), ScriptedAlarms = ReadTopology(root, "ScriptedAlarms"), + Scripts = ReadTopology